All files / geography/maps/src/planner PlannerPaths.tsx

95.58% Statements 195/204
84.11% Branches 90/107
100% Functions 39/39
97.15% Lines 171/176

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 313 314 315 316                                          10x 10x 10x 10x 10x 10x 10x 10x     12x               12x 21x 11x 22x 6x 16x 15x         16x 16x 16x 22x     12x                                   68x 68x 68x           68x   68x   68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 12x     68x 18x   8x 17x 17x 17x 17x 18x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 18x 18x 18x   17x 17x     17x 5x 5x 5x   17x 5x 5x       5x 5x 5x 5x   17x 1x 1x 1x     17x   8x 8x 17x       68x 33x 33x 33x     68x 8x   8x 8x 7x 6x 6x     1x     8x 8x     68x 18x 6x   6x 6x 6x 6x 6x       6x       6x       6x       6x       6x       6x       6x 6x               31x 31x 31x 155x 31x 31x 31x 31x 31x 31x 62x                 6x 42x   6x     6x 6x 6x 6x 6x 6x 6x       68x 26x 26x 12x 4x 2x 2x   2x 6x 6x   4x     2x   12x 12x 12x 12x 12x 12x 12x 12x       68x 19x 6x 4x 4x 4x 4x   4x 45x 4x 26x 77x   4x 122x 4x 4x 4x     329x 68x   43x      
import React, { useEffect, useId, useMemo, useState } from "react";
import { LngLatBounds, Map as MapboxMap, MapMouseEvent, Marker, Popup } from "mapbox-gl";
import type { TripPlannerItinerary } from "@overworld/trimet-client";
import type { PlannerPath, PlannerPathProperties } from "@overworld/routing";
import type { Feature, FeatureCollection } from "geojson";
import "./PlannerPaths.scss";
 
export interface PlannerPathsResult {
  data: FeatureCollection<PlannerPath, PlannerPathProperties>;
}
 
export type PlannerPathRequest = (
  itineraries: TripPlannerItinerary[], signal: AbortSignal, walkingEnabled: boolean
) => Promise<PlannerPathsResult>;
 
export interface PlannerMapStatus {
  mapError: boolean;
  selectedPaths: Feature<PlannerPath, PlannerPathProperties>[];
  incomplete: boolean;
}
 
const SOURCE = "planner-itineraries";
const OTHER = `${SOURCE}-alternatives`;
const CASING = `${SOURCE}-selected-casing`;
const ACTIVE = `${SOURCE}-selected`;
const OTHER_WALK = `${OTHER}-walk`;
const ACTIVE_WALK = `${ACTIVE}-walk`;
const HIGHLIGHT = `${ACTIVE}-highlight`;
const HIGHLIGHT_WALK = `${HIGHLIGHT}-walk`;
 
function itineraryStops(itinerary: TripPlannerItinerary) {
  const stops = new Map<number, {
    id: number;
    name: string;
    point: [number, number];
    actions: Set<string>;
    board: boolean;
    exit: boolean;
  }>();
  for (const leg of itinerary.legs) {
    if (leg.mode?.toLowerCase() === "walk") continue;
    for (const [action, stop] of [["board", leg.from], ["exit", leg.to]] as const) {
      if (!stop?.stopId || !Number.isFinite(stop.lon) || !Number.isFinite(stop.lat) ||
          Math.abs(stop.lon) > 180 || Math.abs(stop.lat) > 90) continue;
      if (!stops.has(stop.stopId)) {
        stops.set(stop.stopId, {
          id: stop.stopId, name: stop.description || `Stop ${stop.stopId}`,
          point: [stop.lon, stop.lat], actions: new Set(), board: false, exit: false
        });
      }
      const marker = stops.get(stop.stopId);
      marker[action] = true;
      const route = leg.route?.name || leg.route?.number || leg.mode;
      marker.actions.add(`${action === "board" ? "Board" : "Get off"}${route ? `: ${route}` : ""}`);
    }
  }
  return Array.from(stops.values());
}
 
export interface PlannerPathsProps {
  map?: MapboxMap;
  suspended?: boolean;
  itineraries: TripPlannerItinerary[];
  selected: number;
  previewTrip?: number;
  walkingEnabled: boolean;
  highlightedLeg?: number;
  onMapLeg: (leg?: number) => void;
  loadPaths: PlannerPathRequest;
  renderStatus: (status: PlannerMapStatus) => React.ReactNode;
}
 
