All files / app/features/search users.ts

17.54% Statements 10/57
0% Branches 0/12
0% Functions 0/9
20% Lines 10/50

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                        1x   1x   1x     1x                       1x                                                                                                                                                     1x                           1x                                                     1x                   1x                                               1x                                                          
import { MapClickedCallback } from "features/search/constants";
import { Point } from "geojson";
import {
  GeoJSONSource,
  LayerSpecification,
  Map as MaplibreMap,
  MapLayerMouseEvent,
  SourceSpecification,
} from "maplibre-gl";
import { User } from "proto/api_pb";
import { UserSearchRes } from "proto/search_pb";
import { InfiniteData } from "react-query";
import { theme } from "theme";
 
import userPin from "./resources/userPin.png";
 
const URL = process.env.NEXT_PUBLIC_API_BASE_URL;
 
type SourceKeys = "clustered-users";
export const sources: Record<SourceKeys, SourceSpecification> = {
  "clustered-users": {
    cluster: true,
    clusterMaxZoom: 14,
    clusterRadius: 50,
    data: URL + "/geojson/users",
    promoteId: "id",
    type: "geojson",
  },
};
 
type LayerKeys = "clusterCountLayer" | "clusterLayer" | "unclusteredPointLayer";
export const layers: Record<LayerKeys, LayerSpecification> = {
  clusterCountLayer: {
    filter: ["has", "point_count"],
    id: "clusters-count",
    layout: {
      "text-field": "{point_count_abbreviated}",
      "text-size": 12,
      "text-font": ["Inter 28pt SemiBold"],
    },
    paint: {
      "text-color": [
        "step",
        ["get", "point_count"],
        theme.palette.getContrastText(theme.palette.primary.light),
        100,
        theme.palette.getContrastText(theme.palette.primary.main),
        750,
        theme.palette.getContrastText(theme.palette.primary.dark),
      ],
    },
    source: "clustered-users",
    type: "symbol",
  },
  clusterLayer: {
    filter: ["has", "point_count"],
    id: "clusters",
    paint: {
      // step expression: https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/#step
      "circle-color": [
        "step",
        ["get", "point_count"],
        theme.palette.primary.light,
        100,
        theme.palette.primary.main,
        750,
        theme.palette.primary.dark,
      ],
      "circle-radius": ["step", ["get", "point_count"], 20, 100, 30, 750, 40],
    },
    source: "clustered-users",
    type: "circle",
  },
  unclusteredPointLayer: {
    filter: ["!", ["has", "point_count"]],
    id: "unclustered-points",
    layout: {
      "icon-image": "user-pin",
      "icon-anchor": "bottom",
      "icon-allow-overlap": true,
    },
    paint: {
      "icon-color": [
        "case",
        ["boolean", ["feature-state", "selected"], false],
        theme.palette.secondary.main,
        ["==", ["get", "has_completed_profile"], true],
        theme.palette.primary.main,
        theme.palette.grey[500],
      ],
      "icon-halo-width": 2,
      "icon-halo-color": [
        "case",
        ["boolean", ["feature-state", "selected"], false],
        theme.palette.secondary.main,
        ["==", ["get", "has_completed_profile"], true],
        theme.palette.primary.main,
        theme.palette.grey[500],
      ],
      "icon-halo-blur": 2,
    },
    source: "clustered-users",
    type: "symbol",
  },
};
 
const addPinImages = async (map: MaplibreMap) => {
  try {
    const image = await map.loadImage(userPin.src);
 
    Iif (map.hasImage("user-pin")) return;
 
    Iif (image) {
      map.addImage("user-pin", image.data, { sdf: true });
    }
  } catch (error) {
    throw error;
  }
};
 
const zoomCluster = async (ev: MapLayerMouseEvent) => {
  const map = ev.target;
  const cluster = ev.features?.[0];
  Iif (!cluster || !cluster.properties?.cluster_id) return;
 
  try {
    const source = map.getSource("clustered-users") as GeoJSONSource;
    const zoom = await source.getClusterExpansionZoom(
      cluster.properties.cluster_id
    );
 
    Iif (zoom !== null && zoom !== undefined) {
      const point = cluster.geometry as Point;
 
      map.flyTo({
        center: point.coordinates as [number, number],
        zoom,
      });
    }
  } catch (error) {
    throw error;
  }
};
 
/**
 * Filters the data and format it
 */
export const filterData = (data: InfiniteData<UserSearchRes.AsObject>) => {
  return data.pages
    .flatMap((page) => page.resultsList)
    .map((result) => {
      return result.user;
    })
    .filter((user): user is User.AsObject => !!user)
    .map((user) => user.userId);
};
 
export const addClusteredUsersToMap = (
  map: MaplibreMap,
  userClickedCallback?: MapClickedCallback
) => {
  map.addSource("clustered-users", sources["clustered-users"]);
  addPinImages(map);
  map.addLayer(layers.clusterLayer);
  map.addLayer(layers.clusterCountLayer);
  map.addLayer(layers.unclusteredPointLayer);
 
  Iif (userClickedCallback) {
    map.on("click", layers.unclusteredPointLayer.id, userClickedCallback);
  }
 
  map.on("click", layers.clusterLayer.id, zoomCluster);
};
 
/**
 * Deletes all the @map results (by cleaning a map layer), adds a new layer containing a new list of results (@ids) and then sets a callback when user click
 * on one result
 * @param map map to edit its results
 * @param ids new list of results to add
 * @param userClickedCallback callback to be executed when user clicks
 */
export const reRenderUsersOnMap = (
  map: MaplibreMap,
  ids: number[] | null,
  userClickedCallback?: MapClickedCallback
) => {
  //clusters can only be filtered at the source before rendering
  //so we have to remove the layers and sources and re-add
  Iif (userClickedCallback) {
    map.off("click", layers.unclusteredPointLayer.id, userClickedCallback);
    map.off("click", layers.clusterLayer.id, zoomCluster);
  }
 
  map.removeLayer(layers.clusterLayer.id);
  map.removeLayer(layers.clusterCountLayer.id);
  map.removeLayer(layers.unclusteredPointLayer.id);
  map.removeSource("clustered-users");
 
  if (ids) {
    //https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/#in
    //basically it's like `ids.contains(clusteredUser.id)`
    //@ts-ignore - type definition incorrect
    sources["clustered-users"].filter = ["in", ["get", "id"], ["literal", ids]];
  } else {
    //@ts-ignore - type definition incorrect
    delete sources["clustered-users"].filter;
  }
 
  addClusteredUsersToMap(map, userClickedCallback);
};