All files / app/features/search/state mapSearchContext.tsx

90.9% Statements 10/11
100% Branches 4/4
75% Functions 3/4
88.88% Lines 8/9

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 573x       3x   3x 3x         25x       13x                                     25x                                       25x  
import { createContext, Dispatch, ReactNode, useContext, useReducer } from "react";
import { GeocodeResult } from "utils/hooks";
import SearchFilters from "utils/searchFilters";
 
import { initialState, MapSearchAction, mapSearchReducer } from "./mapSearchReducers";
 
const MapSearchContext = createContext(initialState);
const MapSearchDispatchContext = createContext<Dispatch<MapSearchAction>>(() => {
  throw new Error("MapSearchDispatchContext used outside of provider");
});
 
function useMapSearchState() {
  return useContext(MapSearchContext);
}
 
function useMapSearchDispatch() {
  return useContext(MapSearchDispatchContext);
}
 
// This is the pattern of using Reducer with Context we're using here:
// https://react.dev/learn/scaling-up-with-reducer-and-context
// @TODO(NA): Keep the search state (place, area, filters, page) in sync with the URL, so searches can be shared,
// survive a refresh and work with the back button. pages/search.tsx already reads some of it on load.
 
function MapSearchProvider({
  children,
  initialBbox,
  initialLocationName,
  initialFilters,
}: {
  children: ReactNode;
  initialBbox: GeocodeResult["bbox"] | undefined;
  initialLocationName: string | undefined;
  initialFilters: SearchFilters;
}) {
  const [mapSearchState, dispatch] = useReducer(mapSearchReducer, {
    ...initialState,
    hasActiveFilters: Object.keys(initialFilters).length > 0 ? true : false,
    // getHasActiveFilters diffs against initialState, so missing keys would read as active
    filters: { ...initialState.filters, ...initialFilters },
    search: {
      query: initialLocationName,
      bbox: initialBbox,
    },
    // a link to a place's area, e.g. /search?location=Berlin&bbox=…, names that place in the results line
    uiOnly: { ...initialState.uiOnly, placeName: initialBbox ? initialLocationName : undefined },
  });
 
  return (
    <MapSearchContext.Provider value={mapSearchState}>
      <MapSearchDispatchContext.Provider value={dispatch}>{children}</MapSearchDispatchContext.Provider>
    </MapSearchContext.Provider>
  );
}
 
export { MapSearchProvider, useMapSearchDispatch, useMapSearchState };