export default function PlannerPaths({ map: plannerMap, suspended, itineraries, selected, previewTrip,
  walkingEnabled, highlightedLeg, onMapLeg, loadPaths, renderStatus }: PlannerPathsProps) {
  const map = suspended ? undefined : plannerMap;
  const includeWalking = walkingEnabled && Boolean(plannerMap);
  const [loaded, setLoaded] = useState<{
    itineraries: TripPlannerItinerary[];
    includeWalking: boolean;
    loadPaths: PlannerPathRequest;
    paths: PlannerPathsResult;
  }>();
  const result = loaded?.itineraries === itineraries && loaded.includeWalking === includeWalking && loaded.loadPaths === loadPaths
    ? loaded.paths : undefined;
  const emphasizedTrip = previewTrip !== undefined && result?.data.features.some(({ properties }) => properties.trip === previewTrip)
    ? previewTrip : selected;
  const emphasizedLeg = emphasizedTrip === selected ? highlightedLeg : undefined;
  const [mapError, setMapError] = useState(false);
  const mapEmphasis = React.useRef(emphasizedTrip);
  const mapHighlight = React.useRef(emphasizedLeg);
  const applySelection = React.useRef<() => void>(undefined);
  const stopsByTrip = useMemo(() => itineraries.map(itineraryStops), [itineraries]);
  const selectedStops = stopsByTrip[selected];
  const popupIdPrefix = useId();
  const lastFit = React.useRef<{ map: MapboxMap; result: typeof result }>(undefined);
  const suspendedInputs = React.useRef<{ itineraries: TripPlannerItinerary[]; includeWalking: boolean; loadPaths: PlannerPathRequest }>(undefined);
  useEffect(() => {
    if (suspended) suspendedInputs.current = { itineraries, includeWalking, loadPaths };
  }, [suspended, itineraries, includeWalking, loadPaths]);
 
  useEffect(() => {
    if (!map || !selectedStops?.length) return;
    let activePopup: Popup | undefined;
    const markers = selectedStops.map(stop => {
      const element = document.createElement("button");
      element.type = "button";
      element.setAttribute("role", "button");
      element.className = "transit-planner-stop-marker";
      element.setAttribute("aria-label", Array.from(stop.actions).map(action => `${action} at ${stop.name}`).join("; "));
      element.setAttribute("aria-expanded", "false");
      element.textContent = stop.board && stop.exit ? "↕" : stop.board ? "↑" : "↓";
      const content = document.createElement("div");
      content.id = `${popupIdPrefix}-trip-stop-${stop.id}`;
      const title = document.createElement("strong");
      title.textContent = stop.name;
      const id = document.createElement("small");
      id.textContent = `Stop ID: ${stop.id}`;
      const actions = document.createElement("ul");
      stop.actions.forEach(action => {
        const row = document.createElement("li");
        row.textContent = action;
        actions.appendChild(row);
      });
      content.append(title, id, actions);
      const popup = new Popup({
        className: "transit-planner-stop-popup", closeButton: false, focusAfterOpen: false, offset: 15,
      }).setLngLat(stop.point).setDOMContent(content);
      popup.on("close", () => {
        element.setAttribute("aria-expanded", "false");
        element.removeAttribute("aria-controls");
        Eif (activePopup === popup) activePopup = undefined;
      });
      element.addEventListener("click", event => {
        event.stopPropagation();
        Iif (popup.isOpen()) {
          popup.remove();
          return;
        }
        activePopup?.remove();
        activePopup = popup.addTo(map);
        element.setAttribute("aria-expanded", "true");
        element.setAttribute("aria-controls", content.id);
      });
      element.addEventListener("keydown", event => {
        Eif (event.key === "Escape" && popup.isOpen()) {
          event.stopPropagation();
          popup.remove();
        }
      });
      return new Marker({ element }).setLngLat(stop.point).addTo(map);
    });
    return () => {
      activePopup?.remove();
      markers.forEach(marker => marker.remove());
    };
  }, [map, selectedStops, popupIdPrefix]);
 
  useEffect(() => {
    mapEmphasis.current = emphasizedTrip;
    mapHighlight.current = emphasizedLeg;
    applySelection.current?.();
  }, [emphasizedTrip, emphasizedLeg]);
 
  useEffect(() => {
    const controller = new AbortController();
    async function load() {
      try {
        const paths = await loadPaths(itineraries, controller.signal, includeWalking);
        if (!controller.signal.aborted) {
          setLoaded({ itineraries, includeWalking, loadPaths, paths });
          setMapError(false);
        }
      } catch {
        Eif (!controller.signal.aborted) setMapError(true);
      }
    }
    void load();
    return () => controller.abort();
  }, [itineraries, includeWalking, loadPaths]);
 
  useEffect(() => {
    if (!map || !result?.data.features.length) return;
    const { data } = result;
    function installLayers() {
      Iif (map.getSource(SOURCE)) return;
      try {
        map.addSource(SOURCE, { type: "geojson", data });
        const layout = { "line-cap": "round", "line-join": "round" } as const;
        map.addLayer({
          id: OTHER, source: SOURCE, type: "line", slot: "top", layout,
          paint: { "line-color": ["get", "color"], "line-width": 3.5, "line-opacity": 0.6, "line-emissive-strength": 1 }
        });
        map.addLayer({
          id: OTHER_WALK, source: SOURCE, type: "line", slot: "top", layout,
          paint: { "line-color": "#667b92", "line-width": 3, "line-dasharray": [1, 2], "line-emissive-strength": 1 }
        });
        map.addLayer({
          id: CASING, source: SOURCE, type: "line", slot: "top", layout,
          paint: { "line-color": "#f8fbff", "line-width": 9, "line-emissive-strength": 1 }
        });
        map.addLayer({
          id: ACTIVE, source: SOURCE, type: "line", slot: "top", layout,
          paint: { "line-color": ["get", "color"], "line-width": 5, "line-emissive-strength": 1 }
        });
        map.addLayer({
          id: ACTIVE_WALK, source: SOURCE, type: "line", slot: "top", layout,
          paint: { "line-color": "#1559d1", "line-width": 4, "line-dasharray": [1, 2], "line-emissive-strength": 1 }
        });
        map.addLayer({
          id: HIGHLIGHT, source: SOURCE, type: "line", slot: "top", layout,
          paint: { "line-color": ["get", "color"], "line-width": 8, "line-emissive-strength": 1 }
        });
        map.addLayer({
          id: HIGHLIGHT_WALK, source: SOURCE, type: "line", slot: "top", layout,
          paint: { "line-color": "#1559d1", "line-width": 7, "line-dasharray": [4 / 7, 8 / 7], "line-emissive-strength": 1 }
        });
        updateSelection();
        setMapError(false);
      } catch {
        removeLayers();
        setMapError(true);
      }
    }
 
    function updateSelection() {
      Iif (!map.getLayer(ACTIVE)) return;
      const trip = mapEmphasis.current;
      const filter = (layer: string, operator: "==" | "!=", walk: boolean) =>
        map.setFilter(layer, ["all", [operator, ["get", "trip"], trip], ["==", ["get", "walk"], walk]]);
      filter(OTHER, "!=", false);
      filter(OTHER_WALK, "!=", true);
      filter(CASING, "==", false);
      filter(ACTIVE, "==", false);
      filter(ACTIVE_WALK, "==", true);
      for (const [layer, walk] of [[HIGHLIGHT, false], [HIGHLIGHT_WALK, true]] as const) {
        map.setFilter(layer, ["all",
          ["==", ["get", "trip"], trip],
          ["==", ["get", "legIndex"], mapHighlight.current ?? -1],
          ["==", ["get", "walk"], walk]
        ]);
      }
    }
 
    function removeLayers() {
      [HIGHLIGHT_WALK, HIGHLIGHT, ACTIVE_WALK, ACTIVE, CASING, OTHER_WALK, OTHER].forEach(id => {
        Eif (map.getLayer(id)) map.removeLayer(id);
      });
      Eif (map.getSource(SOURCE)) map.removeSource(SOURCE);
    }
 
    installLayers();
    map.on("style.load", installLayers);
    applySelection.current = updateSelection;
    return () => {
      applySelection.current = undefined;
      map.off("style.load", installLayers);
      removeLayers();
    };
  }, [map, result]);
 
  useEffect(() => {
    onMapLeg();
    if (!map || !result?.data.features.length || selected < 0) return;
    const move = ({ point }: MapMouseEvent) => {
      const layers = [ACTIVE, ACTIVE_WALK].filter(id => map.getLayer(id));
      Iif (!layers.length) return onMapLeg();
      const features = map.queryRenderedFeatures(point, { layers });
      let firstLeg: number | undefined;
      for (const { properties } of features) {
        const leg = properties?.legIndex;
        if (properties?.trip === selected && Number.isInteger(leg) &&
            (firstLeg === undefined || leg < firstLeg)) {
          firstLeg = leg;
        }
      }
      onMapLeg(firstLeg);
    };
    const leave = () => onMapLeg();
    map.on("mousemove", move);
    map.on("mouseout", leave);
    map.on("dragstart", leave);
    return () => {
      map.off("mousemove", move);
      map.off("mouseout", leave);
      map.off("dragstart", leave);
    };
  }, [map, result, selected, onMapLeg]);
 
  useEffect(() => {
    if (!map || !result) return;
    if (lastFit.current?.map === map && lastFit.current.result === result) return;
    lastFit.current = { map, result };
    const previous = suspendedInputs.current;
    suspendedInputs.current = undefined;
    Iif (previous?.itineraries === itineraries && previous.includeWalking === includeWalking &&
        previous.loadPaths === loadPaths) return;
    const bounds = new LngLatBounds();
    const points = stopsByTrip.flatMap(stops => stops.map(stop => stop.point));
    result.data.features.forEach(({ geometry }) => {
      const lines = geometry.type === "LineString" ? [geometry.coordinates] : geometry.coordinates;
      lines.forEach(line => line.forEach(([lng, lat]) => points.push([lng, lat])));
    });
    Iif (!points.length) return;
    points.forEach(point => bounds.extend(point));
    const { clientWidth, clientHeight } = map.getContainer();
    const padding = Math.floor(Math.min(44, clientWidth / 6, clientHeight / 6));
    map.fitBounds(bounds, { padding, maxZoom: 16, duration: 0 });
  }, [map, result, stopsByTrip, itineraries, includeWalking, loadPaths]);
 
  const selectedPaths = result?.data.features.filter(feature => feature.properties.trip === selected) || [];
  return <>{renderStatus({
    mapError, selectedPaths,
    incomplete: new Set(selectedPaths.map(feature => feature.properties.legIndex)).size < (itineraries[selected]?.legs.length ?? 0),
  })}</>;
}