All files / app/features/search SearchPage.tsx

95.23% Statements 40/42
59.25% Branches 16/27
85.71% Functions 6/7
95.12% Lines 39/41

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 2561x 1x 1x   1x 1x 1x     1x         1x 1x     1x 1x 1x               2x                                                                               2x             3x 3x 3x 3x 3x 3x     3x 3x             3x 3x     3x   3x 3x     3x 3x       3x     3x                             2x                               1x         3x 2x           3x 2x 2x                                           3x                                                                                                                                                              
import { Collapse, useMediaQuery, useTheme } from "@mui/material";
import makeStyles from "@mui/styles/makeStyles";
import HtmlMeta from "components/HtmlMeta";
import { Coordinates } from "features/search/constants";
import { useTranslation } from "i18n";
import { GLOBAL, SEARCH } from "i18n/namespaces";
import { LngLat, Map as MaplibreMap } from "maplibre-gl";
import { HostingStatus, User } from "proto/api_pb";
import { UserSearchRes } from "proto/search_pb";
import { useEffect, useRef, useState } from "react";
import {
  QueryClient,
  QueryClientProvider,
  useInfiniteQuery,
} from "react-query";
import { service } from "service";
import { GeocodeResult } from "utils/hooks";
 
import FilterDialog from "./FilterDialog";
import MapWrapper from "./MapWrapper";
import SearchResultsList from "./SearchResultsList";
 
export type TypeHostingStatusOptions = Exclude<
  HostingStatus,
  | HostingStatus.HOSTING_STATUS_UNKNOWN
  | HostingStatus.HOSTING_STATUS_UNSPECIFIED
>[];
 
const useStyles = makeStyles((theme) => ({
  container: {
    display: "flex",
    alignContent: "stretch",
    flexDirection: "column-reverse",
    position: "fixed",
    top: theme.shape.navPaddingXs,
    left: 0,
    right: 0,
    bottom: 0,
    [theme.breakpoints.up("sm")]: {
      top: theme.shape.navPaddingSmUp,
    },
    [theme.breakpoints.up("md")]: {
      flexDirection: "row",
    },
  },
  mapContainer: {
    flexGrow: 1,
    position: "relative",
  },
  mobileCollapse: {
    flexShrink: 0,
    overflowY: "hidden",
  },
  searchMobile: {
    position: "absolute",
    top: theme.spacing(1.5),
    left: "auto",
    right: 52,
    display: "flex",
    "& .MuiInputBase-root": {
      backgroundColor: "rgba(255, 255, 255, 0.8)",
    },
  },
}));
 
/**
 * Search page, creates the state, obtains the users, renders all its sub-components
 */
