All files / src/hooks useRerouting.ts

94.2% Statements 130/138
81.25% Branches 39/48
100% Functions 22/22
96.72% Lines 118/122

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226                              1x 1x 1x 1x   1x 9x   18x       25x   25x 25x 25x 25x 25x 25x 25x   83x 25x     86x 86x 86x   87x   100x 100x 100x   86x   25x 17x 7x 7x 7x     10x 10x 10x     10x 1x 1x 1x     9x 8x 8x 8x 8x 8x   8x 8x 1x 1x 1x             25x 11x   11x 11x 11x 2x 2x 2x     9x 9x 4x 4x 4x     5x 5x 5x 5x   5x 5x           5x   5x   5x   4x   4x   4x   4x   4x       4x 4x 4x     4x 4x   1x   5x 5x 5x 5x 5x                     25x   71x 7x 7x 7x     64x   43x 43x 43x   43x   43x   43x 36x 36x       11x 11x     7x 7x           25x 15x     25x 14x   7x 56x     7x     25x 14x 7x 7x 7x 7x             25x    
import { useEffect, useRef, useCallback, useState } from "react";
import polyline from "@mapbox/polyline";
import { getDistanceToPolyline } from "../utils/locationUtils";
import { getAllOutdoorDirectionsInfo } from "../api";
import useLocationStore from "./useLocationStore";
import useNavigationState from "./useNavigationState";
import useNavigationConfig from "./useNavigationConfig";
import {
  LabeledCoordinate,
  useNavigationEndpointsStore,
} from "./useNavigationEndpoints";
import useNavigationInfo from "./useNavigationInfo";
import useNavigationProgress from "./useNavigationProgress";
import { Coordinate, TRANSPORT_MODE_API_MAP } from "../type";
 
const OFF_ROUTE_THRESHOLD_METERS = 50;
const REROUTE_COOLDOWN_MS = 15000;
const OFF_ROUTE_CONFIRMATION_COUNT = 3;
const OFF_ROUTE_CHECK_INTERVAL_MS = 1000;
 
const decodePolyline = (encoded: string): Coordinate[] => {
  return polyline
    .decode(encoded)
    .map(([lat, lng]) => ({ latitude: lat, longitude: lng }));
};
 
