All files / app/features/search MapWrapper.tsx

40.96% Statements 34/83
8.33% Branches 2/24
31.25% Functions 5/16
40.5% Lines 32/79

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 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 3131x 1x 1x 1x           1x   1x 1x 1x                   1x   1x 1x   2x                                                                                                             1x                       3x 3x 3x 3x 3x 3x         3x                                                 3x                               3x                           3x   2x                 2x                               3x 2x                                                                       3x 2x                                   3x                                       3x                                 3x                                                                
import ReplayIcon from "@material-ui/icons/Replay";
import TuneIcon from "@material-ui/icons/Tune";
import Button from "components/Button";
import Map from "components/Map";
import {
  addClusteredUsersToMap,
  filterData,
  layers,
  reRenderUsersOnMap,
} from "features/search/users";
import { Point } from "geojson";
import { useTranslation } from "i18n";
import { SEARCH } from "i18n/namespaces";
import maplibregl, { EventData, LngLat, Map as MaplibreMap } from "maplibre-gl";
import { User } from "proto/api_pb";
import { UserSearchRes } from "proto/search_pb";
import {
  Dispatch,
  MutableRefObject,
  SetStateAction,
  useCallback,
  useEffect,
  useState,
} from "react";
import { InfiniteData } from "react-query";
import { GeocodeResult, usePrevious } from "utils/hooks";
import makeStyles from "utils/makeStyles";
 
const useStyles = makeStyles((theme) => ({
  searchHereGroup2: {
    top: "20px",
    left: "50%",
    position: "relative",
    zIndex: 10,
  },
  testContainer: {
    position: "absolute",
    left: "50%",
    width: "100%",
  },
  testChildFromGoogle: {
    width: "300px",
    top: "30px",
    display: "flex",
    position: "relative",
    left: "-50%",
    fontSize: " 14px",
    margin: "8px auto 0",
    alignItems: "center",
 
    height: "25px",
    zIndex: 10,
  },
  buttonSearchSettings: {
    borderRadius: "0 4px 4px 0",
    "& span": {
      margin: 0,
    },
  },
  searchHereButton: {
    borderRadius: "4px 0 0 4px",
  },
}));
 
interface mapWrapperProps {
  selectedResult:
    | Pick<User.AsObject, "username" | "userId" | "lng" | "lat">
    | undefined;
  isLoading: boolean;
  locationResult: GeocodeResult | undefined;
  setLocationResult: Dispatch<SetStateAction<GeocodeResult>>;
  results: InfiniteData<UserSearchRes.AsObject> | undefined;
  setIsFiltersOpen: Dispatch<SetStateAction<boolean>>;
  setSelectedResult: Dispatch<
    SetStateAction<
      Pick<User.AsObject, "username" | "userId" | "lng" | "lat"> | undefined
    >
  >;
  map: MutableRefObject<MaplibreMap | undefined>;
  setWasSearchPerformed: Dispatch<SetStateAction<boolean>>;
  wasSearchPerformed: boolean;
}
 