export default function SearchPage({
  locationName,
  bbox,
}: {
  locationName: string;
  bbox: Coordinates;
}) {
  const { t } = useTranslation([GLOBAL, SEARCH]);
  const queryClient = new QueryClient();
  const classes = useStyles();
  const theme = useTheme();
  const map = useRef<MaplibreMap>();
  const isMobile = useMediaQuery(theme.breakpoints.down("md"));
 
  // State
  const [wasSearchPerformed, setWasSearchPerformed] = useState(false);
  const [locationResult, setLocationResult] = useState<GeocodeResult>({
    bbox: bbox,
    isRegion: false,
    location: new LngLat(0, 0),
    name: locationName,
    simplifiedName: locationName,
  });
  const [queryName, setQueryName] = useState<string>("");
  const [searchType, setSearchType] = useState<"location" | "keyword">(
    "location"
  );
  const [lastActiveFilter, setLastActiveFilter] = useState(0);
  const [hostingStatusFilter, setHostingStatusFilter] =
    useState<TypeHostingStatusOptions>([]);
  const [numberOfGuestFilter, setNumberOfGuestFilter] = useState<
    number | undefined
  >(undefined);
  const [completeProfileFilter, setCompleteProfileFilter] = useState(false);
  const [selectedResult, setSelectedResult] = useState<
    Pick<User.AsObject, "userId" | "lng" | "lat"> | undefined
  >();
 
  const [isFiltersOpen, setIsFiltersOpen] = useState(false);
 
  // Loads the list of users
  const { data, error, isLoading, isFetching, hasNextPage } = useInfiniteQuery<
    UserSearchRes.AsObject,
    Error
  >(
    [
      "userSearch",
      queryName,
      locationResult?.name,
      locationResult?.bbox,
      lastActiveFilter,
      hostingStatusFilter,
      numberOfGuestFilter,
      completeProfileFilter,
    ],
    ({ pageParam }) => {
      return service.search.userSearch(
        {
          query: queryName,
          bbox: locationResult.bbox,
          lastActive: lastActiveFilter === 0 ? undefined : lastActiveFilter,
          hostingStatusOptions:
            hostingStatusFilter.length === 0 ? undefined : hostingStatusFilter,
          numGuests: numberOfGuestFilter,
          completeProfile:
            completeProfileFilter === false ? undefined : completeProfileFilter,
        },
        pageParam
      );
    },
    {
      getNextPageParam: (lastPage) =>
        lastPage.nextPageToken ? lastPage.nextPageToken : undefined,
    }
  );
 
  // Relocate map everytime boundingbox changes
  useEffect(() => {
    map.current?.fitBounds(locationResult.bbox);
  }, [locationResult?.bbox]);
 
  /**
   * Tracks whether a search was perform after the first render (always show all the users of the platform on the first render)
   */
  useEffect(() => {
    if (!wasSearchPerformed) {
      Iif (
        lastActiveFilter !== 0 ||
        hostingStatusFilter.length !== 0 ||
        numberOfGuestFilter !== undefined ||
        completeProfileFilter !== false ||
        queryName !== "" ||
        (locationResult.location.lng !== 0 && locationResult.location.lat !== 0)
      ) {
        setWasSearchPerformed(true);
      }
    }
  }, [
    lastActiveFilter,
    hostingStatusFilter,
    numberOfGuestFilter,
    completeProfileFilter,
    wasSearchPerformed,
    queryName,
    locationResult.location.lng,
    locationResult.location.lat,
  ]);
 
  const errorMessage = error?.message;
 
  return (
    <QueryClientProvider client={queryClient}>
      <HtmlMeta title={t("global:nav.map_search")} />
      <div className={classes.container}>
        {/* Desktop */}
        {!isMobile && (
          <SearchResultsList
            searchType={searchType}
            setSearchType={setSearchType}
            locationResult={locationResult}
            setLocationResult={setLocationResult}
            queryName={queryName}
            setQueryName={setQueryName}
            results={data}
            error={errorMessage}
            hasNext={hasNextPage}
            selectedResult={selectedResult}
            setSelectedResult={setSelectedResult}
            isLoading={isLoading || isFetching}
          />
        )}
        {/* Mobile */}
        {isMobile && (
          <Collapse
            in={wasSearchPerformed || !!selectedResult}
            timeout={theme.transitions.duration.standard}
            className={classes.mobileCollapse}
          >
            <SearchResultsList
              searchType={searchType}
              setSearchType={setSearchType}
              locationResult={locationResult}
              setLocationResult={setLocationResult}
              queryName={queryName}
              setQueryName={setQueryName}
              results={data}
              error={errorMessage}
              hasNext={hasNextPage}
              selectedResult={selectedResult}
              setSelectedResult={setSelectedResult}
              isLoading={isLoading || isFetching}
            />
          </Collapse>
        )}
        <FilterDialog
          isOpen={isFiltersOpen}
          queryName={queryName}
          setQueryName={setQueryName}
          onClose={() => setIsFiltersOpen(false)}
          setLocationResult={setLocationResult}
          lastActiveFilter={lastActiveFilter}
          setLastActiveFilter={setLastActiveFilter}
          hostingStatusFilter={hostingStatusFilter}
          setHostingStatusFilter={setHostingStatusFilter}
          completeProfileFilter={completeProfileFilter}
          setCompleteProfileFilter={setCompleteProfileFilter}
          numberOfGuestFilter={numberOfGuestFilter}
          setNumberOfGuestFilter={setNumberOfGuestFilter}
        />
        <div className={classes.mapContainer}>
          <MapWrapper
            map={map}
            results={data}
            selectedResult={selectedResult}
            locationResult={locationResult}
            setIsFiltersOpen={setIsFiltersOpen}
            setLocationResult={setLocationResult}
            setSelectedResult={setSelectedResult}
            isLoading={isLoading || isFetching}
            setWasSearchPerformed={setWasSearchPerformed}
            wasSearchPerformed={wasSearchPerformed}
          />
        </div>
      </div>
    </QueryClientProvider>
  );
}