All files / geography/maps/src routeLines.ts

91.37% Statements 53/58
76.47% Branches 13/17
93.33% Functions 14/15
94.23% Lines 49/52

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        13x         30x 30x 30x 28x 28x 28x             30x 30x 26x 26x 24x 24x                       30x 30x 30x                             26x                 26x 26x                     1x 1x 1x             6x 6x   6x 6x 14x 12x 12x 12x 12x   12x 12x 12x         1x 1x     5x               6x 10x 14x       2x 2x       6x       44x 58x 51x   58x 51x       44x    
import { LineLayerSpecification, Map } from "mapbox-gl";
import { Feature, LineString, MultiLineString } from "geojson";
import type { NearbyRouteDirections, RouteGeometryLoader } from "./transitTypes";
 
export const NEARBY_ROUTE_LINES = "nearby-route-lines";
 
export function showNearbyRouteLines(
  map: Map, routes: NearbyRouteDirections, getRouteGeometry: RouteGeometryLoader
): () => void {
  const controller = new AbortController();
  const { signal } = controller;
  const requests = Object.keys(routes).flatMap(routeId =>
    Array.from(new Set(routes[Number(routeId)].directions)).map(async direction => {
      try {
        return await getRouteGeometry(routeId, direction, signal);
      } catch (error) {
        if (!signal.aborted) console.warn(`Could not load nearby route ${routeId}, direction ${direction}`, error);
        return undefined;
      }
    })
  );
  void Promise.all(requests).then(results => {
    if (signal.aborted) return;
    const features = results.filter((feature): feature is Feature<LineString | MultiLineString> => feature !== undefined);
    if (!features.length) return;
    map.addSource(NEARBY_ROUTE_LINES, { type: "geojson", data: { type: "FeatureCollection", features } });
    map.addLayer({
      id: NEARBY_ROUTE_LINES,
      source: NEARBY_ROUTE_LINES,
      type: "line",
      slot: "middle",
      layout: { "line-cap": "round", "line-join": "round" },
      paint: { "line-color": "#0080ff", "line-emissive-strength": 1, "line-opacity": 0.6, "line-width": 3 }
    });
  }).catch(error => {
    console.warn("Could not display nearby route lines", error);
  });
 
  return () => {
    controller.abort();
    removeRoutes(map, [NEARBY_ROUTE_LINES]);
  };
}
 
export function addMapboxLayer(
  map: Map,
  feature: Feature<LineString | MultiLineString>,
  sourceId: string,
  paint: LineLayerSpecification["paint"] = {
    "line-color": "#0080ff",
    "line-dasharray": [2, 4],
    "line-opacity": 0.8,
    "line-width": 2
  }
): Map {
  map.addSource(sourceId, {
    data: {
      geometry: feature.geometry,
      properties: {},
      type: "Feature"
    },
    type: "geojson"
  });
 
  try {
    return map.addLayer({
      id: sourceId,
      layout: {
        "line-cap": "round",
        "line-join": "round"
      },
      paint,
      source: sourceId,
      type: "line"
    });
  } catch (error) {
    Iif (map.getLayer(sourceId)) map.removeLayer(sourceId);
    map.removeSource(sourceId);
    throw error;
  }
}
 
function addRouteLayers(
  mapBoxMap: Map, features: Array<Feature<LineString | MultiLineString> | undefined>
): string[] {
  const sources = new Set<string>();
  const sourceIds: string[] = [];
 
  try {
    for (const feature of features) {
      if (feature) {
        const { route_number, direction } = feature.properties;
        const routeIdentifier = `${route_number}_${direction}`;
        const sourceId = `route-${routeIdentifier}`;
        sourceIds.push(sourceId);
 
        Eif (!sources.has(sourceId)) {
          sources.add(sourceId);
          addMapboxLayer(mapBoxMap, feature, sourceId);
        }
      }
    }
  } catch (error) {
    removeRoutes(mapBoxMap, [...sources]);
    throw error;
  }
 
  return sourceIds;
}
 
export async function setRoutes(
  mapBoxMap: Map,
  nearbyRouteIds: NearbyRouteDirections,
  getRouteGeometry: RouteGeometryLoader
): Promise<string[]> {
  const promises = Object.entries(nearbyRouteIds).flatMap(([routeId, route]) =>
    route.directions.map(directionId =>
      getRouteGeometry(routeId, directionId).then(feature => ({
        ...feature,
        properties: { ...feature.properties, route_number: routeId, direction: directionId }
      })).catch(error => {
        console.error(error);
        return undefined;
      })
    )
  );
  return addRouteLayers(mapBoxMap, await Promise.all(promises));
}
 
export function removeRoutes(map: Map, routeLayers: readonly string[]): Map {
  for (const layerId of new Set(routeLayers)) {
    if (map.getLayer(layerId)) {
      map.removeLayer(layerId);
    }
    if (map.getSource(layerId)) {
      map.removeSource(layerId);
    }
  }
 
  return map;
}