export default function MapWrapper({
  map,
  selectedResult,
  locationResult,
  setLocationResult,
  isLoading,
  results,
  setSelectedResult,
  setIsFiltersOpen,
  wasSearchPerformed,
  setWasSearchPerformed,
}: mapWrapperProps) {
  const { t } = useTranslation([SEARCH]);
  const [areClustersLoaded, setAreClustersLoaded] = useState(false);
  const [isMapStyleLoaded, setIsMapStyleLoaded] = useState(false);
  const [isMapSourceLoaded, setIsMapSourceLoaded] = useState(false);
  const previousResult = usePrevious(selectedResult);
  const classes = useStyles();
 
  /**
   * User clicks on a user on map
   */
  const handleMapUserClick = useCallback(
    (
      ev: maplibregl.MapMouseEvent & {
        features?: maplibregl.MapboxGeoJSONFeature[] | undefined;
      } & EventData
    ) => {
      ev.preventDefault();
 
      const props = ev.features?.[0].properties;
      const geom = ev.features?.[0].geometry as Point;
 
      Iif (!props || !geom) return;
 
      const username = props.username;
      const userId = props.id;
 
      const [lng, lat] = geom.coordinates;
      setSelectedResult({ username, userId, lng, lat });
    },
    [setSelectedResult]
  );
 
  /**
   * Detects when map data has been initially loaded
   */
  const handleMapSourceData = useCallback(() => {
    Iif (
      map.current &&
      map.current.getSource("clustered-users") &&
      map.current.isSourceLoaded("clustered-users")
    ) {
      setAreClustersLoaded(true);
 
      // unbind the event
      map.current.off("sourcedata", handleMapSourceData);
    }
  }, [map]);
 
  /**
   * Moves map to selected user's location
   */
  const flyToUser = useCallback(
    (user: Pick<User.AsObject, "lng" | "lat">) => {
      map.current?.stop();
      map.current?.easeTo({
        center: [user.lng, user.lat],
      });
    },
    [map]
  );
 
  /**
   * Centers selected user
   * Unsets previous selected
   */
  useEffect(() => {
    //unset the old feature selection on the map for styling
    Iif (previousResult) {
      Iif (areClustersLoaded) {
        map.current?.setFeatureState(
          { source: "clustered-users", id: previousResult.userId },
          { selected: false }
        );
      }
    }
 
    Iif (selectedResult) {
      flyToUser(selectedResult);
      Iif (areClustersLoaded) {
        map.current?.setFeatureState(
          { source: "clustered-users", id: selectedResult.userId },
          { selected: true }
        );
      }
 
      //update result list
      document
        .getElementById(`search-result-${selectedResult.userId}`)
        ?.scrollIntoView({ behavior: "smooth" });
    }
  }, [selectedResult, areClustersLoaded, previousResult, flyToUser, map]);
 
  useEffect(() => {
    if (!map.current) return;
    const handleMapClickAway = (e: EventData) => {
      // DefaultPrevented is true when a map feature has been clicked
      Iif (!e.defaultPrevented) {
        setSelectedResult(undefined);
      }
    };
 
    // Bind event handlers for map events (order matters!)
    map.current.on(
      "click",
      layers.unclusteredPointLayer.id,
      handleMapUserClick
    );
 
    map.current.on("click", handleMapClickAway);
 
    map.current.on("sourcedata", handleMapSourceData);
 
    return () => {
      Iif (!map.current) return;
 
      // Unbind event handlers for map events
      map.current.off("sourcedata", handleMapSourceData);
      map.current.off("click", handleMapClickAway);
      map.current.off(
        "click",
        layers.unclusteredPointLayer.id,
        handleMapUserClick
      );
    };
  }, [handleMapUserClick, handleMapSourceData, map, setSelectedResult]);
 
  /**
   * Re-renders users list on map (when results array changed)
   */
  useEffect(() => {
    Iif (isMapStyleLoaded && isMapSourceLoaded && wasSearchPerformed) {
      Iif (results) {
        const usersToRender = filterData(results);
        reRenderUsersOnMap(map.current!, usersToRender, handleMapUserClick);
      }
    }
  }, [
    results,
    handleMapUserClick,
    map,
    isMapStyleLoaded,
    isMapSourceLoaded,
    wasSearchPerformed,
  ]);
 
  /**
   * Clicks on 'search here' button
   */
  const handleOnClick = () => {
    const currentBbox = map.current?.getBounds().toArray();
    Iif (currentBbox) {
      Iif (map.current?.getBounds && locationResult) {
        setLocationResult({
          ...locationResult,
          name: "",
          simplifiedName: "",
          bbox: [
            currentBbox[0][0],
            currentBbox[0][1],
            currentBbox[1][0],
            currentBbox[1][1],
          ],
        });
      }
      setWasSearchPerformed(true);
    }
  };
 
  const initializeMap = (newMap: MaplibreMap) => {
    map.current = newMap;
    newMap.on("load", () => {
      addClusteredUsersToMap(newMap);
    });
 
    newMap.on("styledata", function () {
      setIsMapStyleLoaded(true);
    });
 
    newMap.on("sourcedataloading", function (e) {
      Iif (e.sourceId === "clustered-users") {
        setIsMapSourceLoaded(true);
      }
    });
  };
 
  return (
    <>
      <div className={classes.testContainer}>
        <div className={classes.testChildFromGoogle}>
          <Button
            color="primary"
            loading={isLoading}
            onClick={handleOnClick}
            className={classes.searchHereButton}
            endIcon={<ReplayIcon />}
          >
            {t("search:filter_dialog.search_here_button")}
          </Button>
          <Button
            color="primary"
            aria-label="tune search"
            onClick={() => setIsFiltersOpen(true)}
            className={classes.buttonSearchSettings}
            endIcon={<TuneIcon />}
          />
        </div>
      </div>
      <Map
        grow
        initialCenter={new LngLat(0, 0)}
        initialZoom={1}
        postMapInitialize={initializeMap}
        hash
      />
    </>
  );
}