All files / api/places/src lineOverlays.ts

95.34% Statements 41/43
91.37% Branches 53/58
100% Functions 16/16
100% Lines 32/32

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        21x           21x 21x     21x                                   64929x 21663x   21636x         18x         21639x           21633x 12x   6x         21x   1671x 1671x 1671x 221x 9x 9x   9x 9x 9x 9x     6x 6x   9x 3x 3x 3x     6x   9x   1671x    
import { FeatureCollection, LineString, MultiLineString } from "geojson";
import { useEffect, useState } from "react";
import { PlaceSnapshot, safePlaceUrl, validPlacePoint } from "./places";
 
export const LINE_OVERLAY_INFO = {
  "park-trails": { label: "Park trails", file: "park-trails.json", color: "#168461" },
  "bicycle-network": { label: "Bicycle network", file: "bicycle-network.json", color: "#3c7fd8" },
  "recommended-bike-routes": { label: "Recommended bike routes", file: "recommended-bike-routes.json", color: "#b77909" }
} as const;
export type LineOverlayCategory = keyof typeof LINE_OVERLAY_INFO;
export const LINE_OVERLAY_CATEGORIES = Object.keys(LINE_OVERLAY_INFO) as LineOverlayCategory[];
export const DEFAULT_LINE_OVERLAYS: Record<LineOverlayCategory, boolean> = {
  "park-trails": false, "bicycle-network": false, "recommended-bike-routes": false
};
export const LINE_CAUTION_COLOR = "#d44d4d";
export type LineOverlaySnapshot = FeatureCollection<LineString | MultiLineString,
  { name: string; kind: "standard" | "caution"; detail: string }> &
  Pick<PlaceSnapshot, "version" | "retrievedAt" | "source" | "sourceUrl" | "license" | "licenseUrl" | "coverage"> &
  { category: LineOverlayCategory };
export interface LineOverlayState {
  snapshot?: LineOverlaySnapshot;
  loading: boolean;
  error: boolean;
  retry: () => void;
}
export interface LineOverlayControls {
  shown: Record<LineOverlayCategory, boolean>;
  sources: Record<LineOverlayCategory, LineOverlayState>;
  mapErrors: Record<LineOverlayCategory, boolean>;
  onShown: (category: LineOverlayCategory, shown: boolean) => void;
  onRetry: (category: LineOverlayCategory) => void;
}
const record = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null;
const validLine = (value: unknown) => Array.isArray(value) && value.length >= 2 && value.every(validPlacePoint);
function validGeometry(value: unknown) {
  return record(value) && (value.type === "LineString" ? validLine(value.coordinates) :
    value.type === "MultiLineString" && Array.isArray(value.coordinates) &&
      value.coordinates.length > 0 && value.coordinates.every(validLine));
}
export function parseLineOverlaySnapshot(value: unknown, category: LineOverlayCategory): LineOverlaySnapshot {
  if (!record(value) || value.type !== "FeatureCollection" || value.version !== 1 || value.category !== category ||
      typeof value.retrievedAt !== "string" || !Number.isFinite(Date.parse(value.retrievedAt)) ||
      typeof value.source !== "string" || !safePlaceUrl(value.sourceUrl) ||
      typeof value.license !== "string" || !safePlaceUrl(value.licenseUrl) || typeof value.coverage !== "string" ||
      !Array.isArray(value.features) || !value.features.length ||
      !value.features.every(feature => record(feature) && feature.type === "Feature" &&
        typeof feature.id === "string" && new RegExp(`^portland:${category}:[1-9]\\d*$`).test(feature.id) &&
        record(feature.properties) && typeof feature.properties.name === "string" && Boolean(feature.properties.name.trim()) &&
        typeof feature.properties.detail === "string" &&
        (feature.properties.kind === "standard" || (category === "recommended-bike-routes" && feature.properties.kind === "caution")) &&
        validGeometry(feature.geometry)) ||
      new Set(value.features.map(feature => feature.id)).size !== value.features.length) {
    throw new Error(`Invalid ${category} line snapshot`);
  }
  return { type: "FeatureCollection", version: 1, category, retrievedAt: value.retrievedAt,
    source: value.source, sourceUrl: value.sourceUrl, license: value.license, licenseUrl: value.licenseUrl,
    coverage: value.coverage, features: value.features as LineOverlaySnapshot["features"] };
}
 
const cache = new Map<LineOverlayCategory, LineOverlaySnapshot>();
export function useLineOverlay(category: LineOverlayCategory, enabled: boolean): LineOverlayState {
  const [state, setState] = useState<Omit<LineOverlayState, "retry">>({ loading: false, error: false });
  const [attempt, setAttempt] = useState(0);
  useEffect(() => {
    if (!enabled) return;
    const controller = new AbortController();
    setState(previous => ({ ...previous, loading: true, error: false }));
    async function load() {
      const cached = cache.get(category);
      Iif (cached && attempt === 0) return cached;
      const base = (process.env.PUBLIC_URL || "").replace(/\/$/, "");
      const response = await fetch(`${base}/data/places/${LINE_OVERLAY_INFO[category].file}`, {
        signal: controller.signal, ...(attempt > 0 ? { cache: "reload" as const } : {})
      });
      Iif (!response.ok) throw new Error(`Could not load ${LINE_OVERLAY_INFO[category].label}`);
      return parseLineOverlaySnapshot(await response.json(), category);
    }
    load().then(snapshot => {
      Eif (!controller.signal.aborted) {
        cache.set(category, snapshot);
        setState({ snapshot, loading: false, error: false });
      }
    }).catch(() => {
      Eif (!controller.signal.aborted) setState(previous => ({ ...previous, loading: false, error: true }));
    });
    return () => controller.abort();
  }, [category, enabled, attempt]);
  return { ...state, retry: () => setAttempt(value => value + 1) };
}