All files / geography/maps/src/places PlacesMap.tsx

86.03% Statements 154/179
68.04% Branches 66/97
100% Functions 29/29
97.01% Lines 130/134

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              12374x 10960x   851x   1057x                                       27x 27x 27x 27x 7x 7x 7x       35x 35x 35x     8x 8x     22x 22x 660x 660x 660x   660x 3300x   660x 660x     7x   8x 8x 8x 182x 182x 182x 182x 181x 181x 181x                 182x         182x                 182x         182x       182x           6x 6x   2x       5x 150x 300x 5x 5x 5x 5x 5x 2x 2x 2x 2x 2x 2x 1x   1x 1x 1x 2x   2x   5x 3x 2x           180x 3x 3x 3x       3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x   2x 2x 2x 2x 2x 2x   2x   2x   2x   2x   2x   2x   2x   2x   2x   2x 2x 2x   3x 3x 3x 3x 3x   7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1050x 210x 210x 210x       27x 16x     27x    
import { Feature, FeatureCollection, Point } from "geojson";
import { GeoJSONSource, Map as MapboxMap, MapLayerMouseEvent, Popup } from "mapbox-gl";
import React, { useEffect, useRef } from "react";
import { OSM_PLACE_CATEGORIES, InterestPlace, PLACE_CATEGORIES, PLACE_INFO, PlaceCategory } from "@overworld/places/catalog";
import { createPlaceIconImage } from "./placeIcons";
 
type PlaceProperties = { id: string; name: string };
const sourceId = (category: PlaceCategory) => `nearby-places-${category}`;
const layerIds = (category: PlaceCategory) => ["clusters", "counts", "points", "icons", "selection"].map(suffix => `${sourceId(category)}-${suffix}`);
export function placeFeatures(places: InterestPlace[], category: PlaceCategory): FeatureCollection<Point, PlaceProperties> {
  return {
    type: "FeatureCollection",
    features: places.filter(place => place.category === category).map(place => ({
      type: "Feature", geometry: { type: "Point", coordinates: place.coordinates },
      properties: { id: place.id, name: place.name }
    }))
  };
}
 
export interface PlacesMapProps {
  map?: MapboxMap;
  places: InterestPlace[];
  selectedId?: string;
  onSelect: (id: string) => void;
  onCoincident: (ids: string[]) => void;
  onBounds: (bounds: [number, number, number, number]) => void;
  onError: (error: boolean) => void;
  createIconImage?: (category: PlaceCategory) => ImageData;
}
 
