All files / app/features/search SearchPage.tsx

86.3% Statements 63/73
87.5% Branches 28/32
53.84% Functions 7/13
88.23% Lines 60/68

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 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 2701x 1x 1x 1x 1x 1x           1x 1x 1x   1x 1x   1x 1x 1x 1x 1x 1x                                                         10x                       10x                   5x 10x 10x   10x 10x   10x   10x     10x 9x                                             10x   10x 10x 10x 9x 9x 9x 5x 5x                                                                   10x         10x         10x       10x       10x   3x     3x         3x 3x               3x 2x               10x 2x 2x   2x   2x 1x 1x 1x     2x 1x               10x 10x                                                                                                
import { styled } from "@mui/material";
import HtmlMeta from "components/HtmlMeta";
import { DEFAULT_DRAWER_WIDTH } from "components/ResizeableDrawer";
import { useLogEvent } from "features/analytics/hooks";
import { SearchAnalyticsProvider } from "features/analytics/searchAnalyticsContext";
import { getOrCreateSearchSessionId } from "features/analytics/searchAttribution";
import {
  MapViewOptions,
  MapViews,
  MAX_MAP_ZOOM_LEVEL_FOR_SEARCH,
  SleepingArrangementOptions,
} from "features/search/utils/constants";
import { useTranslation } from "i18n";
import { GLOBAL, SEARCH } from "i18n/namespaces";
import { HostingStatus, MeetupStatus } from "proto/api_pb";
import { useEffect, useMemo, useRef, useState } from "react";
import { LngLatLike, MapProvider, MapRef } from "react-map-gl/maplibre";
 
import { useUserSearch } from "./hooks/useUserSearch";
import MapSearchContent from "./MapSearchContent";
import SearchControls from "./SearchControls";
import { useMapSearchState } from "./state/mapSearchContext";
import { useMapSearchActions } from "./state/useMapSearchActions";
import { getMapBounds } from "./utils/mapUtils";
 
/**
 * See map search architecture diagram and a description of the main concepts here:
 * docs/architecture/frontend/map-search.md
 */
 
export type FilterOptions = {
  acceptsKids?: boolean;
  acceptsPets?: boolean;
  acceptsLastMinRequests?: boolean;
  ageMin?: number | undefined;
  ageMax?: number | undefined;
  showEmptyProfile?: boolean;
  drinkingAllowed?: boolean | undefined;
  hasReferences?: boolean;
  hasStrongVerification?: boolean;
  hostingStatus?: HostingStatus[];
  meetupStatus?: MeetupStatus[];
  numGuests?: number;
  lastActive?: number;
  lng?: number;
  lat?: number;
  selectedUserId?: number;
  sleepingArrangement?: SleepingArrangementOptions[];
  smokesAtHome?: boolean | undefined;
  sameGenderOnly?: boolean;
};
 
const SearchPageContainer = styled("div")(({ theme }) => ({
  display: "flex",
  flexDirection: "column",
  height: "100%",
  position: "relative",
 
  [theme.breakpoints.down("md")]: {
    display: "grid",
    gridTemplateRows: "auto 1fr",
  },
}));
 
const SearchControlsWrapper = styled("div")(({ theme }) => ({
  [theme.breakpoints.down("md")]: {
    display: "flex",
    flexDirection: "column",
  },
}));
 
/**
 * Search page, creates the state, obtains the users, renders all its sub-components
 */