export default function useRerouting() {
  const [isRerouting, setIsRerouting] = useState(false);
 
  const offRouteCountRef = useRef(0);
  const reroutingRef = useRef(false);
  const lastRerouteTimeRef = useRef<number>(0);
  const routeCoordsRef = useRef<Coordinate[]>([]);
  const stepStartIndicesRef = useRef<number[]>([]);
  const isOffRouteRef = useRef(false);
  const navigationSessionRef = useRef(0);
 
  const currentLocation = useLocationStore((s) => s.currentLocation);
  const { isNavigating } = useNavigationState();
 
  // Use selectors for stable references
  const allOutdoorRoutes = useNavigationConfig((s) => s.allOutdoorRoutes);
  const setAllOutdoorRoutes = useNavigationConfig((s) => s.setAllOutdoorRoutes);
  const navigationMode = useNavigationConfig((s) => s.navigationMode);
 
  const setOrigin = useNavigationEndpointsStore((s) => s.setOrigin);
 
  const setPathDistance = useNavigationInfo((s) => s.setPathDistance);
  const setPathDuration = useNavigationInfo((s) => s.setPathDuration);
  const setIsLoading = useNavigationInfo((s) => s.setIsLoading);
 
  const resetProgress = useNavigationProgress((s) => s.resetProgress);
 
  useEffect(() => {
    if (!allOutdoorRoutes?.length) {
      routeCoordsRef.current = [];
      stepStartIndicesRef.current = [];
      return;
    }
 
    const apiMode = TRANSPORT_MODE_API_MAP[navigationMode];
    const route = allOutdoorRoutes.find(
      (r) => r.transportMode?.toLowerCase() === apiMode?.toLowerCase(),
    );
 
    if (!route) {
      routeCoordsRef.current = [];
      stepStartIndicesRef.current = [];
      return;
    }
 
    if (route.steps?.length) {
      const coords: Coordinate[] = [];
      const starts: number[] = [];
      for (const step of route.steps) {
        starts.push(coords.length);
        coords.push(...decodePolyline(step.polyline));
      }
      routeCoordsRef.current = coords;
      stepStartIndicesRef.current = starts;
    } else if (route.polyline) {
      routeCoordsRef.current = decodePolyline(route.polyline);
      stepStartIndicesRef.current = [0];
    } else E{
      routeCoordsRef.current = [];
      stepStartIndicesRef.current = [];
    }
  }, [allOutdoorRoutes, navigationMode]);
 
  const triggerReroute = useCallback(async () => {
    Iif (reroutingRef.current) return;
 
    const location = useLocationStore.getState().currentLocation;
    const dest = useNavigationEndpointsStore.getState().destination;
    if (!location || !dest) {
      isOffRouteRef.current = false;
      offRouteCountRef.current = 0;
      return;
    }
 
    const now = Date.now();
    if (now - lastRerouteTimeRef.current < REROUTE_COOLDOWN_MS) {
      isOffRouteRef.current = false;
      offRouteCountRef.current = 0;
      return;
    }
 
    const sessionAtStart = navigationSessionRef.current;
    reroutingRef.current = true;
    setIsRerouting(true);
    setIsLoading(true);
 
    try {
      const newOrigin: LabeledCoordinate = {
        latitude: location.latitude,
        longitude: location.longitude,
        label: "Current Location",
      };
 
      Iif (navigationSessionRef.current !== sessionAtStart) return;
 
      setOrigin(newOrigin);
 
      const routes = await getAllOutdoorDirectionsInfo(newOrigin, dest);
 
      Iif (navigationSessionRef.current !== sessionAtStart) return;
 
      setAllOutdoorRoutes(routes);
 
      const mode = useNavigationConfig.getState().navigationMode;
      const activeRoute =
        routes.find(
          (r) =>
            r.transportMode?.toLowerCase() ===
            TRANSPORT_MODE_API_MAP[mode]?.toLowerCase(),
        ) || routes[0];
 
      Eif (activeRoute) {
        setPathDistance(activeRoute.distance);
        setPathDuration(activeRoute.duration);
      }
 
      lastRerouteTimeRef.current = Date.now();
      resetProgress();
    } catch (error) {
      console.error("[Rerouting] Reroute failed:", error);
    } finally {
      reroutingRef.current = false;
      isOffRouteRef.current = false;
      offRouteCountRef.current = 0;
      setIsRerouting(false);
      setIsLoading(false);
    }
  }, [
    setOrigin,
    setAllOutdoorRoutes,
    setPathDistance,
    setPathDuration,
    setIsLoading,
    resetProgress,
  ]);
 
  const evaluateOffRoute = useCallback(
    (location: Coordinate | null) => {
      if (!isNavigating || !location) {
        offRouteCountRef.current = 0;
        isOffRouteRef.current = false;
        return;
      }
 
      if (routeCoordsRef.current.length === 0 || reroutingRef.current) return;
 
      const stepIdx = useNavigationProgress.getState().currentStepIndex;
      const startAt = stepStartIndicesRef.current[stepIdx] ?? 0;
      const remainingCoords = routeCoordsRef.current.slice(startAt);
 
      Iif (remainingCoords.length === 0) return;
 
      const distance = getDistanceToPolyline(location, remainingCoords);
 
      if (distance > OFF_ROUTE_THRESHOLD_METERS) {
        offRouteCountRef.current += 1;
        if (
          offRouteCountRef.current >= OFF_ROUTE_CONFIRMATION_COUNT &&
          !isOffRouteRef.current
        ) {
          isOffRouteRef.current = true;
          triggerReroute();
        }
      } else {
        offRouteCountRef.current = 0;
        isOffRouteRef.current = false;
      }
    },
    [isNavigating, triggerReroute],
  );
 
  useEffect(() => {
    evaluateOffRoute(currentLocation);
  }, [currentLocation, evaluateOffRoute]);
 
  useEffect(() => {
    if (!isNavigating) return;
 
    const interval = setInterval(() => {
      evaluateOffRoute(useLocationStore.getState().currentLocation);
    }, OFF_ROUTE_CHECK_INTERVAL_MS);
 
    return () => clearInterval(interval);
  }, [isNavigating, evaluateOffRoute]);
 
  useEffect(() => {
    if (!isNavigating) {
      navigationSessionRef.current += 1;
      isOffRouteRef.current = false;
      offRouteCountRef.current = 0;
      Iif (reroutingRef.current) {
        reroutingRef.current = false;
        setIsRerouting(false);
      }
    }
  }, [isNavigating]);
 
  return { isRerouting };
}