export default function PlacesMap({ map, places, selectedId, onSelect, onCoincident, onBounds, onError,
  createIconImage = createPlaceIconImage }: PlacesMapProps) {
  const latest = useRef({ places, selectedId, onSelect, onCoincident, onBounds, onError, createIconImage });
  latest.current = { places, selectedId, onSelect, onCoincident, onBounds, onError, createIconImage };
  const update = useRef<() => void>(undefined);
  useEffect(() => {
    Iif (!map) return;
    let active = true;
    const popup = new Popup({ closeButton: false, closeOnClick: false, focusAfterOpen: false, offset: 18,
      className: "transit-place-hover-popup" });
    let hoveredKey: string | undefined;
    function hidePreview() {
      hoveredKey = undefined;
      popup.remove();
      map.getCanvas().style.cursor = "";
    }
    function reportBounds() {
      const bounds = map.getBounds();
      Eif (bounds) latest.current.onBounds([bounds.getWest(), bounds.getSouth(), bounds.getEast(), bounds.getNorth()]);
    }
    function refresh() {
      hidePreview();
      for (const category of PLACE_CATEGORIES) {
        const source = map.getSource(sourceId(category)) as GeoJSONSource | undefined;
        const data = placeFeatures(latest.current.places, category);
        source?.setData(data);
        // Hide empty categories even while Mapbox retains previously rendered tiles.
        for (const id of layerIds(category)) {
          if (map.getLayer(id)) map.setLayoutProperty(id, "visibility", data.features.length ? "visible" : "none");
        }
        const selection = layerIds(category)[4];
        if (map.getLayer(selection)) map.setFilter(selection, ["==", ["get", "id"], latest.current.selectedId || ""]);
      }
    }
    update.current = refresh;
    function install() {
      reportBounds();
      try {
        for (const category of PLACE_CATEGORIES) {
          const source = sourceId(category);
          const image = `${source}-icon`;
          const [clusters, counts, points, icons, selection] = layerIds(category);
          Eif (!map.hasImage(image)) map.addImage(image, latest.current.createIconImage(category), { pixelRatio: 2 });
          Iif (map.getSource(source)) continue;
          const color = PLACE_INFO[category].color;
          map.addSource(source, {
            type: "geojson", data: placeFeatures(latest.current.places, category),
            cluster: true, clusterRadius: 45, clusterMaxZoom: 14,
            attribution: ["park", "community-garden", "public-restroom", "heritage-tree"].includes(category) ? "City of Portland, Bureau of Parks and Recreation" :
              ["farmers-market", "grocery-store", "reuse-repair", "csa-pickup"].includes(category) ? "City of Portland, Bureau of Planning and Sustainability" :
              category === "bicycle-parking" ? "City of Portland, Bureau of Transportation" :
              OSM_PLACE_CATEGORIES.includes(category) ? '<a href="https://www.openstreetmap.org/copyright">OpenStreetMap contributors (ODbL)</a>' :
                '<a href="https://rlisdiscovery.oregonmetro.gov/pages/open-database-license">Metro RLIS data (license)</a>'
          });
          map.addLayer({
            id: clusters, type: "circle", source, filter: ["has", "point_count"],
            paint: { "circle-color": color, "circle-radius": ["step", ["get", "point_count"], 23, 10, 27, 50, 32],
              "circle-stroke-width": 2, "circle-stroke-color": "#ffffff", "circle-emissive-strength": 1 }
          });
          map.addLayer({
            id: counts, type: "symbol", source, filter: ["has", "point_count"],
            layout: {
              "icon-image": image, "icon-size": 0.9, "icon-offset": [-12, 0], "icon-allow-overlap": true,
              "text-field": ["get", "point_count_abbreviated"], "text-size": 13, "text-anchor": "left",
              "text-offset": [0.35, 0], "text-allow-overlap": true, "icon-ignore-placement": true, "text-ignore-placement": true
            },
            paint: { "text-color": "#ffffff", "text-emissive-strength": 1 }
          });
          map.addLayer({
            id: points, type: "circle", source, filter: ["!", ["has", "point_count"]],
            paint: { "circle-color": color, "circle-radius": 13, "circle-stroke-color": "#ffffff",
              "circle-stroke-width": 2, "circle-emissive-strength": 1 }
          });
          map.addLayer({
            id: icons, type: "symbol", source, filter: ["!", ["has", "point_count"]],
            layout: { "icon-image": image, "icon-size": 1, "icon-allow-overlap": true, "icon-ignore-placement": true }
          });
          map.addLayer({
            id: selection, type: "circle", source, filter: ["==", ["get", "id"], latest.current.selectedId || ""],
            paint: { "circle-color": color, "circle-opacity": 0, "circle-radius": 18,
              "circle-stroke-color": color, "circle-stroke-width": 3, "circle-emissive-strength": 1 }
          });
        }
        latest.current.onError(false);
        refresh();
      } catch {
        latest.current.onError(true);
      }
    }
    async function click(event: MapLayerMouseEvent) {
      hidePreview();
      const layers = PLACE_CATEGORIES.flatMap(category => [layerIds(category)[0], layerIds(category)[2]])
        .filter(id => map.getLayer(id));
      const features = map.queryRenderedFeatures(event.point, { layers });
      Iif (!features.length) return;
      const feature = features[0];
      try {
        if (feature.properties?.cluster && feature.geometry.type === "Point") {
          const source = map.getSource(feature.source) as GeoJSONSource;
          const zoom = await new Promise<number>((resolve, reject) =>
            source.getClusterExpansionZoom(Number(feature.properties.cluster_id), (error, value) =>
              error ? reject(error) : resolve(value)));
          Iif (!active) return;
          if (zoom > map.getZoom() && map.getZoom() < map.getMaxZoom()) {
            map.easeTo({ center: [feature.geometry.coordinates[0], feature.geometry.coordinates[1]], zoom: Math.min(zoom, map.getMaxZoom()) });
          } else {
            const leaves = await new Promise<Feature[]>((resolve, reject) =>
              source.getClusterLeaves(Number(feature.properties.cluster_id), Number(feature.properties.point_count), 0,
                (error, value) => error ? reject(error) : resolve(value)));
            Eif (active) latest.current.onCoincident(leaves.map(leaf => String(leaf.properties.id)));
          }
          return;
        }
        const ids = [...new Set(features.filter(item => !item.properties?.cluster).map(item => String(item.properties.id)))];
        if (ids.length > 1) latest.current.onCoincident(ids);
        else latest.current.onSelect(ids[0]);
      } catch {
        if (active) latest.current.onError(true);
      }
    }
    function movePointer(event: MapLayerMouseEvent) {
      const layers = PLACE_CATEGORIES.flatMap(category => [layerIds(category)[0], layerIds(category)[2]]).filter(id => map.getLayer(id));
      const features = layers.length ? map.queryRenderedFeatures(event.point, { layers }) : [];
      const feature = features[0];
      Iif (!feature || feature.geometry.type !== "Point") {
        hidePreview();
        return;
      }
      map.getCanvas().style.cursor = "pointer";
      const key = `${feature.source}:${feature.properties.cluster_id ?? feature.properties.id}`;
      Iif (key === hoveredKey) return;
      const content = document.createElement("div");
      const title = document.createElement("strong");
      const description = document.createElement("p");
      if (feature.properties.cluster) {
        const category = PLACE_CATEGORIES.find(category => sourceId(category) === feature.source);
        Iif (!category) { hidePreview(); return; }
        title.textContent = `${feature.properties.point_count} ${PLACE_INFO[category].label.toLowerCase()}`;
        description.textContent = "Click to explore these places.";
      } else {
        const place = latest.current.places.find(place => place.id === feature.properties.id);
        Iif (!place) { hidePreview(); return; }
        title.textContent = place.name;
        description.textContent = PLACE_INFO[place.category].singular;
        Eif (place.address) description.append(document.createElement("br"), document.createTextNode(place.address));
        Iif (place.category === "farmers-market") description.append(document.createElement("br"),
          document.createTextNode("Schedules may be outdated; check before visiting."));
        Iif (place.category === "community-garden") description.append(document.createElement("br"),
          document.createTextNode("Plot access may require registration."));
        Iif (place.category === "public-restroom") description.append(document.createElement("br"),
          document.createTextNode("Availability is not live; closures or access restrictions may apply."));
        Iif (place.category === "heritage-tree") description.append(document.createElement("br"),
          document.createTextNode("May be on private land; view only from lawful public access."));
        Iif (place.category === "grocery-store") description.append(document.createElement("br"),
          document.createTextNode("Check the current location and opening hours."));
        Iif (place.category === "reuse-repair") description.append(document.createElement("br"),
          document.createTextNode("Confirm accepted items, appointments and access before visiting."));
        Iif (place.category === "csa-pickup") description.append(document.createElement("br"),
          document.createTextNode("Membership and arranged pickup may be required; not a public market."));
        Iif (place.category === "bicycle-parking") description.append(document.createElement("br"),
          document.createTextNode("Mapped rack, not live parking availability."));
        Iif (place.amenityType) description.append(document.createElement("br"),
          document.createTextNode(place.amenityStyle || place.amenityType));
        Iif (place.category === "drinking-fountain") description.append(document.createElement("br"),
          document.createTextNode("Water service and potability are not verified; some assets are dog bowls."));
        const hint = document.createElement("p");
        hint.textContent = "Click for details and trip planning.";
        content.append(hint);
      }
      content.prepend(title, description);
      const coordinates: [number, number] = [feature.geometry.coordinates[0], feature.geometry.coordinates[1]];
      while (Math.abs(event.lngLat.lng - coordinates[0]) > 180) coordinates[0] += event.lngLat.lng > coordinates[0] ? 360 : -360;
      popup.setLngLat(coordinates).setDOMContent(content).addTo(map);
      hoveredKey = key;
    }
    map.on("style.load", install);
    map.on("moveend", reportBounds);
    map.on("click", click);
    map.on("mousemove", movePointer);
    map.on("movestart", hidePreview);
    map.getCanvas().addEventListener("mouseleave", hidePreview);
    install();
    return () => {
      active = false;
      update.current = undefined;
      map.off("style.load", install);
      map.off("moveend", reportBounds);
      map.off("click", click);
      map.off("mousemove", movePointer);
      map.off("movestart", hidePreview);
      map.getCanvas().removeEventListener("mouseleave", hidePreview);
      hidePreview();
      for (const category of PLACE_CATEGORIES) {
        for (const id of layerIds(category).reverse()) if (map.getLayer(id)) map.removeLayer(id);
        if (map.getSource(sourceId(category))) map.removeSource(sourceId(category));
        const image = `${sourceId(category)}-icon`;
        if (map.hasImage(image)) map.removeImage(image);
      }
    };
  }, [map]);
  useEffect(() => {
    try { update.current?.(); }
    catch { onError(true); }
  }, [places, selectedId]);
  return null;
}