All files / app/utils hooks.ts

83.33% Statements 65/78
33.33% Branches 4/12
85.71% Functions 12/14
86.48% Lines 64/74

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  59x 59x 59x                 59x 59x         59x       59x                         2585x   2585x 570x 570x 570x       2585x             3461x   3461x   322x 313x           3461x                     59x   59x 439x 439x 439x       439x         439x   12x     12x 12x 12x 12x     12x           12x 12x 12x   12x   10x   10x     10x 10x 10x 10x 10x 10x   10x             27x       10x             10x     2x         2x   12x         439x                       220x   220x 25x           25x               25x 25x 25x 25x 25x           440x 2147x 2145x 221x    
import { Coordinates } from "features/search/utils/constants";
import { LngLat } from "maplibre-gl";
import { useRouter } from "next/router";
import Sentry from "platform/sentry";
import {
  Dispatch,
  MutableRefObject,
  SetStateAction,
  useCallback,
  useEffect,
  useRef,
  useState,
} from "react";
import { service } from "service";
import {
  filterDuplicatePlaces,
  NominatimPlace,
  simplifyPlaceDisplayName,
} from "utils/nominatim";
 
// Locations having one of these keys are considered non-regions.
// https://nominatim.org/release-docs/latest/api/Output/#addressdetails
const nonRegionKeys = [
  "municipality",
  "city",
  "town",
  "village",
  "city_district",
  "district",
  "borough",
  "suburb",
  "subdivision",
];
 
function useIsMounted() {
  const isMounted = useRef(false);
 
  useEffect(() => {
    isMounted.current = true;
    return () => {
      isMounted.current = false;
    };
  }, []);
 
  return isMounted;
}
 
function useSafeState<State>(
  isMounted: MutableRefObject<boolean>,
  initialState: State | (() => State),
): [State, Dispatch<SetStateAction<State>>] {
  const [state, setState] = useState(initialState);
 
  const safeSetState = useCallback(
    (newState: SetStateAction<State>) => {
      if (isMounted.current) {
        setState(newState);
      }
    },
    [isMounted],
  );
 
  return [state, safeSetState];
}
 
export interface GeocodeResult {
  name: string;
  simplifiedName: string;
  location: LngLat;
  bbox: Coordinates;
  isRegion?: boolean;
}
 
const NOMINATIM_URL = process.env.NEXT_PUBLIC_NOMINATIM_URL;
 
const useGeocodeQuery = () => {
  const isMounted = useIsMounted();
  const [isLoading, setIsLoading] = useSafeState(isMounted, false);
  const [error, setError] = useSafeState<string | undefined>(
    isMounted,
    undefined,
  );
  const [results, setResults] = useSafeState<GeocodeResult[] | undefined>(
    isMounted,
    undefined,
  );
 
  const query = useCallback(
    async (value: string) => {
      Iif (!value) {
        return;
      }
      setIsLoading(true);
      setError(undefined);
      setResults(undefined);
      const url = `${NOMINATIM_URL!}search?format=jsonv2&q=${encodeURIComponent(
        value,
      )}&addressdetails=1`;
      const fetchOptions = {
        headers: {
          Accept: "application/json",
        },
        method: "GET",
      };
      try {
        const startTime = performance.now();
        const response = await fetch(url, fetchOptions);
 
        if (!response.ok) throw Error(await response.text());
 
        const nominatimResults: NominatimPlace[] = await response.json();
 
        Iif (nominatimResults.length === 0) {
          setResults([]);
        } else {
          const filteredResults = filterDuplicatePlaces(nominatimResults);
          const formattedResults = filteredResults.map((result) => {
            const firstElem = result["boundingbox"].shift() as number;
            const lastElem = result["boundingbox"].pop() as number;
            result["boundingbox"].push(firstElem);
            result["boundingbox"].unshift(lastElem);
 
            return {
              location: new LngLat(
                Number(result["lon"]),
                Number(result["lat"]),
              ),
              name: result["display_name"],
              simplifiedName: simplifyPlaceDisplayName(result),
              isRegion: !nonRegionKeys.some((k) => k in result.address),
              bbox: result["boundingbox"],
            };
          });
          service.bugs.geolocationSearchInfo({
            searchString: value,
            nominatimResultJson: JSON.stringify(nominatimResults),
            formattedResultJson: JSON.stringify(formattedResults),
            durationMs: performance.now() - startTime,
          });
 
          setResults(formattedResults);
        }
      } catch (e) {
        Sentry.captureException(e, {
          tags: {
            hook: "useGeocodeQuery",
          },
        });
        setError(e instanceof Error ? e.message : "");
      }
      setIsLoading(false);
    },
    [setError, setIsLoading, setResults],
  );
 
  return { isLoading, error, results, query };
};
 
function useUnsavedChangesWarning({
  isDirty,
  isSubmitted,
  warningMessage,
}: {
  isDirty: boolean;
  isSubmitted: boolean;
  warningMessage: string;
}) {
  const router = useRouter();
  // https://github.com/vercel/next.js/issues/2694#issuecomment-732990201
  useEffect(() => {
    const handleWindowClose = (e: BeforeUnloadEvent) => {
      Iif (!isDirty) return;
      e.preventDefault();
      e.returnValue = warningMessage;
      return;
    };
    const handleBrowseAway = () => {
      Iif (!isDirty || isSubmitted) return;
      // Note: window.confirm() shows browser's default "The page at [url] says:" title
      // This cannot be customized as next.js pages router does not offer useBlocker hook
      Iif (window.confirm(warningMessage)) return;
      router.events.emit("routeChangeError");
      throw Error("Cancelled due to unsaved changes");
    };
    window.addEventListener("beforeunload", handleWindowClose);
    router.events.on("routeChangeStart", handleBrowseAway);
    return () => {
      window.removeEventListener("beforeunload", handleWindowClose);
      router.events.off("routeChangeStart", handleBrowseAway);
    };
  }, [isDirty, router.events, isSubmitted, warningMessage]);
}
 
export {
  useGeocodeQuery,
  useIsMounted,
  useSafeState,
  useUnsavedChangesWarning,
};