All files / app/utils hooks.ts

84.88% Statements 73/86
33.33% Branches 4/12
87.5% Functions 14/16
87.65% Lines 71/81

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  67x 67x 67x                 67x 67x 67x         67x       67x                                 4410x   4410x 886x 886x 886x       4410x             5302x   5302x   372x 362x           5302x       49x 49x 49x                     67x   67x 447x     447x 447x 447x       447x         447x   12x     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         447x                       227x   227x 28x           28x               28x 28x 28x 28x 28x           448x 50x 3964x 3962x 228x    
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 { useTranslation } from "react-i18next";
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",
];
 
/**
 * @deprecated use useIsClient instead. This pattern should only be used as a last resort
 * (e.g. to avoid hydration errors) as in most cases, render logic should not depend on the client being mounted.
 */
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];
}
 
function useIsClient() {
  const [isClient, setIsClient] = useState(false);
  useEffect(() => setIsClient(true), []);
  return isClient;
}
 
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 {
    i18n: { languages: locales },
  } = useTranslation();
  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);
 
      // Refer to https://nominatim.org/release-docs/latest/api/Search/
      const queryArgs = new URLSearchParams({
        format: "jsonv2",
        q: value,
        addressdetails: "1", // include a breakdown of the address into elements
        "accept-language": locales.join(","),
      });
 
      const url = `${NOMINATIM_URL!}search?${queryArgs}`;
      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);
    },
    [locales, 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,
  useIsClient,
  useIsMounted,
  useSafeState,
  useUnsavedChangesWarning,
};