export default function SearchPage() {
  const { t } = useTranslation([GLOBAL, SEARCH]);
  const mapRef = useRef<MapRef | null>(null);
 
  const [drawerWidth, setDrawerWidth] = useState<number>(DEFAULT_DRAWER_WIDTH);
  const [mapView, setMapView] = useState<MapViewOptions>(MapViews.MAP_AND_LIST);
 
  const mapSearchState = useMapSearchState();
  const { setPageNumber, setMapQueryArea, setMoveMapUIOnly, setShowSearchThisAreaButton, setSelectedUserId } =
    useMapSearchActions();
 
  // useMemo to avoid unnecessary object reference changes - causing unnecessary rerenders
  const searchParams = useMemo(
    () => ({
      ...mapSearchState.filters,
      ...mapSearchState.search,
      // Don't send query when bbox is present (location search vs keyword search)
      query: mapSearchState.search.bbox ? undefined : mapSearchState.search.query,
      selectedUserId: mapSearchState.shouldSearchByUserId ? mapSearchState.selectedUserId : undefined,
    }),
    [mapSearchState.filters, mapSearchState.search, mapSearchState.selectedUserId, mapSearchState.shouldSearchByUserId],
  );
 
  const {
    error,
    fetchNextPage,
    fetchPreviousPage,
    isLoading,
    hasNextPage,
    hasPreviousPage,
    currentRange,
    totalFilteredItems,
    totalUnfilteredItems,
    users,
    searchQueryId,
    bfcSearchId,
  } = useUserSearch(searchParams, mapSearchState);
 
  const logEvent = useLogEvent();
  const lastRenderedKeyRef = useRef<string | null>(null);
  useEffect(() => {
    Iif (!users || isLoading) return;
    const key = `${searchQueryId}:${mapSearchState.pageNumber}`;
    if (lastRenderedKeyRef.current === key) return;
    lastRenderedKeyRef.current = key;
    logEvent("search.results_rendered", {
      search_session_id: getOrCreateSearchSessionId(),
      search_query_id: searchQueryId,
      bfc_search_id: bfcSearchId,
      page_number: mapSearchState.pageNumber,
      num_results: users.length,
      total_items: totalFilteredItems,
      total_unfiltered_items: totalUnfilteredItems,
      has_next_page: hasNextPage,
      has_previous_page: hasPreviousPage,
      map_view: mapView,
      query: mapSearchState.search.query ?? null,
      bbox: mapSearchState.search.bbox ?? null,
      zoom: mapSearchState.uiOnly.zoom,
      filters: mapSearchState.filters,
    });
  }, [
    users,
    isLoading,
    searchQueryId,
    bfcSearchId,
    mapSearchState.pageNumber,
    mapSearchState.search.query,
    mapSearchState.search.bbox,
    mapSearchState.uiOnly.zoom,
    mapSearchState.filters,
    hasNextPage,
    hasPreviousPage,
    totalFilteredItems,
    totalUnfilteredItems,
    mapView,
    logEvent,
  ]);
 
  const handleLoadPreviousPage = () => {
    fetchPreviousPage();
    setPageNumber(mapSearchState.pageNumber - 1);
  };
 
  const handleLoadNextPage = () => {
    fetchNextPage();
    setPageNumber(mapSearchState.pageNumber + 1);
  };
 
  const handleDrawerWidthChange = (width: number) => {
    setDrawerWidth(width);
  };
 
  const handleSetMapView = (view: MapViewOptions) => {
    setMapView(view);
  };
 
  const handleZoomIn = (newZoom: number, center?: LngLatLike, isLocationSearch: boolean = false) => {
    const didCrossSearchThreshold =
      newZoom >= MAX_MAP_ZOOM_LEVEL_FOR_SEARCH && mapSearchState.uiOnly.zoom < MAX_MAP_ZOOM_LEVEL_FOR_SEARCH;
 
    // If it's the first zoom within threshold, set the map bounds so the user pins load
    if (
      didCrossSearchThreshold &&
      !isLocationSearch && // need to pass since it's zoomed before state is set
      !mapSearchState.search.query // not keyword search bc already has filter then
    ) {
      const bbox = getMapBounds(mapRef);
      setMapQueryArea(bbox, newZoom, didCrossSearchThreshold);
    } else E{
      setMoveMapUIOnly({ zoom: newZoom });
    }
 
    // Skip a no-center call already at the target zoom (the map's own zoomend echo; equal because the
    // map is uncontrolled). A zoomend fired while another animation is interrupted would nest an
    // easeTo whose frame gets orphaned, freezing the map (Sentry FRONTEND-6E3/6E4).
    if (center || newZoom !== mapRef.current?.getZoom()) {
      mapRef.current?.easeTo({
        center,
        zoom: newZoom,
        duration: 2000,
      });
    }
  };
 
  const handleZoomOut = (newZoom: number) => {
    const didZoomOutWithinThreshold = newZoom >= MAX_MAP_ZOOM_LEVEL_FOR_SEARCH;
    const didZoomBelowThreshold = newZoom < MAX_MAP_ZOOM_LEVEL_FOR_SEARCH;
 
    setSelectedUserId(undefined);
 
    if (didZoomBelowThreshold) {
      setMapQueryArea(undefined, newZoom);
    } else Eif (didZoomOutWithinThreshold) {
      setShowSearchThisAreaButton(true);
    }
 
    if (newZoom !== mapRef.current?.getZoom()) {
      mapRef.current?.easeTo({
        zoom: newZoom,
        duration: 2000,
      });
    }
  };
 
  // here so both the search bar and the results line can open the filters
  const [isFiltersOpen, setIsFiltersOpen] = useState(false);
  const handleOpenFilters = () => setIsFiltersOpen(true);
 
  return (
    <SearchPageContainer>
      <MapProvider>
        <HtmlMeta title={t("global:nav.map_search")} />
        <SearchControlsWrapper>
          <SearchControls
            drawerWidth={drawerWidth}
            isFiltersOpen={isFiltersOpen}
            mapRef={mapRef}
            mapView={mapView}
            onCloseFilters={() => setIsFiltersOpen(false)}
            onOpenFilters={handleOpenFilters}
            onSetMapView={handleSetMapView}
            onZoomIn={handleZoomIn}
          />
        </SearchControlsWrapper>
        <SearchAnalyticsProvider
          searchQueryId={searchQueryId}
          bfcSearchId={bfcSearchId}
          pageNumber={mapSearchState.pageNumber}
        >
          <MapSearchContent
            error={error}
            onOpenFilters={handleOpenFilters}
            drawerWidth={drawerWidth}
            hasPreviousPage={hasPreviousPage}
            hasNextPage={hasNextPage}
            isLoading={isLoading}
            mapRef={mapRef}
            mapView={mapView}
            currentRange={currentRange}
            onDrawerWidthChange={handleDrawerWidthChange}
            onLoadPreviousPage={handleLoadPreviousPage}
            onLoadNextPage={handleLoadNextPage}
            onSetMapView={handleSetMapView}
            onZoomIn={handleZoomIn}
            onZoomOut={handleZoomOut}
            totalFilteredItems={totalFilteredItems}
            totalUnfilteredItems={totalUnfilteredItems}
            users={users}
          />
        </SearchAnalyticsProvider>
      </MapProvider>
    </SearchPageContainer>
  );
}