All files / app/utils hooks.ts

81.94% Statements 59/72
31.25% Branches 5/16
81.81% Functions 9/11
84.61% Lines 55/65

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  11x 11x 11x 11x 11x 11x 11x       11x                         49x 49x 49x                     11x   11x     334x 334x 334x 334x   334x   15x     15x 15x 15x     15x             15x 15x           15x 15x 15x   15x   13x   13x     13x 13x 13x 13x 13x 13x   13x       33x       13x             13x     2x         2x   15x         334x                       67x   67x 28x           28x               28x 28x 28x 28x 28x         334x  
import { Coordinates } from "features/search/utils/constants";
import { LngLat } from "maplibre-gl";
import { useRouter } from "next/router";
import Sentry from "platform/sentry";
import { useCallback, useEffect, 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",
];
 
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 {
    i18n: { languages: locales },
  } = useTranslation();
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | undefined>(undefined);
  const [results, setResults] = useState<GeocodeResult[] | undefined>(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) => {
      if (!isDirty) return;
      e.preventDefault();
      e.returnValue = warningMessage;
      return;
    };
    const handleBrowseAway = () => {
      if (!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
      if (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, useUnsavedChangesWarning };