Download web/src/customer-grid/MapView.tsx from fsanyoto/loopable: direct link, hf CLI and curl.
- Browser
- Download file 289 kB
-
https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/customer-grid/MapView.tsx
- Command line
-
hf download hf://spaces/fsanyoto/loopable/web/src/customer-grid/MapView.tsx
-
curl -L -o MapView.tsx https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/customer-grid/MapView.tsx
289 kB
// ---------------------------------------------------------------------------
// customer-grid / MapView.tsx
// "Map" is a VIEW beside Grid/List/Calendar/Kanban, not a module: it projects
// the SAME pipeline output the grid paints, so the toolbar count, filters and
// sorts mean exactly what they mean on the grid; only the projection changes.
//
// Wave 8 grows it up (I2/I3/I5/I6, contracts C2/C3/C7):
// I2 wheel/pinch zoom, drag to pan, and a box-select that feeds the grid's
// OWN selection — so the existing "N selected · Add to cohort" bar serves
// the map with no second cohort picker to keep in sync.
// I3 colour pins by any single-select field (`display.colorField`) + legend.
// I5 size pins by any numeric/measure field (`display.sizeField`) + legend.
// I6 a less templatic picture: water wash, land fill, thin C1 strokes,
// graticule, hover halos.
//
// C7 CALL — NO map library, and that call still stands. C7 allowed maplibre-gl
// "with a self-hosted vector/raster-free style"; a tileless maplibre would have
// rendered exactly the geometry below for +230 KB gz on a 251 KB budget.
//
// ⭐⭐ WAVE 37 (R3/R14, W37-T35) — THE MAP NOW FETCHES TILES, AND THE OLD NOTE
// HERE SAID THE OPPOSITE. It read: "Nothing is fetched and no coordinate leaves
// the page unless the user deliberately clicks." That was true for two waves and
// is FALSE now, so it is rewritten rather than left to rot. What is true today:
//
// - a RASTER BASEMAP is fetched, by the browser, straight from the tile
// provider. Panning the map therefore tells that provider roughly where you
// are looking. It does NOT tell them who: no record, no name and no address
// is ever sent, because a tile request carries only a z/x/y grid square that
// millions of other people also request;
// - the provider is a SEAM, not a vendor. `/api/v1/geo/providers` serves a URL
// template plus a credit line, both environment-driven, so pointing this at
// a paid vendor is configuration and not a rewrite. That seam is the whole
// reason R14 could defer the Google key without dropping the feature;
// - the DEFAULT is OpenStreetMap, which needs no key and no billing account.
// Its credit line is a LICENCE TERM and is rendered, not optional;
// - GEOCODING is still not automatic and never will be from here (R3). It has
// its own door, it takes an explicit list of addresses, and it is rate
// limited in code. Nothing on this surface geocodes anything;
// - if the tiles fail to load, the vendored vector basemap below is still
// here and takes over. A map that has lost its network draws the coastline
// it always drew rather than an empty rectangle.
//
// Honesty rules (rule 8b), carried and extended:
// - rows WITHOUT coordinates are never silently hidden: the count line reads
// "N of M mapped", so the unmapped share is the gap between the two numbers;
// - a pin per row at its geocoded position, no clustering and no jitter (two
// customers at one address overlap rather than being drawn where they are
// not);
// - the colour legend STATES it when a field has more choices than the
// palette has entries, rather than recycling a colour onto a second meaning;
// - a row with no value under the size field gets the smallest dot and the
// legend says so — it is never dropped from the map.
// ---------------------------------------------------------------------------
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { LogoLoader } from "../ui/LogoLoader";
import type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent, ReactNode } from "react";
import type { CatalogSpec, Conjunction, Field, FilterNode, Row, ViewConfig } from "./types";
import { API_V1, CREDENTIALS, NAV_MINIMIZE_EVENT, signal } from "../apiContract";
import { formatDisplay } from "./cells";
import { readDataPath } from "./dataPath";
import { AppFrame } from "./AppFrame";
// C1: Routing and Catalog are Odoo Apps; verify_icons.py holds these two marks to TEMPLATES.
import { AppFrameMarks } from "../apps/templateMarks";
import { CatalogApp } from "../apps/catalog/CatalogApp";
import { RouteApplicationMapView } from "../apps/routing/RouteApplicationMapView";
import type { CatalogApplicationDefinition, CatalogViewSpec } from "./CatalogView";
import { applicationTemplateSurface } from "./viewModes";
import { LAND_PATH, LAKE_PATHS } from "./mapGeometry";
import { routingPreferenceKey, bubbleSizeRange, pointRadius, routeFilterSignatureOf } from "./routePrefs";
import type { RoutingCustomerDetail } from "./RouteNav";
import { RouteCustomerPane } from "./RouteNav";
import {
BASEMAP_DETAIL_K,
bubbleRadius,
magnitudeDomain,
cardBox,
clientToUser,
dashPattern,
fitView,
formatDuration,
fromScreen,
googleMapsUrl,
googleRouteUrls,
googleZoomForK,
graticuleOpacity,
hairline,
haversineKm,
isPlottable,
normRect,
parseLatLon,
pathBounds,
planRoute,
pointInPolygon,
project,
rotateAt,
routeFingerprint,
routeRanks,
ROUTE_STOP_CAP,
toScreen,
unproject,
WORLD,
zoomAt,
zoomLimits,
} from "./mapProjection";
import type { GeoStop, Pt, RouteStamp, View } from "./mapProjection";
import { LP_INK, LP_MAP_SELECTED, LP_PURPLE, LP_PURPLE_DEEP, LP_RED, LP_RED_DEEP, LP_ZONE_FILL_OPACITY, LP_ZONE_STROKE_WIDTH } from "./theme";
import { GoogleMapsMark, RouteNav } from "./RouteNav";
import { endpointRoutePlan, normalizedRouteMapLinks } from "./routeLinks";
import {
fetchRouteDeliveryRecipients,
requestRouteDelivery,
routeInventoryPath,
routeApplicationPath,
usesNormalizedCustomerZones,
zoneCollectionPath,
zoneItemPath,
zoneMutationPayload,
} from "./routeZoneApi";
import { mapNavigatorMode, routeSourceStopIds, toggleRouteSelection } from "./routeZoneTypes";
// W51-T28 / R6 + C8 — the wave-51 base kit. Every destructive act on this surface goes through
// the ONE dialog, and every panel registers its Escape claim with the ONE arbiter. Neither is
// re-implemented here: `ConfirmDialog` brings its own portal, focus trap, backdrop and focus
// restore, and `useEscapeClose` brings the topmost-wins stack.
import { ConfirmDialog } from "../ui/ConfirmDialog";
import { useEscapeClose } from "../ui/useEscapeClose";
import type {
MapRouteDto, MapRouteFolderDto, MapRouteSource, MapRouteUpdate, MapZoneDto,
RouteDeliveryRecipientDirectory, RouteDeliveryDto, RouteDeliveryRequest,
RouteSelectionRequest, RouteSelectionResponse,
ZoneGeometry,
} from "./routeZoneTypes";
import "./map.css";
import "../styles/wave46/map-panels.css";
import "../styles/sdlc74/routing.css";
/**
* W37-T35 — THE PROVIDER SEAM, client side.
*
* A URL template and a credit line, nothing else. The renderer never learns which company is
* behind them, which is exactly what makes swapping in a paid provider a config change (R14).
* These constants are the OFFLINE DEFAULT: `/api/v1/geo/providers` overrides them at mount, and
* the map still draws if that call never answers.
*/
interface TileProvider {
url: string;
attribution: string;
attributionUrl: string;
maxZoom: number;
}
const TILES_DEFAULT: TileProvider = {
url: "https://tile.openstreetmap.org/{z}/{x}/{y}.png",
attribution: "© OpenStreetMap contributors",
attributionUrl: "https://www.openstreetmap.org/copyright",
maxZoom: 19,
};
/** How many tiles one frame may paint. A pathological zoom/pan otherwise asks for thousands, and
* a shared free tile service is exactly the wrong place to find that out. */
const TILE_BUDGET = 240;
/** ⭐ OWNER ITEM 1 (2026-08-23) — degrees per click of Rotate left / Rotate right, the owner's
* own number: *"every click is say rotating the map by 5 degrees"*. 72 clicks is a full turn,
* which is why Fit to data doubles as the way back to north. */
const ROTATE_STEP = 5;
/**
* CSS pixels per SVG user unit, at the width this view is normally painted.
*
* ⛔ MIRRORED FROM `mapProjection.googleZoomForK`, WHICH HARDCODES THE SAME 1.08 AND DOES NOT
* EXPORT IT. Two copies of one number is [[one-question-two-normalizers]], so `verify_map.py`
* asserts the constant still reads 1.08 over there. If that gate goes red, these two have drifted
* and the tile grid will be one zoom level off the hand-off link it is supposed to agree with.
*/
const CSS_PX_PER_UNIT = 1.08;
/** The inverse of `googleZoomForK`: the camera `k` at which one 256px tile paints at ~256 CSS px.
* Used for the zoom ceiling, so "as far in as the provider actually serves" is a number and not
* a guess. */
function kForTileZoom(z: number): number {
return (256 * Math.pow(2, z)) / (WORLD * CSS_PX_PER_UNIT);
}
/** Consecutive tile errors before the vendored vector basemap takes back over. Three rather than
* one: a single 404 at the edge of coverage is normal and is not an outage. */
const TILE_FAIL_LIMIT = 3;
const VIEW_W = 1000;
const VIEW_H = 620;
const R_MIN = 3.2;
const R_MAX = 15;
const R_PLAIN = 4.5;
const R_NULL = 2.6;
/** A synthetic route-only id. Odoo record ids are positive, so zero cannot become a customer. */
const DEPOT_PID = 0;
/**
* ⭐⭐ OWNER ITEM 9 — ONE SEARCHABLE RECORD PICKER, used twice.
*
* The owner asked for search in two places at once: the Start dropdown, and a way to add a record
* by looking it up in the database. Those are the same control over two different pools, so this
* is one component rather than two that drift.
*
* ⛔ IT IS A FILTERED LIST, NOT A FLOATING COMBOBOX, and that is deliberate. The route panel is
* already an absolutely positioned `<aside>` with its own scroll container; a popup listbox inside
* it needs portal + placement + reposition-on-scroll machinery to sit right, and every one of
* those is a way for the list to land off-screen. Expanding IN PLACE cannot be mispositioned.
*
* ⚠ THE CAP IS STATED, NEVER SILENT (standing rule 1's second sentence). A book of 3,600 customers
* cannot paint 3,600 rows into a 360px panel, so the list shows the first `LIST_CAP` matches and
* SAYS how many more the search found; it does not quietly show a tenth of the answer.
*/
const PICKER_LIST_CAP = 40;
function RecordPicker({
label,
placeholder,
emptyNote,
options,
currentPid,
onPick,
}: {
label: string;
placeholder: string;
emptyNote: string;
options: { pid: number; title: string }[];
/** Named on the trigger when this picker chooses one of the stops (the Start). */
currentPid?: number | null;
onPick: (pid: number) => void;
}) {
const [open, setOpen] = useState(false);
const [q, setQ] = useState("");
const needle = q.trim().toLowerCase();
const matches = useMemo(() => {
if (!needle) return options;
return options.filter((o) => o.title.toLowerCase().includes(needle));
}, [options, needle]);
const shown = matches.slice(0, PICKER_LIST_CAP);
const current = currentPid == null ? null : options.find((o) => o.pid === currentPid) || null;
return (
<div className="cg-route-picker">
<span className="cg-route-picker-label">{label}</span>
<button
type="button"
className="cg-route-picker-trigger"
aria-expanded={open}
onClick={() => {
setOpen((v) => !v);
setQ("");
}}
title={open ? `Close the ${label.toLowerCase()} search` : `Search records by name`}
>
<span className="cg-route-picker-current">
{current ? current.title : placeholder}
</span>
<svg viewBox="0 0 16 16" aria-hidden="true" className="cg-route-picker-caret">
<path d="M4 6.5 8 10.5l4-4" />
</svg>
</button>
{open && (
<div className="cg-route-picker-panel">
<input
className="cg-input cg-route-picker-search"
type="search"
autoFocus
value={q}
placeholder="Search records"
aria-label={`Search records for ${label.toLowerCase()}`}
onChange={(e) => setQ(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Escape") {
e.stopPropagation();
setOpen(false);
}
}}
/>
{shown.length === 0 ? (
<span className="cg-route-picker-empty">{needle ? "No record matches that." : emptyNote}</span>
) : (
<div className="cg-route-picker-list" role="listbox">
{shown.map((o) => (
<button
key={o.pid}
type="button"
role="option"
aria-selected={o.pid === currentPid}
className={
"cg-route-picker-opt" + (o.pid === currentPid ? " is-on" : "")
}
onClick={() => {
onPick(o.pid);
setOpen(false);
setQ("");
}}
>
{o.title}
</button>
))}
</div>
)}
{matches.length > shown.length && (
<span className="cg-route-picker-empty">
Showing the first {shown.length.toLocaleString()} of{" "}
{matches.length.toLocaleString()} matches. Keep typing to narrow them.
</span>
)}
</div>
)}
</div>
);
}
/** ⭐ OWNER ITEM 7 — the travel modes `routes_geo.py` answers. */
type TravelMode = "driving" | "walking";
type RouteModeOffer = { key: TravelMode; label: string; available: boolean };
/** Matches `routes_geo._ROUTE_MODES`, so the toggle is right before the provider call lands. */
const TRAVEL_MODES_DEFAULT: RouteModeOffer[] = [
{ key: "driving", label: "Driving", available: true },
{ key: "walking", label: "Walking", available: true },
];
/** ⚠ ONE frozen empty set, not `new Set()` in a `useState` initialiser argument: the bare call
* builds a NEW set on every render, and React only ignores it because the initialiser is read
* once. Hoisting it says so, and keeps the identity stable for the memos that depend on it. */
const EMPTY_PIDS: ReadonlySet<number> = new Set<number>();
interface RouteDepot {
address: string;
lat: number;
lon: number;
}
/**
* The Map starts in the Group-purple family. Colour-by retains its distinct
* series after that first default, while an unencoded point never regresses to blue.
* 20%-darkened variants, exactly as the contract specifies for series colour.
* `fill` is the pastel; `line` is a darker companion, because a C1 pastel
* measures 1.4-1.9:1 on white and a fill alone would be a smudge (the same
* measurement that drove the I7c amendment).
*/
const SERIES: { fill: string; line: string }[] = [
{ fill: LP_PURPLE, line: LP_PURPLE_DEEP },
{ fill: "#A5D8B4", line: "#5E9C74" },
{ fill: "#F5D989", line: "#B39A46" },
{ fill: "#F0A8A0", line: "#B76D65" },
{ fill: "#7E99C2", line: "#4A6790" },
{ fill: "#84AD91", line: "#4C7A5C" },
{ fill: "#C4AE6E", line: "#8C7838" },
{ fill: "#C0867F", line: "#8A5049" },
];
/** Anything past the palette, plus the blank bucket. Neutral ON PURPOSE: a
* ninth colour that repeats the first would make two meanings look identical. */
const OVERFLOW = { fill: "#D7DBE3", line: "#8A909C" };
const DEFAULT_PIN = { fill: LP_PURPLE, line: LP_PURPLE_DEEP };
const NEGATIVE_PIN = { fill: LP_RED, line: LP_RED_DEEP };
const ZONE_COLOR_CHOICES = [
{ value: LP_PURPLE, label: "Purple" },
{ value: "#A5D8B4", label: "Green" },
{ value: "#F5D989", label: "Yellow" },
{ value: "#F0A8A0", label: "Red" },
{ value: "#C7B7E8", label: "Purple" },
];
/**
* ⛔⛔ W47-T02, CAUSE 1 OF THE BLACK BLOB (owner instruction 21, reference image "ERROR 18 Black
* Blob on the Map.png"): AN SVG SHAPE WITH NO `fill` PAINTS BLACK. Not transparent, not skipped:
* black is SVG's INITIAL `fill`, so `fill={zone.color}` with an empty colour renders a solid black
* shape the size of the whole boundary. `saveZone` defaults a colour on ITS OWN write path only
* (`zoneColor || existing?.color || ZONE_COLOR_CHOICES[0].value`), so a Zone that arrived any other
* way - an older record, an import, a PATCH that omitted the key, a normalized Customer Zone - is
* colourless at every render site. `MapZoneDto.color` is TYPED `string`, which is precisely why
* this survived so long: the type is a claim about the API, not a guarantee about the JSON.
*
* ⭐ NORMALISED ONCE, HERE, and called by EVERY zone render site rather than sprinkled over the
* individual `fill`/`stroke` attributes, so a future fourth zone shape cannot miss it the way the
* keyboard-draft preview was missed before. The fallback is the same value `saveZone` writes, so a
* repaired Zone does not change colour the moment somebody finally saves it.
*
* ⚠ THIS IS A RENDER-PATH FIX ON PURPOSE. A colourless Zone must still DRAW, in a visible
* fallback; defaulting the colour on the write path or filtering the Zone out of the list would
* hide the boundary, which is a different defect.
*/
export function zonePaint(color?: string | null): string {
return typeof color === "string" && color.trim() ? color.trim() : ZONE_COLOR_CHOICES[0].value;
}
/**
* The STATED screen bound for a Zone radius: the DIAGONAL of the `VIEW_W` x `VIEW_H` canvas,
* i.e. corner to corner of the 1000x620 viewBox, ~1176.6 user units.
* ⭐ WHY THE DIAGONAL RATHER THAN `VIEW_W` OR `VIEW_H`: the camera rotates - `tf` puts a `rotate`
* between the translate and the scale - so width and height swap roles at 90 degrees, and the
* diagonal is the only single number that still covers the frame at every angle.
*/
const ZONE_RADIUS_SCREEN_MAX = Math.hypot(VIEW_W, VIEW_H);
/**
* ⛔⛔ W47-T02, CAUSE 2 OF THE BLACK BLOB. INDEPENDENT OF CAUSE 1, EQUALLY REAL, AND IT SHIPS TOO.
* `zoneCircles` computed `radius: Math.abs(edge.x - center.x)` from a projected longitude delta
* and nothing bounded it. A `radiusMeters` that is huge, non-finite or negative - a bad import, a
* NaN centre latitude driving the `cos` term, a degrees/metres mix-up - projects to a radius of
* millions of user units and paints a filled disc over the entire canvas: the same "really Huge
* Blob" symptom arriving from the other direction. Whichever cause a previous attempt found, the
* other one was still there, which is why the owner has reported this repeatedly.
*
* `radius` is in the PRE-TRANSFORM user space of `<g transform={tf}>`, so the on-screen radius is
* `radius * k`. Dividing the bound by `k` is what makes this a SCREEN bound at every zoom rather
* than a user-space one that goes slack the moment somebody zooms in.
*
* ⚠ THE TRADEOFF, STATED RATHER THAN HIDDEN: clamping an off-centre monster can uncover canvas
* that the unclamped disc used to cover. Accepted deliberately - a circle whose screen radius
* exceeds the viewport diagonal is the defect, not a use case, so a distance-aware bound would
* buy nothing real and would cost an invariant a gate can hold.
*
* ⛔ NON-FINITE AND NEGATIVE ARE FOLDED IN HERE, not only the too-large case: SVG `r` must be a
* finite number >= 0, and `r="NaN"` or `r="-5"` is the unbounded case wearing a different mask.
*/
export function clampZoneRadius(radius: number, k?: number): number {
if (!Number.isFinite(radius) || radius <= 0) return 0;
const zoom = typeof k === "number" && Number.isFinite(k) && k > 0 ? k : 1;
return Math.min(radius, ZONE_RADIUS_SCREEN_MAX / zoom);
}
/** Move a durable GeoJSON boundary without changing its topology or membership snapshot. */
export function translateZoneGeometry(
geometry: ZoneGeometry, delta: { lon: number; lat: number }
): ZoneGeometry {
if (geometry.type === "Circle") return {
type: "Circle",
center: [Math.max(-180, Math.min(180, geometry.center[0] + delta.lon)), Math.max(-90, Math.min(90, geometry.center[1] + delta.lat))],
radiusMeters: geometry.radiusMeters,
};
const point = (pair: number[]) => [
Math.max(-180, Math.min(180, pair[0] + delta.lon)),
Math.max(-90, Math.min(90, pair[1] + delta.lat)),
];
if (geometry.type === "Polygon") {
return { type: "Polygon", coordinates: (geometry.coordinates as number[][][])
.map((ring) => ring.map(point)) };
}
return { type: "MultiPolygon", coordinates: (geometry.coordinates as number[][][][])
.map((polygon) => polygon.map((ring) => ring.map(point))) };
}
/** How many draggable corners one boundary ring may show. A shape a person DREW has a handful;
* anything past this was traced by the lasso, one coordinate per pointermove, and its dots
* would obscure the Zone rather than let anyone reshape it. See the render site. */
const ZONE_VERTEX_HANDLE_MAX = 24;
/** Where a single vertex lives inside a boundary. `polygonIndex` is meaningless for a plain
* Polygon (it is always 0) and load-bearing for a MultiPolygon; both are carried so one
* address works for either shape. */
interface ZoneVertexAddress {
polygonIndex: number;
ringIndex: number;
vertexIndex: number;
}
/**
* ⭐ W46-T28 — MOVE ONE VERTEX, leaving every other point where it was. Owner instruction 16:
* *"the zone vertices should be a dot that is draggable so I can minimize or expand a zone."*
* `translateZoneGeometry` above is the whole-boundary sibling; this is the reshape.
*
* ⛔ A GeoJSON RING IS CLOSED: its first and last coordinate are THE SAME POINT stored twice.
* Writing only the index that was grabbed tears the ring open at that seam, and the polygon then
* renders with a slit that no gate can see. Vertex 0 and the closing vertex always move
* together, which is the one rule this function exists to hold.
*/
export function moveZoneVertex(
geometry: ZoneGeometry, at: ZoneVertexAddress, to: { lon: number; lat: number }
): ZoneGeometry {
if (geometry.type === "Circle") return geometry;
const moved = [
Math.max(-180, Math.min(180, to.lon)),
Math.max(-90, Math.min(90, to.lat)),
];
const editRing = (ring: number[][]) => {
if (at.vertexIndex < 0 || at.vertexIndex >= ring.length) return ring;
const next = ring.map((pair) => [...pair]);
const last = next.length - 1;
const closed = last > 0 && next[0][0] === next[last][0] && next[0][1] === next[last][1];
next[at.vertexIndex] = [...moved];
if (closed && at.vertexIndex === 0) next[last] = [...moved];
if (closed && at.vertexIndex === last) next[0] = [...moved];
return next;
};
if (geometry.type === "Polygon") {
return { type: "Polygon", coordinates: (geometry.coordinates as number[][][])
.map((ring, ringIndex) => (ringIndex === at.ringIndex ? editRing(ring) : ring)) };
}
return { type: "MultiPolygon", coordinates: (geometry.coordinates as number[][][][])
.map((polygon, polygonIndex) => (polygonIndex !== at.polygonIndex ? polygon
: polygon.map((ring, ringIndex) => (ringIndex === at.ringIndex ? editRing(ring) : ring)))) };
}
/** C3's durable map-domain DTO. Zones are not generic fields: geometry, visibility and the
* membership snapshot only make sense to this projection. */
type MapZone = MapZoneDto;
interface ZoneMove {
zone: MapZone;
geometry: ZoneGeometry;
start: Pt;
}
/** An in-flight vertex drag. It carries the geometry it started from, so every pointermove
* recomputes from the ORIGINAL rather than compounding its own previous answer. */
interface ZoneVertexDrag extends ZoneVertexAddress {
zone: MapZone;
geometry: ZoneGeometry;
}
/** Immutable provenance supplied by the host grid for a scheduled route snapshot. */
export interface RouteSourceView {
id: string;
name: string;
/** Exact saved config the API compares before minting immutable route provenance. */
config: ViewConfig;
}
/* ═══════ R10 (W50-T14) — THE MAP REMEMBERS WHERE YOU WERE, PER PERSON ═══════
*
* Owner ruling R10: map state (viewport, open route, panel) is remembered per person, per view,
* in this browser, and it NEVER writes the saved view.
*
* ⛔ THE SECOND HALF IS A PROHIBITION, NOT a nice-to-have. This is a READER's preference and it
* goes to `localStorage` and nowhere else: no `persistView`, no view upsert, no mutation of
* `activeView.config` and no `onManagedRouteViewState` call on this path. A colleague opening the
* same saved view must see the view as it was SAVED, not wherever the last person left the camera.
*
* ⚠ `localStorage` CAN THROW OUTRIGHT (private mode, blocked site data), so every read and every
* write is wrapped and the map draws correctly with no stored value at all. Same discipline as
* `zoneFillOpacity` below, and for the same reason.
*
* ⚠ A STORED VIEWPORT IS VALIDATED, NOT TRUSTED. It is restored BEFORE the first auto-fit and
* suppresses it, so a corrupt `k` of zero or a NaN translate would leave a permanently blank map.
* Every number is range-checked on the way in instead.
*/
const MAP_MEMORY_PREFIX = "cg-map:";
/** How long the map settles before a pan or a zoom is written. A wheel gesture is dozens of
* renders; one write per render would be a storage call per animation frame. */
const MAP_MEMORY_DEBOUNCE_MS = 400;
/** What one reader's browser remembers for one saved view. Every field is optional: a memory
* written by an older build must never stop the map drawing. */
interface MapMemory {
view?: { k: number; tx: number; ty: number; rot?: number };
routeId?: string | null;
navigator?: "routes" | "zones" | null;
}
/** Apps remember their own panel and camera; standalone maps retain the saved View key. */
function mapMemoryKey(tableKey: string, viewId: string | null | undefined, applicationId?: string): string | null {
if (applicationId) return routingPreferenceKey(`${MAP_MEMORY_PREFIX}${tableKey}`, applicationId);
if (!tableKey || !viewId) return null;
return `${MAP_MEMORY_PREFIX}${tableKey}:${viewId}`;
}
function readMapMemory(key: string | null): MapMemory | null {
if (!key) return null;
try {
const raw = window.localStorage.getItem(key);
if (!raw) return null;
const parsed = JSON.parse(raw) as MapMemory | null;
if (!parsed || typeof parsed !== "object") return null;
const stored = parsed.view;
const view = stored
&& Number.isFinite(stored.k) && stored.k > 0
&& Number.isFinite(stored.tx) && Number.isFinite(stored.ty)
&& (stored.rot === undefined || Number.isFinite(stored.rot))
? { k: stored.k, tx: stored.tx, ty: stored.ty, rot: stored.rot }
: undefined;
const mode = parsed.navigator === "routes" || parsed.navigator === "zones" ? parsed.navigator : null;
const routeId = typeof parsed.routeId === "string" && parsed.routeId ? parsed.routeId : null;
return { view, routeId, navigator: mode };
} catch {
return null;
}
}
function writeMapMemory(key: string | null, memory: MapMemory): void {
if (!key) return;
try {
window.localStorage.setItem(key, JSON.stringify(memory));
} catch {
/* a reader who cannot store a preference still gets a working map for this session */
}
}
interface MapPoint {
pid: number;
title: string;
p: Pt;
/** The ORIGINAL coordinate, kept beside the projected one so the Google
* hand-off links to the exact geocode we plotted rather than to a round-trip
* through the projection. */
lat: number;
lon: number;
colorKey: string | null;
size: number | null;
/** The RAW cell values behind the two encodings. The hover card formats these
* with `formatDisplay`, the grid's own formatter — `colorKey` is trimmed for
* bucketing and `size` is coerced for the bubble scale, so neither is what a
* human should be shown. */
colorVal: Row[keyof Row];
sizeVal: Row[keyof Row];
}
function coord(v: Row[keyof Row]): number | null {
if (v == null || v === "") return null;
const n = typeof v === "number" ? v : Number(v);
return Number.isFinite(n) ? n : null;
}
type CoordinateFields = { latitude: Field; longitude: Field };
/** Resolve one row through database setup, then legacy composite setup, then built-in transport. */
function rowCoordinates(
row: Row,
coordinateFields?: CoordinateFields,
coordField?: Field,
sessionCoordinates?: ReadonlyMap<number, { lat: number; lon: number }>,
): { lat: number; lon: number } | null {
const sessionPoint = sessionCoordinates?.get(row.pid) ?? null;
if (coordinateFields) {
const lat = coord(row[coordinateFields.latitude.key]);
const lon = coord(row[coordinateFields.longitude.key]);
return lat == null || lon == null || !isPlottable(lat, lon) ? sessionPoint : { lat, lon };
}
if (coordField?.key) return parseLatLon(row[coordField.key]) ?? sessionPoint;
const lat = coord(row.lat);
const lon = coord(row.lon);
return lat == null || lon == null || !isPlottable(lat, lon) ? sessionPoint : { lat, lon };
}
function numOrNull(v: Row[keyof Row]): number | null {
if (v == null || v === "") return null;
const n = typeof v === "number" ? v : Number(v);
return Number.isFinite(n) ? n : null;
}
/** W46-T17 — the draw glyph for the Zone arming button. A pen over a dotted
* outline: what the button does, in the same 16x16 box and the same
* `currentColor`/`fill="none"` idiom as the camera controls below.
* ⚠ It lives here rather than in `iconShapes.ts` only because that shared
* vocabulary belongs to another lane this wave. Its home there is owed. */
function DrawZoneIcon() {
return (
<svg className="cg-zone-draw-ico" viewBox="0 0 16 16" aria-hidden="true"
fill="none" stroke="currentColor" strokeWidth="1.4"
strokeLinecap="round" strokeLinejoin="round">
<path d="M2.4 9.6V3.2h5.2" strokeDasharray="2 1.6" />
<path d="M2.4 12.8h4.2" strokeDasharray="2 1.6" />
<path d="M13.6 3.1 8.2 8.5l-.7 2.5 2.5-.7 5.4-5.4z" />
</svg>
);
}
export function MapViewSurface(props: Parameters<typeof MapViewSurfaceContent>[0]) {
return <MapViewSurfaceContent key={JSON.stringify([props.tableKey, props.applicationId ?? ""])} {...props} />;
}
function MapViewSurfaceContent({
rows,
field,
coordinateFields,
coordField,
colorField,
sizeField,
selectedPids,
onSelectPids,
onOpen,
onGeocoded,
onRouteFieldCreated,
routePanelOpen: requestedRoutePanelOpen,
allRows,
activeView,
tableKey,
onManagedRouteViewState,
filterRestore = null,
onZoneChanged,
applicationName,
applicationId,
routingFilters,
customerDetail = null,
onCustomerBack,
routeApplication = false,
geocodeSessionOnly = false,
hosted = false,
recordsPending = false,
pinClickSelects = false,
}: {
/** DISTINCT data rows from the full pipeline, overlay edits layered — the
* calendar/kanban contract, verbatim. */
rows: Row[];
/** The locked identity column — pin tooltips and aria labels. */
field: Field;
/** The database's configured latitude and longitude fields, resolved by the caller.
*
* ⛔ OPTIONAL, AND THE ABSENT CASE IS NOT "NO MAP" — it is the `lat`/`lon` column pair the
* customers mirror has always carried. */
coordinateFields?: CoordinateFields;
/**
* Legacy composite location field from an older saved View or prerelease database setup.
* It remains a backwards-compatible fallback after the database-owned coordinate pair.
*
* That fallback is the ONLY reason this change is not a migration: every map without a custom
* source keeps painting exactly what it painted before.
*/
coordField?: Field;
/** I3 — the view's `display.colorField`, already resolved to a real field. */
colorField?: Field;
/** I5 — the view's `display.sizeField`, already resolved to a real field. */
sizeField?: Field;
/** The grid's selection, shared: pins render selected, and the existing
* selection bar is what offers "Add to cohort" (C3). */
selectedPids: ReadonlySet<number>;
onSelectPids: (pids: number[], mode: "replace" | "add") => void;
onOpen: (pid: number) => void;
/**
* W37-T37 (R4 / C7) — where looked-up coordinates go. The map does the ASKING; the host does the
* WRITING, through whichever cell door it already owns.
*
* ⛔ THE MAP DELIBERATELY HAS NO WRITER OF ITS OWN. A second path that can put values into cells
* would sit outside every guard the grid's own edit door carries, and this view is the last place
* that should own one. Absent callback = the control does not render unless a Route Application
* explicitly keeps its results in this map session, so every lookup still has somewhere to land.
*/
onGeocoded?: (writes: { pid: number; value: string }[]) => void;
onRouteFieldCreated?: (key: string) => void;
routePanelOpen: boolean;
/** The real active View driving this map, never a map-local synthetic id. */
activeView: RouteSourceView | null;
/** Canonical database identity for durable, table-scoped Zones. */
tableKey: string;
/** C2 handoff: the server alone returns the managed route-membership clause. */
onManagedRouteViewState?: (viewState: Record<string, unknown>, applicationId?: string) => void;
/** S72-T60: the host restored saved filters. A change to exactly this signature is a restore,
* so it keeps the route selection and posts nothing. Each `seq` is honoured once. */
filterRestore?: { seq: number; signature: string } | null;
/** Customer Zones also project into the read-only grid field, so a successful normalized
* mutation invalidates the host row payload instead of leaving that projection stale. */
onZoneChanged?: (applicationId?: string) => void;
/** The saved Routing App name and the identity that scopes its assets and preferences. */
applicationName?: string;
applicationId?: string;
/** The host supplies its existing filter controls above the saved Routes. */
routingFilters?: ReactNode;
customerDetail?: RoutingCustomerDetail | null;
onCustomerBack?: () => void;
/** Opens the Routes navigator as presentation state for a Routing Application. The host's
* ordinary route toggle remains authoritative everywhere else. */
routeApplication?: boolean;
/** Route templates may map an address without owning a coordinate cell. Successful lookups
* stay in this mounted map so the Application can plot them without inventing a database field. */
geocodeSessionOnly?: boolean;
/**
* ⭐⭐ OWNER ITEM 9 — THE WHOLE BOOK, so a stop can be added that the VIEW filtered out.
*
* ⛔ "UNFILTERED" MEANS UNFILTERED BY THE VIEW, NOT UNWALLED, and the distinction is the whole
* safety of this prop. The host passes `scopedRows`, which is the row set AFTER `allowed_pids`
* and the business-unit scope and BEFORE the view's own filters and search. So a person
* planning a day can reach a customer their current filter hides, and cannot reach one their
* book does not contain. Absent = the picker does not render, rather than rendering empty.
*/
allRows?: Row[];
/** S72-T63 / C3: a grid mounted at an address. The map then never reads `location.hash`. */
hosted?: boolean;
recordsPending?: boolean;
/** Table opts in. Direct surface consumers retain their existing pin gestures. */
pinClickSelects?: boolean;
}) {
const routingAlive = useRef(true);
useEffect(() => {
routingAlive.current = true;
return () => { routingAlive.current = false; };
}, []);
const routingFetch = useCallback((path: string, init?: RequestInit) => {
if (!routingAlive.current) return Promise.reject(new DOMException("Routing App closed", "AbortError"));
return fetch(routeApplicationPath(path, applicationId), init);
}, [applicationId]);
const [hoverPid, setHoverPid] = useState<number | null>(null);
// R23 makes the Routing app's rail constant. Previously the host prop and local seed could
// disagree: Escape could close the seed and a host mode change could clear the prop. Neither
// path can close the app's rail now; the Data routing view still follows the host prop.
const routePanelOpen = routeApplication || requestedRoutePanelOpen;
/* R10 — READ ON MOUNT, BEFORE THE FIRST FIT, and that is why this is a lazy initializer rather
than an effect. The auto-fit below seeds `view` from the first `fit` it can compute; a restore
that ran afterwards would be overwritten by it, and one that ran just before would still have
painted the fitted camera for a frame. Seeding the state IS the ordering. */
const [restoredMap] = useState<MapMemory | null>(() => readMapMemory(mapMemoryKey(tableKey, activeView?.id, applicationId)));
/* ⚠ DECLARED HERE, AT THE TOP, AND NOT BESIDE THE `view` STATE THAT CONSUMES IT. The Route and
navigator restore effects far below take `restoredMap` as a dependency, and a dependency array
is evaluated DURING render — a `const` declared later in this body is in its temporal dead zone
at that point and throws, even though the effect callback itself would have run fine. */
// I18-R — the route planner. Off until asked for: a route drawn over a
// selection nobody asked to route is just clutter.
const [routeOn, setRouteOn] = useState(false);
/** Route navigation is an index first; planning begins only after the explicit Create route
* action or an existing saved route has been opened. */
/** ⭐⭐ OWNER 2026-08-31 - *"wtf I don't see the button to make it either 1 single trip or
* round trip. The algorithm was there its not being displayed anymore"*. Correct, and the
* record was in the code: this state's ONLY writer, `setRoundTrip`, sat in the retired
* `void []` compatibility list below, so the value was pinned at false with no control
* anywhere while `planRoute`, `twoOptOrder`, `tourLength` and `routes_geo.py` all still read
* it. It lives HERE, not in `RouteNav`, because the drawn `plan` and the panel's drive time
* have to answer the same question - two copies is how they come to disagree. */
const [roundTrip, setRoundTrip] = useState(false);
const [routeStartPid, setRouteStartPid] = useState<number | null>(null);
const [routeEndPid, setRouteEndPid] = useState<number | null>(null);
const askRoadRef = useRef(false);
/**
* W37-T36 — A HAND-PICKED STOP ORDER, pids in visiting sequence, or null for the planner's.
*
* The planner solves for distance; a person routing a day of visits is solving for an
* appointment at eleven. So the arithmetic proposes and the human disposes, and the foot row's
* `Update calculation` hands it back (wave 41 / R13: setting this to null IS the re-solve, and
* it now travels with the road refetch rather than beside it).
* Kept as pids rather than indices because the selection can change underneath it.
*/
const [routeOrder, setRouteOrder] = useState<number[] | null>(null);
/**
* ⛔ OWNER ITEM 6 — THE DEPOT UI IS GONE AND THIS STATE DELIBERATELY IS NOT. The owner removed
* the "Optional route start" section: the start is the record dropdown and nothing else. What
* stays is the PLUMBING it fed (`depotPoint` -> `routable` -> `plan.depot`, and the pin), so
* this is a hotfix that removes a control rather than a refactor that removes a concept, and a
* column somebody already saved with a depot still round-trips through the server untouched
* (nothing in this file SENDS the key, so `route_order_write` preserves what it stored).
* It is therefore always null now, and `Clear` is what keeps that honest.
*/
const [depot, setDepot] = useState<RouteDepot | null>(null);
/**
* ⭐ OWNER ITEM 7 — DRIVING OR WALKING, and the modes come from the SERVER rather than being
* hardcoded here: a mode this deployment has no router for must not be offered
* ([[permitted-is-not-answerable]]). The default list matches `routes_geo.py`'s own, so the
* toggle works before the provider call lands and keeps working if it never does.
*/
const [travelMode, setTravelMode] = useState<TravelMode>("driving");
const [travelModes, setTravelModes] = useState<RouteModeOffer[]>(TRAVEL_MODES_DEFAULT);
/**
* ⭐⭐ OWNER ITEM 9 — records added to the route BY HAND, from outside the view's filter.
*
* ⛔ THEY JOIN THE MAP'S OWN ROW SET RATHER THAN A PARALLEL STOP LIST, which is what keeps the
* counts one story: an added record gets a pin, gets counted in "N of M mapped", and lands in
* the "no location, so not routed" chip if it has no coordinate. A second list beside `points`
* would have had to re-derive every one of those and would have drifted from the first.
*/
const [addedPids, setAddedPids] = useState<ReadonlySet<number>>(EMPTY_PIDS);
/** C3 Zone chooser/editor state. `null` means the tenant read has not answered; an empty
* array is an honest, editable no-Zones state. */
const [zones, setZones] = useState<MapZone[] | null>(null);
/** C2 named-route read model. */
const [namedRoutes, setNamedRoutes] = useState<MapRouteDto[]>([]);
// `[]` cannot tell "not read yet" from "none": RouteNav says Loading until the first read answers.
const [routesLoaded, setRoutesLoaded] = useState(false);
// A failed read is not "no routes": RouteNav shows a load error and keeps the last good list.
const [routesLoadError, setRoutesLoadError] = useState(false);
const [routeFolders, setRouteFolders] = useState<MapRouteFolderDto[]>([]);
const [routeDeliveryRecipients, setRouteDeliveryRecipients] = useState<RouteDeliveryRecipientDirectory | null>(null);
const [deliveryRecipientError, setDeliveryRecipientError] = useState<string | null>(null);
const [createdRoute, setCreatedRoute] = useState<MapRouteDto | null>(null);
const [selectedRouteIds, setSelectedRouteIds] = useState<ReadonlySet<string>>(new Set());
/** The Route detail is the only pin-edit target. Route selection never chooses it implicitly. */
const [activeRouteId, setActiveRouteId] = useState<string | null>(null);
const pendingInboxRoute = useRef<string | null>(null);
useEffect(() => {
const openRoute = (event: Event) => {
const routeId = String((event as CustomEvent<{ routeId?: string }>).detail?.routeId ?? "");
if (!routeId) return;
pendingInboxRoute.current = routeId;
setActiveRouteId(routeId);
};
window.addEventListener("aios:route-open", openRoute);
return () => window.removeEventListener("aios:route-open", openRoute);
}, []);
useEffect(() => {
// C3: a hosted map has no page address, so a Route opens only through `aios:route-open`.
if (hosted) return;
const openHashRoute = () => {
const queryAt = window.location.hash.indexOf("?");
if (queryAt < 0) return;
const routeId = new URLSearchParams(window.location.hash.slice(queryAt + 1)).get("route");
if (!routeId) return;
pendingInboxRoute.current = routeId;
setActiveRouteId(routeId);
};
openHashRoute();
window.addEventListener("hashchange", openHashRoute);
return () => window.removeEventListener("hashchange", openHashRoute);
}, [hosted]);
const [routePinPrompt, setRoutePinPrompt] = useState<{
routeId: string; customerPid: number; title: string; present: boolean;
} | null>(null);
const [routePinNotice, setRoutePinNotice] = useState<string | null>(null);
const [routePinBusy, setRoutePinBusy] = useState(false);
/* ⭐ W51-T28 / R6 — THE TWO PENDING CONFIRMS, HOISTED TO THE COMPONENT so the dialog outlives
the control that opened it. Both replaced a `window.confirm`, which blocked the JS thread and
therefore needed no state at all; a real dialog paints on a later frame, so the subject of the
question has to be held somewhere that survives that frame. */
const [pendingRouteInclude, setPendingRouteInclude] = useState<MapRouteDto | null>(null);
const [pendingZoneDelete, setPendingZoneDelete] = useState<MapZone | null>(null);
const [managedRouteViewState, setManagedRouteViewState] = useState<Record<string, unknown> | null>(null);
const [routeSelectionWarning, setRouteSelectionWarning] = useState<string | null>(null);
const [activeZoneIds, setActiveZoneIds] = useState<ReadonlySet<string>>(new Set());
const [zoneNavigatorOpen, setZoneNavigatorOpen] = useState(false);
const [zoneEditorOpen, setZoneEditorOpen] = useState(false);
const [zoneEditorId, setZoneEditorId] = useState("");
const [zoneName, setZoneName] = useState("");
const [zoneColor, setZoneColor] = useState(ZONE_COLOR_CHOICES[0].value);
/* ⭐⭐ OWNER, 2026-08-31: *"let's make the Zone opacity toggleable under the Zone configuration
module"*, in the same breath as correcting the fill to 80%. This state is the SINGLE WRITER of
both seams contract C1 names -- it drives the `--lp-zone-fill` custom property inline on
`.cg-mapview` AND the keyboard draft's `fillOpacity` attribute -- so the two can no longer
drift by hand, which is what C1 was asking a person to prevent.
⚠ A DISPLAY PREFERENCE, NOT ZONE DATA, and that is a deliberate scope call on a hotfix. It is
stored per reader in `localStorage` rather than on the Zone record: persisting it server-side
would mean a `MapZoneDto` field, a route and a store write, which is a schema change and not a
hotfix. If the owner wants opacity to travel WITH a Zone to other viewers, that is the
follow-up this comment exists to name.
⚠ `localStorage` can throw outright (private mode, blocked site data), so every read and
write is guarded and falls back to the token rather than leaving the map unpainted. */
const [zoneFillOpacity, setZoneFillOpacity] = useState<number>(() => {
try {
const raw = window.localStorage.getItem("cg-zone-fill-opacity");
const parsed = raw === null ? NaN : Number(raw);
return Number.isFinite(parsed) && parsed >= 0 && parsed <= 1 ? parsed : LP_ZONE_FILL_OPACITY;
} catch {
return LP_ZONE_FILL_OPACITY;
}
});
useEffect(() => {
try {
window.localStorage.setItem("cg-zone-fill-opacity", String(zoneFillOpacity));
} catch {
/* a reader who cannot store a preference still gets to SET one for this session */
}
}, [zoneFillOpacity]);
const [zoneDrawShape, setZoneDrawShape] = useState<"polygon" | "circle">("polygon");
const [drawnZoneGeometry, setDrawnZoneGeometry] = useState<ZoneGeometry | null>(null);
const [zoneKeyboardDraft, setZoneKeyboardDraft] = useState<{
shape: "polygon" | "circle";
cursor: Pt;
points: Pt[];
center?: Pt;
} | null>(null);
const mapFrameRef = useRef<HTMLDivElement | null>(null);
const [zoneMove, setZoneMove] = useState<ZoneMove | null>(null);
const [zoneVertex, setZoneVertex] = useState<ZoneVertexDrag | null>(null);
const [zoneGeometryDraft, setZoneGeometryDraft] = useState<{ id: string; geometry: ZoneGeometry } | null>(null);
const [zoneBusy, setZoneBusy] = useState(false);
const [zoneErr, setZoneErr] = useState<string | null>(null);
const zoneRequestRef = useRef<{ generation: number; controller: AbortController | null }>({
generation: 0,
controller: null,
});
const routeRequestRef = useRef<{ generation: number; controller: AbortController | null }>({
generation: 0,
controller: null,
});
const deliveryRecipientRequestRef = useRef<{ generation: number; controller: AbortController | null }>({
generation: 0,
controller: null,
});
const normalizedCustomerZones = usesNormalizedCustomerZones(tableKey);
const mapNavigator = mapNavigatorMode(routePanelOpen, zoneNavigatorOpen);
const activeNamedRoute = useMemo(
() => activeRouteId ? namedRoutes.find((route) => route.id === activeRouteId) || null : null,
[activeRouteId, namedRoutes]
);
useEffect(() => {
const routeId = pendingInboxRoute.current;
if (!routeId || !namedRoutes.some((route) => route.id === routeId)) return;
pendingInboxRoute.current = null;
setActiveRouteId(routeId);
}, [namedRoutes]);
useEffect(() => {
setRoutePinPrompt(null);
setRoutePinNotice(null);
}, [activeRouteId]);
useEffect(() => {
if (activeRouteId && !activeNamedRoute) setActiveRouteId(null);
}, [activeNamedRoute, activeRouteId]);
useEffect(() => {
if (routePanelOpen) {
return;
}
setZoneNavigatorOpen(false);
setZoneEditorOpen(false);
setActiveRouteId(null);
setRoutePinPrompt(null);
setRoutePinNotice(null);
setRoutePinBusy(false);
}, [routePanelOpen]);
/* ══════════ R10 — THE RESTORE HALF, AND IT SITS *AFTER* THE CLOSE EFFECT ON PURPOSE ══════════
Both react to `routePanelOpen`, and the effect above clears the Route detail and the Zone
navigator whenever the panel is shut. Declared before it, these two would restore into a state
the close effect then wiped in the same commit. Declared after, and gated on the panel being
OPEN, they can only ever run when the close effect has taken its early return.
⚠ `routePanelOpen` is the effective presentation answer: the host's ordinary toggle OR the
Routing Application's local first-paint seed. Both therefore reach these same restore effects;
the Application path does not bypass them or write the saved View configuration. */
const navigatorRestored = useRef(false);
useEffect(() => {
if (navigatorRestored.current || !routePanelOpen) return;
navigatorRestored.current = true;
if (restoredMap?.navigator === "zones") setZoneNavigatorOpen(true);
}, [restoredMap, routePanelOpen]);
/* ⛔ ONE SHOT, AND BOUNDED. The named-Route read answers asynchronously, so this has to wait for
`namedRoutes` — but it must NOT stay armed after that, or a later refresh of the list would
re-open a route the reader had since closed. The flag is set as soon as the list has answered,
whether or not the remembered route survived in it. */
const routeRestored = useRef(false);
useEffect(() => {
if (routeRestored.current || !routePanelOpen) return;
const routeId = restoredMap?.routeId;
if (!routeId) {
routeRestored.current = true;
return;
}
if (namedRoutes.length === 0) return;
routeRestored.current = true;
if (namedRoutes.some((route) => route.id === routeId)) setActiveRouteId(routeId);
}, [namedRoutes, restoredMap, routePanelOpen]);
/**
* W37-T36 — the ROAD answer, which is the half arithmetic cannot produce.
*
* ⛔ FETCHED ONLY WHEN ASKED (R3), and "asked" means a click, never a render and never a
* selection change. When the stops or their order move underneath a fetched route, the geometry
* is marked STALE and stays on screen greyed rather than being silently refetched or silently
* left looking current. A route that quietly describes a different set of stops than the one on
* screen is the failure mode worth spending a state field to prevent.
*/
const [road, setRoad] = useState<
{
km: number;
minutes: number;
line: number[][];
key: string;
attribution: string;
/** WHICH mode produced these numbers, so the label can never outrun the answer. */
mode: TravelMode;
} | null
>(null);
const [roadBusy, setRoadBusy] = useState(false);
const [roadErr, setRoadErr] = useState<string | null>(null);
/** The legacy on-map planner still chunks a preview at ten stops. Scheduled normalized Routes
* own their independently editable 2-10 choice inside RouteNav. */
const mapsPerLink = 10;
const [routeCopyMsg, setRouteCopyMsg] = useState<string | null>(null);
const [routeDeliveries, setRouteDeliveries] = useState<RouteDeliveryDto[] | null>(null);
/** Which saved column a save writes to. `""` = a new field, named in the prompt below. */
const [saveTarget, setSaveTarget] = useState("");
/**
* ⭐⭐ OWNER, 2026-08-23 — WHICH SAVED ROUTE IS BEING **SHOWN**, which is not the same
* question as which column a save WRITES TO.
*
* Owner: *"when I click the Route navigation button. I should be able to choose any Route
* field I want to see the Routes."* Before this the only route control was `saveTarget`: it
* appeared behind `plan &&` (so you could not reach it until you had already solved something
* else), it listed `mine` columns only, and picking one changed nothing on the map because it
* named a WRITE destination. Reading a colleague's plan was not expressible at all.
*
* ⛔ TWO STATES BECAUSE THEY ARE TWO PERMISSIONS. Anyone the column was shared with may OPEN
* it; only its planner or an admin may re-solve it (`route_order_write`'s creator-or-admin
* wall, reported as `mine`). Collapsing them into one control would either offer a Save that
* earns a 403 or hide a route the person is allowed to read.
*/
const [, setOpenedRoute] = useState("");
const [openErr, setOpenErr] = useState<string | null>(null);
/**
* ⭐⭐ OWNER ITEM 5 (2026-08-23) — THE NAME IS ASKED FOR, AND ITS DEFAULT COMES FROM THE SERVER.
*
* Owner: *"When we click the newly renamed 'Save route' it should prompt the user to Name the
* route, with the default as Route 1, or Route 2, etc."*
*
* ⛔ THE SERVER-SIDE ALLOCATOR IS GONE. `nextLabel` used to come from
* `GET /customers/route-order`, which counted the whole shared stratum of legacy route COLUMNS
* so a user with no grant on `route_route_1` was never pre-filled a name they would then be
* refused. That door and that stratum are deleted, and no client reads this value: W47-T09 / R9
* had already retired the naming panel, which is why the constant below is parked in the
* `void [...]` list rather than rendered.
*
* ⚠ WHOEVER PUTS THE NAMING PANEL BACK: derive the pre-fill from the normalized Routes the
* panel already holds, NOT from a column listing -- there are no columns to count any more, and
* the refusal the old allocator existed to prevent (`field_key_taken` on a name this panel put
* in the box) cannot arise on a Route record, whose name is not a store key.
*/
const nextLabel = "";
const [naming, setNaming] = useState(false);
const [nameDraft, setNameDraft] = useState("");
const [saveBusy, setSaveBusy] = useState(false);
const [saveMsg, setSaveMsg] = useState<string | null>(null);
const [saveErr, setSaveErr] = useState<string | null>(null);
/**
* W37-T37 — the address lookup's own progress, and it exists so the WAIT IS VISIBLE.
*
* ⛔ R3/R14: a lookup runs only when a person asks, for the records that person chose, and at
* roughly one address per second. That last part means a real run TAKES MINUTES, so hiding it
* behind a spinner would be the difference between a wait and a hang. `done` of `total` is on
* screen the whole time, and it counts records rather than requests because that is the unit the
* person selected.
*/
const [geo, setGeo] = useState<{
busy: boolean; done: number; total: number; found: number; error: string | null;
}>({ busy: false, done: 0, total: 0, found: 0, error: null });
const [sessionCoordinates, setSessionCoordinates] = useState<
ReadonlyMap<number, { lat: number; lon: number }>
>(() => new Map());
const [view, setView] = useState<View | null>(() => restoredMap?.view ?? null);
/**
* The selection gesture in flight. Two shapes, never a mode for SELECTING
* itself: shift-drag always selects, and `lassoTool` only changes what it
* draws. That distinction is why the "no mode toggle" note over `onPointerDown`
* still holds — the thing people would never find behind a mode is selection,
* and it is still on the bare gesture.
*/
const [drag, setDrag] = useState<
| { kind: "rect"; x0: number; y0: number; x1: number; y1: number }
| { kind: "lasso"; pts: Pt[] }
| null
>(null);
const [lassoTool, setLassoTool] = useState(false);
/**
* ⚠ The svg element lives in STATE, not in a ref, and that is load-bearing.
*
* `view` starts null, so the FIRST render returns the empty state and there is
* no <svg> in the tree at all. A `useRef` would still be null when the wheel
* effect below first ran, and by the time the svg actually mounted the
* effect's deps (`localPoint`, `kMin`, `kMax`) were all unchanged — so React
* would never re-run it and the wheel listener would never be attached. Wheel
* zoom would be silently dead on the ordinary path.
*
* Holding the element in state makes attachment a consequence of MOUNTING
* rather than of a dependency happening to change, so the hazard cannot come
* back. No unit test can see this: the gate is pure TS under node, and a
* screenshot of a static page has no React in it.
*/
const [svgEl, setSvgEl] = useState<SVGSVGElement | null>(null);
/**
* W37-T35 — the tile provider, and whether tiles are working.
*
* ⚠ `tiles` starts at the OFFLINE DEFAULT rather than at null, so the basemap paints on the
* first frame instead of flashing the vector map and then replacing it. The fetch below only
* ever REPLACES a working default with a configured one.
*/
const [tiles, setTiles] = useState<TileProvider>(TILES_DEFAULT);
/** W37-T37 — the lookup's batch size and its MEASURED seconds-per-address, both served by the
* same provider door as the tiles. Defaults match `routes_geo.py`'s own, so the control works
* before the config call lands and keeps working if it never does. */
const [geoBatch, setGeoBatch] = useState(25);
const [geoSeconds, setGeoSeconds] = useState(3.3);
const [tileFails, setTileFails] = useState(0);
const tilesOk = tileFails < TILE_FAIL_LIMIT;
useEffect(() => {
let live = true;
// ⛔ A FAILURE HERE IS SILENT ON PURPOSE, and it is the one place in this file where that is
// right: the answer is a STYLE CHOICE, the default is already correct and already painting,
// and a person cannot act on "the provider config endpoint is unreachable". The failures that
// must be loud are the ones that change what the data SAYS, and this changes none.
fetch("/api/v1/geo/providers", { credentials: "same-origin" })
.then((r) => (r.ok ? r.json() : null))
.then((j) => {
const t = j && j.tiles;
if (!live || !t || typeof t.url !== "string" || !t.url) return;
setTiles({
url: t.url,
attribution: String(t.attribution || TILES_DEFAULT.attribution),
attributionUrl: String(t.attributionUrl || TILES_DEFAULT.attributionUrl),
maxZoom: Number(t.maxZoom) > 0 ? Number(t.maxZoom) : TILES_DEFAULT.maxZoom,
});
const gc = j.geocode;
if (gc) {
if (Number(gc.maxBatch) > 0) setGeoBatch(Number(gc.maxBatch));
if (Number(gc.secondsPerAddress) > 0) setGeoSeconds(Number(gc.secondsPerAddress));
}
// ⭐ ITEM 7 — which travel modes this deployment can actually answer. Unlike the tiles
// above, a wrong answer here is not a style choice, so the offer is taken from the server
// and the defaults are only the pre-arrival stand-in.
const offered = Array.isArray(j.route?.modes) ? j.route.modes : null;
if (offered) {
const clean = offered
.filter((m: { key?: unknown }) => m && (m.key === "driving" || m.key === "walking"))
.map((m: { key: TravelMode; label?: unknown; available?: unknown }) => ({
key: m.key,
label: String(m.label || (m.key === "walking" ? "Walking" : "Driving")),
available: m.available !== false,
}));
if (clean.length) setTravelModes(clean);
}
})
.catch(() => {});
return () => {
live = false;
};
}, []);
const panRef = useRef<{ x: number; y: number; tx: number; ty: number } | null>(null);
/** A finished drag must not also read as a click on the pin underneath — the
* kanban card's lesson (viewModes.tsx), same fix. */
const movedRef = useRef(false);
/** Where a gesture began, in CLIENT pixels, so `onPointerMove` can take the pointer capture
* only once it has become a drag. See the block in `onPointerDown` (W38-T09). */
const downRef = useRef<{ id: number; cx: number; cy: number } | null>(null);
/** Once the user has zoomed or panned, a data change must NOT yank the view
* back. Before that, refitting on new data is the helpful behaviour.
* R10 — A RESTORED VIEWPORT COUNTS AS TOUCHED, so the auto-fit leaves it alone. `Fit` still
* clears this and re-frames the data, which is the way back from any remembered camera. */
const touchedRef = useRef(Boolean(restoredMap?.view));
/* ═════════ R10 — THE WRITE HALF. `localStorage` ONLY: this touches no saved view ═════════ */
const mapStateKey = useMemo(() => mapMemoryKey(tableKey, activeView?.id, applicationId), [tableKey, activeView?.id, applicationId]);
const mapState = useMemo<MapMemory>(() => ({
view: view ? { k: view.k, tx: view.tx, ty: view.ty, rot: view.rot } : undefined,
routeId: activeRouteId,
navigator: mapNavigator,
}), [activeRouteId, mapNavigator, view]);
/**
* ⛔ THE UNMOUNT WRITE READS A REF, NEVER THE CLOSURE. A `useEffect(() => () => write(mapState),
* [])` captures the FIRST render's values, so leaving the Map view would store the camera the map
* OPENED with rather than the one the person left it at — a persistence bug that looks exactly
* like no persistence at all, because the stored value is always the fitted default.
*/
const mapStateLatest = useRef<{ key: string | null; state: MapMemory }>({ key: mapStateKey, state: mapState });
useEffect(() => {
mapStateLatest.current = { key: mapStateKey, state: mapState };
});
useEffect(() => {
if (!mapStateKey) return;
const timer = window.setTimeout(() => writeMapMemory(mapStateKey, mapState), MAP_MEMORY_DEBOUNCE_MS);
return () => window.clearTimeout(timer);
}, [mapState, mapStateKey]);
useEffect(() => () => {
const latest = mapStateLatest.current;
writeMapMemory(latest.key, latest.state);
}, []);
/** The view's rows PLUS the ones the user reached past the filter for (owner item 9). */
const mapRows = useMemo(() => {
if (routeApplication) {
const have = new Set(rows.map((row) => row.pid));
return [...rows, ...(allRows ?? []).filter((row) => selectedPids.has(row.pid) && !have.has(row.pid))];
}
if (addedPids.size === 0 || !allRows || allRows.length === 0) return rows;
const have = new Set(rows.map((r) => r.pid));
const extra = allRows.filter((r) => addedPids.has(r.pid) && !have.has(r.pid));
return extra.length ? [...rows, ...extra] : rows;
}, [rows, allRows, addedPids, routeApplication, selectedPids]);
const points = useMemo(() => {
const out: MapPoint[] = [];
for (const r of mapRows) {
const at = rowCoordinates(r, coordinateFields, coordField, sessionCoordinates);
if (!at) continue;
const { lat, lon } = at;
out.push({
pid: r.pid,
title: String(r[field.key] ?? ""),
p: project(lon, lat),
lat,
lon,
colorKey: colorField ? String(r[colorField.key] ?? "").trim() : null,
size: sizeField ? numOrNull(r[sizeField.key]) : null,
colorVal: colorField ? r[colorField.key] : null,
sizeVal: sizeField ? r[sizeField.key] : null,
});
}
return out;
}, [mapRows, field.key, coordinateFields, coordField, sessionCoordinates, colorField, sizeField]);
/**
* W46-T26 — WHAT EACH STOP IS CALLED. The Route panel used to print a bare ordinal, so the
* list said nothing about who the driver is visiting. The name lives on the row, not on the
* route DTO (`visibleStopIds` is a bare `number[]`), so it is carried down from here.
*
* ⛔ BUILT FROM THE ROW BOOK, NOT FROM `points`. `points` holds only rows that survived
* coordinate validation, so a customer who has never been geocoded is ABSENT from it — and
* that is precisely the stop the address fallback exists to name. `allRows` leads for the same
* reason the saved-route row resolution takes it: a saved stop may sit outside the current
* View's filter and must still read as itself rather than as a placeholder.
*
* Name and address stay SEPARATE fields rather than one pre-picked string, because the printed
* route sheet needs both on the same line.
*/
const routeStopLabels = useMemo(() => {
const addrKey = coordField?.geocode?.addressField;
const out: Record<number, { name: string; address: string }> = {};
const book = allRows && allRows.length ? [...allRows, ...mapRows] : mapRows;
for (const r of book) {
if (out[r.pid]) continue;
out[r.pid] = {
name: String(r[field.key] ?? "").trim(),
address: addrKey ? String(r[addrKey] ?? "").trim() : "",
};
}
return out;
}, [allRows, mapRows, field.key, coordField]);
/**
* W46-T19 / CONTRACT C2 — the coordinates the Route timer measures from.
*
* ⛔ ROUTENAV CANNOT REACH THESE ON ITS OWN. `stopLabels` carries name and address only, and
* `NormalizedRouteMapLink` carries `{url,index,start,end,stopIds}` with no lat/lon, so without
* this prop the timer renders "No drive time yet" forever and C2's whole client half is dead.
*
* ⚠ THE SAME DERIVATION AS `activeRouteMaps` (below), deliberately: one rule for what counts as
* a located stop, so the Maps hand-off and the drive time can never disagree about which stops
* have a position. Built over the ROW BOOK rather than `points`, because `points` drops every
* row that failed coordinate validation and a saved stop can sit outside the current filter.
*/
const routeStopCoords = useMemo(() => {
const out: Record<number, { lat: number; lon: number }> = {};
for (const row of (allRows?.length ? allRows : mapRows)) {
if (out[row.pid]) continue;
const at = rowCoordinates(row, coordinateFields, coordField, sessionCoordinates);
if (at) out[row.pid] = { lat: at.lat, lon: at.lon };
}
return out;
}, [allRows, mapRows, coordinateFields, coordField, sessionCoordinates]);
const loadZones = useCallback(async () => {
zoneRequestRef.current.controller?.abort();
const controller = new AbortController();
const generation = zoneRequestRef.current.generation + 1;
zoneRequestRef.current = { generation, controller };
try {
const res = await routingFetch(zoneCollectionPath(tableKey), {
credentials: "same-origin",
signal: controller.signal,
});
const body = res.ok ? await res.json().catch(() => null) : null;
if (!routingAlive.current) return;
if (zoneRequestRef.current.generation !== generation) return;
const loadedZones: MapZone[] = Array.isArray(body?.zones) ? body.zones : [];
setZones(loadedZones);
setActiveZoneIds(new Set(
loadedZones.filter((zone) => zone.visible).map((zone) => zone.id)
));
} catch {
if (controller.signal.aborted) return;
if (zoneRequestRef.current.generation !== generation) return;
setZones([]);
setActiveZoneIds(new Set());
}
}, [tableKey, routingFetch]);
useEffect(() => { void loadZones(); }, [loadZones]);
const loadNamedRoutes = useCallback(async () => {
routeRequestRef.current.controller?.abort();
const controller = new AbortController();
const generation = routeRequestRef.current.generation + 1;
routeRequestRef.current = { generation, controller };
try {
const res = await routingFetch(routeInventoryPath(), {
credentials: "same-origin",
signal: controller.signal,
});
const body = res.ok ? await res.json().catch(() => null) : null;
if (!routingAlive.current) return;
if (routeRequestRef.current.generation !== generation) return;
setRoutesLoaded(true);
if (!res.ok || !Array.isArray(body?.routes)) {
setRoutesLoadError(true);
return;
}
setRoutesLoadError(false);
setNamedRoutes(body.routes);
if (Array.isArray(body?.folders)) setRouteFolders(body.folders);
} catch {
if (controller.signal.aborted) return;
setRoutesLoaded(true);
setRoutesLoadError(true);
/* Keep the last honest Route navigation when a refresh is temporarily unavailable. */
}
}, [routingFetch]);
const loadRouteDeliveryRecipients = useCallback(async () => {
deliveryRecipientRequestRef.current.controller?.abort();
const controller = new AbortController();
setRouteDeliveryRecipients(null);
setDeliveryRecipientError(null);
const generation = deliveryRecipientRequestRef.current.generation + 1;
deliveryRecipientRequestRef.current = { generation, controller };
const result = await fetchRouteDeliveryRecipients(controller.signal, undefined, applicationId);
if (!routingAlive.current || controller.signal.aborted || deliveryRecipientRequestRef.current.generation !== generation) return;
if (result.directory) {
setRouteDeliveryRecipients(result.directory);
setDeliveryRecipientError(null);
} else {
setDeliveryRecipientError(result.error || "Delivery recipients are unavailable.");
}
}, [applicationId]);
useEffect(() => () => {
zoneRequestRef.current.controller?.abort();
routeRequestRef.current.controller?.abort();
deliveryRecipientRequestRef.current.controller?.abort();
}, []);
useEffect(() => { void loadNamedRoutes(); }, [loadNamedRoutes]);
useEffect(() => {
if (applicationId) onManagedRouteViewState?.({}, applicationId);
}, [applicationId, onManagedRouteViewState]);
useEffect(() => {
if (routePanelOpen) void loadRouteDeliveryRecipients();
}, [loadRouteDeliveryRecipients, routePanelOpen]);
useEffect(() => {
// A managed clause belongs to one saved View. Never carry it into another View's authored state.
setManagedRouteViewState(null);
setSelectedRouteIds(new Set());
setRouteSelectionWarning(null);
}, [activeView?.id]);
const routeFilterSignature = useMemo(
() => routeFilterSignatureOf(activeView?.config?.filters, activeView?.config?.filterConj),
[activeView?.config?.filterConj, activeView?.config?.filters]
);
const routeFilterSignatureRef = useRef({ viewId: activeView?.id || "", signature: routeFilterSignature });
const filterRestoreSeenRef = useRef(0);
useEffect(() => {
const prior = routeFilterSignatureRef.current;
const viewId = activeView?.id || "";
// S72-T60: a host restore seeds the ref with its own signature, so it never clears the selection.
const restored = !!filterRestore && filterRestore.seq !== filterRestoreSeenRef.current &&
filterRestore.signature === routeFilterSignature;
if (filterRestore) filterRestoreSeenRef.current = filterRestore.seq;
const changed = !restored && prior.viewId === viewId && prior.signature !== routeFilterSignature;
routeFilterSignatureRef.current = { viewId, signature: routeFilterSignature };
if (!changed || !activeView || selectedRouteIds.size === 0) return;
void (async () => {
try {
const res = await routingFetch("/api/v1/customers/routes/selection", {
method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ routeIds: [], viewState: activeView.config as unknown as Record<string, unknown> } satisfies RouteSelectionRequest),
});
const body = await res.json().catch(() => null) as RouteSelectionResponse | null;
if (!routingAlive.current) return;
if (!res.ok || body?.managedBy !== "loopable" || !body.viewState) throw new Error("managed selection refusal");
setSelectedRouteIds(new Set());
setManagedRouteViewState(body.viewState);
onManagedRouteViewState?.(body.viewState, applicationId);
setRouteSelectionWarning("Route selection cleared because the View filter changed.");
} catch {
setRouteSelectionWarning("Route selection could not be cleared after the View filter changed.");
}
})();
}, [activeView, filterRestore, onManagedRouteViewState, routeFilterSignature, selectedRouteIds, routingFetch, applicationId]);
/**
* ⭐⭐ W51-T28 / R6 — THE WRITE HALF, SPLIT OUT SO THE CONFIRM CAN BE A DIALOG.
*
* This body was reached past a `window.confirm` sitting at the top of one async function, and
* that arrangement cannot survive the change: `window.confirm` blocks the thread and hands back
* a boolean, while a dialog is a render. There is no way to `await` the dialog without inventing
* a promise bridge across React state, so the function is CUT INSTEAD OF WRAPPED.
*
* ⛔⛔ THE NAME IS LOAD-BEARING, AND NOT FOR READABILITY. `verify_w44_map_routes.py`'s
* `managed-route-callback` leg slices this file between the `toggleNamedRoute` declaration and
* the `moveNamedRouteStop` one, then asserts that `onManagedRouteViewState?.(...)` fires AFTER
* the `body?.managedBy !== "loopable"` refusal. Splitting the function moved that whole sequence
* out of the slice, and the leg went red on code whose logic had not changed a line. The
* extracted half therefore keeps the `toggleNamedRoute` PREFIX, so the slice opens on this
* function rather than on the entry below it and still contains the whole toggle path. Rename
* this and that gate, which this ticket does not own, goes red again for the same non-reason.
*
* ⛔⛔ AND THE PROSE HERE MUST NOT SPELL THE ANCHORS THE WAY THE GATE SPELLS THEM. That leg
* slices with a plain `str.find` over the RAW file and strips no comments, so a note quoting its
* two anchor strings verbatim, `const` keyword and all, is found BEFORE the real declarations
* and yields a 33-character slice. That is exactly how this comment reddened the gate it was
* written to explain, which is why the two names above appear WITHOUT the keyword in front.
*
* ⛔ `isAdding` AND `next` ARE RECOMPUTED HERE, NOT PASSED IN, and that is the trap this note
* exists for. The pending route waits in state across at least one render; a decision captured
* at the moment the dialog opened could describe a selection that has since changed underneath
* it. Recomputing from the live `selectedRouteIds` makes the confirmed act the act the user is
* looking at. There is exactly ONE copy of this body: the ordinary path calls it directly.
*/
const toggleNamedRouteSelection = useCallback(async (route: MapRouteDto) => {
const isAdding = !selectedRouteIds.has(route.id);
const next = toggleRouteSelection(selectedRouteIds, route.id);
if (!activeView) {
setRouteSelectionWarning("Select a saved View before adding a route inclusion.");
return;
}
const routeIds = [...next];
try {
const request: RouteSelectionRequest = {
routeIds,
viewState: managedRouteViewState || (activeView.config as unknown as Record<string, unknown>),
};
const res = await routingFetch("/api/v1/customers/routes/selection", {
method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
});
const body = await res.json().catch(() => null) as RouteSelectionResponse | null;
if (!routingAlive.current) return;
if (!res.ok || body?.managedBy !== "loopable" || !body.viewState) {
setRouteSelectionWarning(body && "error" in body ? String((body as { error?: { message?: string } }).error?.message || "Route inclusion could not be changed.") : "Route inclusion could not be changed.");
return;
}
setSelectedRouteIds(next);
setManagedRouteViewState(body.viewState);
onManagedRouteViewState?.(body.viewState, applicationId);
setRouteSelectionWarning(route.outsideFilter && next.has(route.id) ? `${route.name} is included through its managed route group.` : null);
const pids = namedRoutes.filter((item) => next.has(item.id)).flatMap((item) => item.visibleStopIds);
/**
* ⭐⭐ OWNER 2026-08-31 item 1 - UNTICKING A ROUTE UNDOES EVERYTHING TICKING IT DID.
*
* Owner: *"When I press clear after I selected the Route that has records not actually a
* part of the filter. The record stays, only when I change the filter it actually move
* back."* Confirmed with them: the control is the route's own checkbox, and the records
* stay in the grid AND on the map.
*
* ⛔ THE ADD PATH WROTE THREE STORES AND THE REMOVE PATH CLEARED ONE. Ticking a Route
* writes (a) the server's managed OR clause, (b) the host row selection, and (c) - once
* the Route has also been opened - `addedPids`, which is what earns an out-of-filter stop
* a pin through `mapRows`. Unticking sent `"add"` with the REMAINING routes' pids, and
* `"add"` is monotone: it can never take a pid back out. So (b) and (c) survived, the
* record kept its row and its pin, and the next filter edit rebuilt the pipeline from
* scratch - which is exactly the "only when I change the filter" the owner described.
*
* ⚠ ONLY THE PIDS NO SURVIVING ROUTE STILL CLAIMS ARE DROPPED. Two ticked routes sharing
* a stop must not lose it when one of them is unticked, and a record the person picked by
* hand is not this callback's to remove either - hence the subtraction is computed
* against `keep`, and the host selection is rebuilt from what it currently holds rather
* than replaced by the route union.
*/
if (isAdding) {
onSelectPids([...new Set(pids)], "add");
} else {
const keep = new Set(pids);
const dropped = (route.visibleStopIds || []).filter((pid) => !keep.has(pid));
if (dropped.length) {
const gone = new Set(dropped);
onSelectPids([...selectedPids].filter((pid) => !gone.has(pid)), "replace");
setAddedPids((prev) => {
if (![...gone].some((pid) => prev.has(pid))) return prev;
const remaining = new Set(prev);
for (const pid of gone) remaining.delete(pid);
return remaining;
});
for (const pid of gone) routeAddedRef.current.delete(pid);
}
// The opened Route detail is armed from `activeNamedRoute`; leaving the arming key set
// would refuse to re-arm this Route on a later tick, because the signature would match.
if (armedRouteRef.current.startsWith(`${route.id}:`)) armedRouteRef.current = "";
}
} catch { setRouteSelectionWarning("Route inclusion could not be changed."); }
}, [activeView, managedRouteViewState, namedRoutes, onManagedRouteViewState, onSelectPids, selectedPids, selectedRouteIds, routingFetch, applicationId]);
/**
* The ENTRY point. Ticking a route that the View's own filter excludes is the one branch that
* asks first: the inclusion widens what the grid shows, so the person is told before it happens.
* Everything else goes straight through to the write above.
*/
const toggleNamedRoute = useCallback(async (route: MapRouteDto) => {
const isAdding = !selectedRouteIds.has(route.id);
if (isAdding && route.outsideFilter) {
setPendingRouteInclude(route);
return;
}
await toggleNamedRouteSelection(route);
}, [toggleNamedRouteSelection, selectedRouteIds]);
const confirmPendingRouteInclude = useCallback(() => {
const route = pendingRouteInclude;
if (!route) return;
// Cleared BEFORE the dispatch, so a second Enter on a dialog that has not yet unmounted
// cannot post the same inclusion twice.
setPendingRouteInclude(null);
void toggleNamedRouteSelection(route);
}, [toggleNamedRouteSelection, pendingRouteInclude]);
const moveNamedRouteStop = useCallback(async (route: MapRouteDto, customerPid: number, order: number): Promise<string | null> => {
try {
const res = await routingFetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/stops/move`, {
method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ customerPid, order }),
});
const body = await res.json().catch(() => null);
if (!routingAlive.current) return "This Routing App is no longer open.";
if (res.status === 409 && body?.error?.code === "no_route_stop") return "This route has no matching stop to move.";
if (!res.ok) return body?.error?.message || "The stop order could not be changed.";
const routeUpdate = body?.route as MapRouteDto | undefined;
if (routeUpdate) setNamedRoutes((current) => current.map((item) => item.id === routeUpdate.id
? { ...item, ...routeUpdate, folderId: item.folderId, navOrder: item.navOrder }
: item));
return null;
} catch { return "The stop order could not be changed."; }
}, [routingFetch]);
const updateNamedRoute = useCallback(async (
route: MapRouteDto, patch: MapRouteUpdate
): Promise<string | null> => {
const actionAllowed = "starred" in patch
? route.capabilities?.star === true
: route.capabilities?.rename === true;
if (!actionAllowed)
return "This Route is read-only.";
try {
const res = await routingFetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}`, {
method: "PATCH", credentials: "same-origin", headers: { "Content-Type": "application/json" },
body: JSON.stringify(patch),
});
const body = await res.json().catch(() => null);
if (!routingAlive.current) return "This Routing App is no longer open.";
if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route could not be updated.";
const routeUpdate = body?.route as MapRouteDto | undefined;
if (!routeUpdate) return "The Route update returned no Route.";
setNamedRoutes((current) => current.map((item) => item.id === routeUpdate.id
? { ...item, ...routeUpdate, folderId: item.folderId, navOrder: item.navOrder }
: item));
return null;
} catch { return "The Route could not be updated."; }
}, [routingFetch]);
const deleteNamedRoute = useCallback(async (route: MapRouteDto): Promise<string | null> => {
if (route.capabilities?.delete !== true)
return "This Route is read-only.";
try {
const res = await routingFetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}`, {
method: "DELETE", credentials: "same-origin",
});
const body = await res.json().catch(() => null);
if (!routingAlive.current) return "This Routing App is no longer open.";
if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route could not be deleted.";
const nextSelected = new Set(selectedRouteIds);
const removedSelection = nextSelected.delete(route.id);
setNamedRoutes((current) => current.filter((item) => item.id !== route.id));
setCreatedRoute((current) => current?.id === route.id ? null : current);
setSelectedRouteIds(nextSelected);
if (activeRouteId === route.id) setActiveRouteId(null);
setRoutePinPrompt(null);
setRoutePinNotice(null);
if (removedSelection && activeView) {
try {
const selectionRes = await routingFetch("/api/v1/customers/routes/selection", {
method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
body: JSON.stringify({
routeIds: [...nextSelected],
viewState: managedRouteViewState || (activeView.config as unknown as Record<string, unknown>),
} satisfies RouteSelectionRequest),
});
const selectionBody = await selectionRes.json().catch(() => null) as RouteSelectionResponse | null;
if (!routingAlive.current) return "This Routing App is no longer open.";
if (!selectionRes.ok || selectionBody?.managedBy !== "loopable" || !selectionBody.viewState)
throw new Error("managed selection refusal");
setManagedRouteViewState(selectionBody.viewState);
onManagedRouteViewState?.(selectionBody.viewState, applicationId);
setRouteSelectionWarning(null);
} catch {
setRouteSelectionWarning("The Route was deleted, but its View inclusion could not be cleared.");
}
}
return null;
} catch { return "The Route could not be deleted."; }
}, [activeRouteId, activeView, managedRouteViewState, onManagedRouteViewState, selectedRouteIds, routingFetch, applicationId]);
const requestRoutePinMembership = useCallback((customerPid: number, title: string) => {
setRoutePinNotice(null);
if (!activeNamedRoute) {
setRoutePinPrompt(null);
setRoutePinNotice("Open a route first.");
return;
}
if (!activeNamedRoute.permission.canEdit) {
setRoutePinPrompt(null);
setRoutePinNotice("This Route is read-only.");
return;
}
const isMember = activeNamedRoute.visibleStopIds.includes(customerPid);
setRoutePinPrompt({
routeId: activeNamedRoute.id,
customerPid,
title: title || `Record ${customerPid}`,
present: !isMember,
});
}, [activeNamedRoute]);
const confirmRoutePinMembership = useCallback(async () => {
const prompt = routePinPrompt;
if (!prompt || routePinBusy) return;
setRoutePinBusy(true);
setRoutePinNotice(null);
try {
const res = await routingFetch(
`/api/v1/customers/routes/${encodeURIComponent(prompt.routeId)}/stops/membership`,
{
method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ customerPid: prompt.customerPid, present: prompt.present }),
}
);
const body = await res.json().catch(() => null);
if (!routingAlive.current) return;
if (!res.ok) {
setRoutePinNotice(body?.error?.message || body?.detail?.message || "The Route stop could not be changed.");
return;
}
const routeUpdate = body?.route as MapRouteDto | undefined;
if (!routeUpdate) {
setRoutePinNotice("The Route stop update returned no Route.");
return;
}
setNamedRoutes((current) => current.map((item) => item.id === routeUpdate.id
? { ...item, ...routeUpdate, folderId: item.folderId, navOrder: item.navOrder }
: item));
setRoutePinPrompt(null);
setRoutePinNotice(`${prompt.title} was ${prompt.present ? "added to" : "removed from"} ${routeUpdate.name}.`);
} catch {
setRoutePinNotice("The Route stop could not be changed.");
} finally {
setRoutePinBusy(false);
}
}, [routePinBusy, routePinPrompt, routingFetch]);
const activeZones = useMemo(
() => (zones || []).filter((zone) => zone.visible && activeZoneIds.has(zone.id)),
[zones, activeZoneIds]
);
const activeZonePids = useMemo(() => {
const pids = new Set<number>();
for (const zone of activeZones) for (const pid of zone.memberships || []) pids.add(pid);
return pids;
}, [activeZones]);
const routeSources = useMemo<MapRouteSource[]>(() => [
{ id: "selection", label: "Current selection", pids: routeSourceStopIds(selectedPids) },
// ⛔ HOTFIX 2026-08-31, owner instruction: *"when I create a new route and I select
// 'Selected Zones' it still selects literally everything in the zone. it shouldn't, it should
// be scoped to the View's current Filter as well. So its always Filter and then what is in the
// zone."*
//
// A Zone's `memberships` is the WHOLE zone: it is computed server-side against the table
// (`route_system.zone_members` over the permission-scoped rows), never against the View the
// person is looking at. Offering that set raw meant every filter they had just set was
// discarded the moment they picked this source. The source is now FILTER ∩ ZONE, and it is
// walked in `rows` order rather than membership order so the stop order matches the grid
// exactly the way "Current filtered records" below already does.
{ id: "zones", label: "Selected Zones",
pids: routeSourceStopIds(rows.filter((row) => activeZonePids.has(row.pid)).map((row) => row.pid)) },
// ⭐ W47-T06 / instruction 7. THIS IS A MOVE, NOT A NEW QUERY. `rows` is exactly what the
// retired "Select all N filtered records" button read, so the picker now offers the same
// capability in the one place a person is already choosing what the Route is made of. The
// button and its handler were deleted together, so nothing dangles behind it.
{ id: "filtered", label: "Current filtered records",
pids: routeSourceStopIds(rows.map((row) => row.pid)) },
], [activeZonePids, selectedPids, rows]);
const createNamedRoute = useCallback(async (name: string, source: MapRouteSource): Promise<string | null> => {
if (!source.pids.length) return "Choose a Route source with at least one customer.";
try {
const res = await routingFetch("/api/v1/customers/routes", {
method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, stops: source.pids, ...(activeView ? { sourceViewId: activeView.id } : {}) }),
});
const body = await res.json().catch(() => null);
if (!routingAlive.current) return "This Routing App is no longer open.";
if (!res.ok) return body?.error?.message || "The Route could not be created.";
if (body?.route) {
setNamedRoutes((current) => [...current, body.route].sort((a, b) => a.navOrder - b.navOrder));
setCreatedRoute(body.route as MapRouteDto);
await loadNamedRoutes();
}
return null;
} catch { return "The Route could not be created."; }
}, [activeView, loadNamedRoutes, routingFetch]);
const duplicateNamedRoute = useCallback(async (route: MapRouteDto): Promise<string | null> => {
if (route.capabilities?.duplicate !== true)
return "This Route cannot be duplicated.";
try {
const res = await routingFetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/duplicate`, {
method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: `${route.name} copy` }),
});
const body = await res.json().catch(() => null);
if (!routingAlive.current) return "This Routing App is no longer open.";
if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route could not be duplicated.";
if (!body?.route) return "The duplicate returned no Route.";
setNamedRoutes((current) => [...current, body.route].sort((a, b) => a.navOrder - b.navOrder));
setCreatedRoute(body.route as MapRouteDto);
await loadNamedRoutes();
return null;
} catch { return "The Route could not be duplicated."; }
}, [loadNamedRoutes, routingFetch]);
const shareNamedRoute = useCallback(async (route: MapRouteDto): Promise<string | null> => {
if (route.capabilities?.share !== true)
return "Only the Route owner can share this Route.";
try {
const res = await routingFetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/share-ready`, {
method: "POST", credentials: "same-origin",
});
const body = await res.json().catch(() => null);
if (!routingAlive.current) return "This Routing App is no longer open.";
if (!res.ok) return body?.error?.message || body?.detail?.message || "Sharing could not be opened.";
window.dispatchEvent(new CustomEvent("aios:share-open", {
detail: { kind: body?.kind || "field", id: body?.id || route.shareId, label: body?.label || route.name },
}));
return null;
} catch { return "Sharing could not be opened."; }
}, [routingFetch]);
const moveNamedRoute = useCallback(async (route: MapRouteDto, folderId: string | null): Promise<string | null> => {
try {
const res = await routingFetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/folder`, {
method: "PATCH", credentials: "same-origin", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ folderId }),
});
const body = await res.json().catch(() => null);
if (!routingAlive.current) return "This Routing App is no longer open.";
if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route could not be moved.";
if (body?.route) setNamedRoutes((current) => current.map((item) => item.id === route.id ? body.route : item));
if (Array.isArray(body?.folders)) setRouteFolders(body.folders);
return null;
} catch { return "The Route could not be moved."; }
}, [routingFetch]);
const reorderNamedRoutes = useCallback(async (order: string[]): Promise<string | null> => {
try {
const res = await routingFetch("/api/v1/customers/routes/reorder", {
method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ order }),
});
const body = await res.json().catch(() => null);
if (!routingAlive.current) return "This Routing App is no longer open.";
if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route order could not be saved.";
await loadNamedRoutes();
return null;
} catch { return "The Route order could not be saved."; }
}, [loadNamedRoutes, routingFetch]);
const createNamedRouteFolder = useCallback(async (name: string, parent: string | null): Promise<string | null> => {
try {
const res = await routingFetch("/api/v1/customers/route-folders", {
method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, parent }),
});
const body = await res.json().catch(() => null);
if (!routingAlive.current) return "This Routing App is no longer open.";
if (!res.ok) return body?.error?.message || body?.detail?.message || "The folder could not be created.";
if (Array.isArray(body?.folders)) setRouteFolders(body.folders);
return null;
} catch { return "The folder could not be created."; }
}, [routingFetch]);
const updateNamedRouteFolder = useCallback(async (
folder: MapRouteFolderDto, patch: { name?: string; parent?: string | null }
): Promise<string | null> => {
try {
const res = await routingFetch(`/api/v1/customers/route-folders/${encodeURIComponent(folder.id)}`, {
method: "PATCH", credentials: "same-origin", headers: { "Content-Type": "application/json" },
body: JSON.stringify(patch),
});
const body = await res.json().catch(() => null);
if (!routingAlive.current) return "This Routing App is no longer open.";
if (!res.ok) return body?.error?.message || body?.detail?.message || "The folder could not be updated.";
if (Array.isArray(body?.folders)) setRouteFolders(body.folders);
return null;
} catch { return "The folder could not be updated."; }
}, [routingFetch]);
const deleteNamedRouteFolder = useCallback(async (folder: MapRouteFolderDto): Promise<string | null> => {
try {
const res = await routingFetch(`/api/v1/customers/route-folders/${encodeURIComponent(folder.id)}`, {
method: "DELETE", credentials: "same-origin",
});
const body = await res.json().catch(() => null);
if (!routingAlive.current) return "This Routing App is no longer open.";
if (!res.ok) return body?.error?.message || body?.detail?.message || "The folder could not be deleted.";
if (Array.isArray(body?.folders)) setRouteFolders(body.folders);
await loadNamedRoutes();
return null;
} catch { return "The folder could not be deleted."; }
}, [loadNamedRoutes, routingFetch]);
const reorderNamedRouteFolders = useCallback(async (order: string[]): Promise<string | null> => {
try {
const res = await routingFetch("/api/v1/customers/route-folders/reorder", {
method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ order }),
});
const body = await res.json().catch(() => null);
if (!routingAlive.current) return "This Routing App is no longer open.";
if (!res.ok) return body?.error?.message || body?.detail?.message || "The folder order could not be saved.";
await loadNamedRoutes();
return null;
} catch { return "The folder order could not be saved."; }
}, [loadNamedRoutes, routingFetch]);
const zoneEditor = useMemo(
() => (zones || []).find((zone) => zone.id === zoneEditorId) || null,
[zones, zoneEditorId]
);
const beginNewZone = useCallback(() => {
setZoneEditorId("");
setZoneName("");
setZoneColor(ZONE_COLOR_CHOICES[0].value);
setZoneDrawShape("polygon");
setDrawnZoneGeometry(null);
setZoneKeyboardDraft(null);
setZoneErr(null);
setZoneEditorOpen(true);
}, []);
const beginEditZone = useCallback((zone: MapZone) => {
setZoneEditorId(zone.id);
setZoneName(zone.name);
setZoneColor(zone.color);
setZoneDrawShape(zone.geometryGeoJson?.type === "Circle" ? "circle" : "polygon");
setDrawnZoneGeometry(null);
setZoneKeyboardDraft(null);
setZoneErr(null);
setZoneEditorOpen(true);
}, []);
/**
* Zone visibility is a checkbox chooser, not a ctrl-click native multi-select. A toggle also
* immediately projects the Zone's durable membership onto the grid selection; removing one
* Zone preserves records that are still held by another checked Zone.
*/
const toggleZone = useCallback((zone: MapZone, checked: boolean) => {
const next = new Set(activeZoneIds);
if (checked) next.add(zone.id);
else next.delete(zone.id);
const stillHeld = new Set<number>();
for (const item of zones || []) {
if (!next.has(item.id)) continue;
for (const pid of item.memberships || []) stillHeld.add(pid);
}
const selection = new Set(selectedPids);
if (checked) for (const pid of zone.memberships || []) selection.add(pid);
else for (const pid of zone.memberships || []) if (!stillHeld.has(pid)) selection.delete(pid);
onSelectPids([...selection], "replace");
setActiveZoneIds(next);
}, [activeZoneIds, zones, selectedPids, onSelectPids]);
const zonePolygons = useMemo(() => activeZones.flatMap((zone) => {
const geometry = zoneGeometryDraft?.id === zone.id
? zoneGeometryDraft.geometry
: zone.geometryGeoJson;
if (!geometry) return [];
const polygons = geometry.type === "Polygon"
? [geometry.coordinates as number[][][]]
: geometry.type === "MultiPolygon"
? geometry.coordinates as number[][][][]
: [];
return polygons.flatMap((polygon, polygonIndex) => polygon.map((ring, ringIndex) => {
// ⛔ W46-T28 — THE SOURCE INDEX TRAVELS WITH THE POINT. The filter below drops any pair
// that is not two finite numbers, so a rendered point's position in this array is NOT its
// position in the stored ring. A vertex drag writes back BY INDEX, and reading the screen
// index would silently move a different corner the moment one bad pair existed.
const points = ring
.map((pair, vertexIndex) => ({ pair, vertexIndex }))
.filter(({ pair }) => Array.isArray(pair) && Number.isFinite(pair[0]) && Number.isFinite(pair[1]))
.map(({ pair, vertexIndex }) => ({ ...project(pair[0], pair[1]), vertexIndex }));
const last = points.length - 1;
const closed = last > 0 && points[0].x === points[last].x && points[0].y === points[last].y;
return {
key: `${zone.id}:${polygonIndex}:${ringIndex}`,
zone,
geometry,
polygonIndex,
ringIndex,
points,
// One dot per CORNER. The closing coordinate is the opening one stored twice, so
// drawing it too would stack two handles on the same pixel and the top one would
// shadow the other's drag.
handles: closed ? points.slice(0, last) : points,
};
}).filter((ring) => ring.points.length >= 4));
}), [activeZones, zoneGeometryDraft]);
const zoneCircles = useMemo(() => activeZones.flatMap((zone) => {
const geometry = zoneGeometryDraft?.id === zone.id ? zoneGeometryDraft.geometry : zone.geometryGeoJson;
if (!geometry || geometry.type !== "Circle") return [];
const center = project(geometry.center[0], geometry.center[1]);
const latitudeRadians = geometry.center[1] * Math.PI / 180;
const lonDelta = geometry.radiusMeters / Math.max(1, 111_320 * Math.cos(latitudeRadians));
const edge = project(geometry.center[0] + lonDelta, geometry.center[1]);
return [{ zone, geometry, center, radius: Math.abs(edge.x - center.x) }];
}), [activeZones, zoneGeometryDraft]);
/**
* ⛔⛔ W47-T03 — THE FINISHED-BUT-UNSAVED BOUNDARY, PROJECTED SO IT CAN FINALLY BE PAINTED.
* Owner instruction 20: *"When I click 'Finish zone' under the Zone navigation, the zone just
* disappear. Only when I save the zone does it actually reappear. This is really bad UI, i was
* really confused whether I have made the zone or not."*
*
* THE CAUSE, EXACTLY. `finishZoneDraft` stores the boundary in `drawnZoneGeometry` and then
* clears `zoneKeyboardDraft` — and `zoneKeyboardDraft` was the ONLY state painting anything.
* `drawnZoneGeometry` was read by `saveZone` and by the Save button's `title` and by NO render
* path in this file, so the shape existed, was saveable, and was invisible. The owner was not
* confused by a subtle state: there was nothing on the screen to be in one.
*
* ⭐ IT COVERS THREE GESTURES, NOT THE ONE THE TICKET NAMES. `setDrawnZoneGeometry` also fires
* from `onPointerUp` when a drag-drawn marquee or lasso closes with the Zone editor open, and
* that outline was equally unpainted the moment the marquee cleared. One render site, all of
* them.
*
* ⚠ THE PROJECTIONS ARE `zonePolygons`' AND `zoneCircles`' OWN, DELIBERATELY. The geometry is
* lon/lat (it came out of `unproject(fromScreen(...))`), so this mounts INSIDE
* `<g transform={tf}>` and holds its ground through every pan, zoom and rotation, exactly as
* the saved boundary it is about to become does. ⛔ Do NOT copy the `.cg-zone-keyboard-draft`
* group's form: that one lives OUTSIDE `tf` on screen coordinates, which is why its clamp
* takes no zoom argument. Inside `tf` the clamp needs `view.k` or the screen bound goes slack.
*/
const unsavedZoneShape = useMemo(() => {
const geometry = drawnZoneGeometry;
if (!geometry) return null;
if (geometry.type === "Circle") {
const center = project(geometry.center[0], geometry.center[1]);
const latitudeRadians = geometry.center[1] * Math.PI / 180;
const lonDelta = geometry.radiusMeters / Math.max(1, 111_320 * Math.cos(latitudeRadians));
const edge = project(geometry.center[0] + lonDelta, geometry.center[1]);
return { kind: "circle" as const, center, radius: Math.abs(edge.x - center.x) };
}
const polygons = geometry.type === "Polygon"
? [geometry.coordinates as number[][][]]
: geometry.type === "MultiPolygon"
? geometry.coordinates as number[][][][]
: [];
// A pair that is not two finite numbers is dropped rather than projected: `project` would
// return NaN and one NaN in a `points` list voids the WHOLE polygon, so a single bad vertex
// would put the screen back exactly where instruction 20 found it.
const rings = polygons
.flatMap((polygon) => polygon.map((ring) => ring
.filter((pair) => Array.isArray(pair) && Number.isFinite(pair[0]) && Number.isFinite(pair[1]))
.map((pair) => project(pair[0], pair[1]))))
.filter((ring) => ring.length >= 3)
.map((ring) => ring.map((point) => `${point.x.toFixed(2)},${point.y.toFixed(2)}`).join(" "));
return rings.length ? { kind: "polygon" as const, rings } : null;
}, [drawnZoneGeometry]);
/**
* ⛔⛔ W46-T28 — `pendingGeometry` IS THE FIX FOR "IT WON'T EVEN LET ME SAVE", and it is here
* rather than in a `useEffect` because React state set in the same tick is not readable from
* this closure. The Save button commits a still-open click-drawn outline and hands the
* geometry straight down, so the save does not have to wait a render for `drawnZoneGeometry`.
*/
const saveZone = useCallback(async (existing?: MapZone, pendingGeometry?: ZoneGeometry) => {
const geometryGeoJson = pendingGeometry || drawnZoneGeometry || existing?.geometryGeoJson;
const name = zoneName.trim() || existing?.name || "";
if (!name || !geometryGeoJson) {
setZoneErr("Name a Zone and draw its boundary on the map.");
return;
}
if (normalizedCustomerZones && !existing && !activeView?.id) {
setZoneErr("Open a saved View before creating a Customer Zone.");
return;
}
setZoneBusy(true);
setZoneErr(null);
try {
const res = await routingFetch(existing ? zoneItemPath(tableKey, existing.id) : zoneCollectionPath(tableKey), {
method: existing ? "PATCH" : "POST",
credentials: "same-origin",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(zoneMutationPayload(tableKey, existing?.sourceViewId || activeView?.id || null, {
name,
color: zoneColor || existing?.color || ZONE_COLOR_CHOICES[0].value,
geometryGeoJson,
visible: existing?.visible ?? true,
})),
});
const body = await res.json().catch(() => null);
if (!routingAlive.current) return;
if (!res.ok) {
setZoneErr(body?.error?.message || "The Zone could not be saved.");
return;
}
const saved = body?.zone as MapZone | undefined;
if (saved) {
setZones((current) => {
const without = (current || []).filter((zone) => zone.id !== saved.id);
return [...without, saved].sort((a, b) => a.name.localeCompare(b.name));
});
setActiveZoneIds((current) => {
const next = new Set(current);
if (saved.visible) next.add(saved.id);
else next.delete(saved.id);
return next;
});
setZoneEditorId(saved.id);
setZoneEditorOpen(false);
if (normalizedCustomerZones) onZoneChanged?.(applicationId);
}
setDrawnZoneGeometry(null);
setZoneName("");
} catch {
setZoneErr("The Zone could not be saved.");
} finally {
setZoneBusy(false);
}
}, [drawnZoneGeometry, zoneName, zoneColor, tableKey, normalizedCustomerZones,
activeView?.id, onZoneChanged, routingFetch, applicationId]);
const setZoneVisible = useCallback(async (zone: MapZone, visible: boolean) => {
setZoneBusy(true);
setZoneErr(null);
try {
const res = await routingFetch(zoneItemPath(tableKey, zone.id), {
method: "PATCH",
credentials: "same-origin",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(zoneMutationPayload(tableKey, zone.sourceViewId || activeView?.id || null, { visible })),
});
const body = await res.json().catch(() => null);
if (!routingAlive.current) return;
if (!res.ok) {
setZoneErr(body?.error?.message || "The Zone visibility could not be updated.");
return;
}
const saved = body?.zone as MapZone | undefined;
if (saved) {
setZones((current) => (current || []).map((item) => item.id === saved.id ? saved : item));
if (!saved.visible && activeZoneIds.has(saved.id)) toggleZone(zone, false);
if (normalizedCustomerZones) onZoneChanged?.(applicationId);
}
} catch {
setZoneErr("The Zone visibility could not be updated.");
} finally {
setZoneBusy(false);
}
}, [tableKey, activeZoneIds, toggleZone, activeView?.id, normalizedCustomerZones, onZoneChanged, routingFetch, applicationId]);
/** Persist a direct boundary drag without re-deriving membership from the current selection. */
const persistZoneGeometry = useCallback(async (zone: MapZone, geometryGeoJson: ZoneGeometry) => {
setZoneBusy(true);
setZoneErr(null);
try {
const res = await routingFetch(zoneItemPath(tableKey, zone.id), {
method: "PATCH",
credentials: "same-origin",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(zoneMutationPayload(
tableKey, zone.sourceViewId || activeView?.id || null, { geometryGeoJson },
)),
});
const body = await res.json().catch(() => null);
if (!routingAlive.current) return;
if (!res.ok) {
setZoneErr(body?.error?.message || "The Zone boundary could not be saved.");
return;
}
const saved = body?.zone as MapZone | undefined;
if (saved) {
setZones((current) => (current || []).map((item) => item.id === saved.id ? saved : item));
if (normalizedCustomerZones) onZoneChanged?.(applicationId);
}
} catch {
setZoneErr("The Zone boundary could not be saved.");
} finally {
setZoneBusy(false);
}
}, [tableKey, activeView?.id, normalizedCustomerZones, onZoneChanged, routingFetch, applicationId]);
const deleteZone = useCallback(async (zone: MapZone) => {
setZoneBusy(true);
setZoneErr(null);
try {
const generic = !normalizedCustomerZones;
const res = await routingFetch(zoneItemPath(tableKey, zone.id), {
method: "DELETE",
credentials: "same-origin",
...(generic ? {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ tableKey }),
} : {}),
});
const body = await res.json().catch(() => null);
if (!routingAlive.current) return;
if (!res.ok) {
setZoneErr(body?.error?.message || body?.detail?.message || "The Zone could not be deleted.");
return;
}
setZones((current) => (current || []).filter((item) => item.id !== zone.id));
setActiveZoneIds((current) => {
const next = new Set(current);
next.delete(zone.id);
return next;
});
setZoneEditorId("");
setZoneEditorOpen(false);
if (normalizedCustomerZones) onZoneChanged?.(applicationId);
} catch {
setZoneErr("The Zone could not be deleted.");
} finally {
setZoneBusy(false);
}
}, [normalizedCustomerZones, onZoneChanged, tableKey, routingFetch, applicationId]);
// The fit is the INITIAL view, not the projection (see mapProjection.ts).
const fit = useMemo(
() => fitView(points.map((p) => p.p), VIEW_W, VIEW_H) ?? (routeApplication
? fitView([{ x: 0, y: 0 }, { x: WORLD, y: WORLD }], VIEW_W, VIEW_H)
: null),
[points, routeApplication]
);
useEffect(() => {
if (!fit) return;
if (!touchedRef.current || view == null) setView(fit);
// `view` is deliberately absent from the deps: this effect exists to seed
// and re-fit, and re-running it on every pan would fight the user for the
// camera.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [fit]);
/* ═══════════════ W51-T28 / C8 — ESCAPE CLOSES THE MAP'S OWN PANELS ═══════════════════════
*
* ⛔ THE TWO CLOSE ACTIONS ARE NAMED CALLBACKS, AND THE `Back` BUTTONS CALL THE SAME ONES.
* Escape that does something slightly different from the visible close is a second behaviour
* wearing the first one's name; sharing the callback makes "Escape does what Back does" a
* property of the code rather than a claim about it.
*
* ⚠ THE `active` FLAGS MUST MATCH THE RENDER CONDITIONS, INCLUDING THE EMPTY STATE. This
* component returns `.cg-mode-empty` early when there is no camera and no fit, and that branch
* renders none of these panels. A claim on Escape from a panel nobody can see would swallow the
* key from whatever IS on screen, so `mapCanvasMounted` is part of both flags. The two panel
* expressions are hoisted here rather than duplicated: the render sites below read these same
* constants, so the flag and the panel cannot drift apart.
*
* ⭐ THE TOPMOST-WINS ORDER IS NOT CONFIGURED ANYWHERE, ON PURPOSE. `useEscapeClose` keeps ONE
* push-ordered stack, and `ConfirmDialog` joins it when it opens, i.e. after the panel that
* opened it. So Escape closes the dialog first and the panel underneath on the second press,
* with no priority number, no z-index and no second listener involved.
*
* ⚠ `cancelEditFirst` STAYS AT ITS DEFAULT FALSE. These are panels holding a Zone-name input
* and a search box; opting in would turn every one of those into a two-Escape close.
*/
const mapCanvasMounted = view != null && fit != null;
const zoneChooserPanelOpen = zones !== null && mapNavigator === "zones" && !zoneEditorOpen;
const zoneEditorPanelOpen = zones !== null && mapNavigator === "zones" && zoneEditorOpen;
const closeZoneChooser = useCallback(() => setZoneNavigatorOpen(false), []);
const closeZoneEditor = useCallback(() => {
setZoneErr(null);
setZoneEditorOpen(false);
}, []);
useEscapeClose(mapCanvasMounted && zoneChooserPanelOpen, closeZoneChooser);
useEscapeClose(mapCanvasMounted && zoneEditorPanelOpen, closeZoneEditor);
/**
* W37-T35 — HOW FAR IN THE CAMERA MAY GO, and the answer now depends on what is under the pins.
*
* `BASEMAP_DETAIL_K` is an HONESTY limit on the VENDORED geometry: past it you are magnifying a
* generalised polygon and learning nothing. Real tiles have their own resolution, several orders
* further in, so keeping that cap while a street map is loaded would be a limit with no subject.
*
* ⚠ `zoomLimits`' second term (`fitK * 60`) also binds, and it binds FIRST: a US-wide fit sits
* near k=1.36, so 60x lands around tile zoom 10 and the user never reaches a street whatever
* `detailK` says. So the tile branch computes its ceiling from the PROVIDER's own max zoom
* rather than taking that helper's answer. `kMin` is still the helper's, unchanged.
*/
const { kMin, kMax } = useMemo(() => {
if (!fit) return { kMin: 1, kMax: 1 };
const vector = zoomLimits(fit.k, VIEW_H, BASEMAP_DETAIL_K);
if (!tilesOk) return vector;
return { kMin: vector.kMin, kMax: Math.max(fit.k, kForTileZoom(tiles.maxZoom)) };
}, [fit, tilesOk, tiles.maxZoom]);
/**
* W37-T35 — WHICH TILES COVER WHAT IS ON SCREEN.
*
* ⭐ THE REASON THIS IS ~20 LINES AND NOT A LIBRARY: `mapProjection.project` is already fixed Web
* Mercator onto a 0..WORLD square, which IS the tile scheme's own coordinate system scaled by
* WORLD. So tile (x, y) at zoom z occupies exactly `[x*S, (x+1)*S] x [y*S, (y+1)*S]` with
* `S = WORLD / 2^z`, and dropping the images inside the SAME transformed group as the pins makes
* them pan and zoom in lockstep with the geography. There is no second camera to keep in sync,
* which is the failure mode a tile library would have been carrying the weight of.
*
* ⚠ Clamped to the world, never wrapped. Panning past the antimeridian shows no tiles rather
* than a second copy of the planet, and the vendored coastline never wrapped either.
*/
const tileLayer = useMemo(() => {
if (!view || !tilesOk || !tiles.url) return null;
const z = Math.max(0, Math.min(tiles.maxZoom, googleZoomForK(view.k)));
const n = Math.pow(2, z);
const S = WORLD / n;
// ⭐ OWNER ITEM 1 (2026-08-23) — ALL FOUR CORNERS, NOT TWO. Two corners describe the world
// rectangle on screen only while the map is north-up; the moment it carries a bearing the
// screen rectangle is a rotated QUADRILATERAL in world space, and its top-left corner is no
// longer its minimum on either axis. Taking two would have left a triangular wedge of the
// frame with no tiles under it at every bearing that is not a multiple of 90 degrees.
// ⚠ THE BUDGET IS NOT THE BINDING CONSTRAINT, measured rather than assumed: the frame is
// 1000x620 units at ~1.08 CSS px each, and `googleZoomForK` targets ~256 CSS px per tile, so
// a north-up frame asks for roughly 5x4 tiles. The worst bearing (45 degrees) grows the
// bounding box to ~1145x1145 units, i.e. ~5x5 tiles. Both are an order of magnitude under
// `TILE_BUDGET`.
const corners = [
fromScreen({ x: 0, y: 0 }, view),
fromScreen({ x: VIEW_W, y: 0 }, view),
fromScreen({ x: 0, y: VIEW_H }, view),
fromScreen({ x: VIEW_W, y: VIEW_H }, view),
];
const minX = Math.min(...corners.map((c) => c.x));
const maxX = Math.max(...corners.map((c) => c.x));
const minY = Math.min(...corners.map((c) => c.y));
const maxY = Math.max(...corners.map((c) => c.y));
const x0 = Math.max(0, Math.floor(minX / S));
const x1 = Math.min(n - 1, Math.floor(maxX / S));
const y0 = Math.max(0, Math.floor(minY / S));
const y1 = Math.min(n - 1, Math.floor(maxY / S));
if (x1 < x0 || y1 < y0) return null;
// One tile-pixel of overlap. Tile edges land on fractional device pixels at most zooms, and
// without it the seams paint as a faint grid across the whole basemap.
const over = S / 256;
const items: { key: string; x: number; y: number; s: number; href: string }[] = [];
for (let ty = y0; ty <= y1 && items.length < TILE_BUDGET; ty++) {
for (let tx = x0; tx <= x1 && items.length < TILE_BUDGET; tx++) {
items.push({
key: `${z}/${tx}/${ty}`,
x: tx * S,
y: ty * S,
s: S + over,
href: tiles.url
.replace("{z}", String(z))
.replace("{x}", String(tx))
.replace("{y}", String(ty)),
});
}
}
return {
z,
items,
bed: { x: x0 * S, y: y0 * S, w: (x1 - x0 + 1) * S, h: (y1 - y0 + 1) * S },
};
}, [view, tilesOk, tiles.url, tiles.maxZoom]);
/** Colour buckets, in first-seen order so the legend is stable. */
const colorBuckets = useMemo(() => {
if (!colorField) return null;
const order: string[] = [];
const counts = new Map<string, number>();
for (const p of points) {
const k = p.colorKey ?? "";
if (!counts.has(k)) {
counts.set(k, 0);
order.push(k);
}
counts.set(k, (counts.get(k) ?? 0) + 1);
}
const named = order.filter((k) => k !== "");
const swatch = new Map<string, { fill: string; line: string }>();
named.forEach((k, i) => swatch.set(k, i < SERIES.length ? SERIES[i] : OVERFLOW));
return {
order,
counts,
swatch,
overflow: Math.max(0, named.length - SERIES.length),
};
}, [colorField, points]);
/** The size field's observed range across MAPPED points (not the whole table:
* the legend must describe the picture actually on screen). */
const sizeRange = useMemo(
() => bubbleSizeRange(points.map((p) => p.size), !!sizeField),
[sizeField, points]
);
/** A coarse pointer means a phone or tablet, where Google's free URL takes 3
* waypoints rather than 9. A media query, not user-agent sniffing. */
const coarsePointer = useMemo(
() =>
typeof window !== "undefined" &&
typeof window.matchMedia === "function" &&
window.matchMedia("(pointer: coarse)").matches,
[]
);
const activeRouteMaps = useMemo(() => {
if (!activeNamedRoute) return { links: [], missingStopIds: [], refusal: null };
const wanted = new Set(activeNamedRoute.visibleStopIds);
const located = [] as { pid: number; lat: number; lon: number }[];
for (const row of (allRows?.length ? allRows : mapRows)) {
if (!wanted.has(row.pid)) continue;
const at = rowCoordinates(row, coordinateFields, coordField, sessionCoordinates);
if (at) located.push({ pid: row.pid, lat: at.lat, lon: at.lon });
}
return normalizedRouteMapLinks(activeNamedRoute.visibleStopIds, located, coarsePointer);
}, [activeNamedRoute, allRows, coarsePointer, coordinateFields, coordField, mapRows, sessionCoordinates]);
const activeRouteMapsRefusal = activeRouteMaps.missingStopIds.length
? `${activeRouteMaps.missingStopIds.length.toLocaleString()} Route stop${activeRouteMaps.missingStopIds.length === 1 ? " has" : "s have"} no map location. Add coordinates before opening Maps links.`
: activeRouteMaps.refusal;
/** Selected pins that can actually be routed, in a STABLE order (by pid) —
* a Set's iteration order must not be what decides a route. */
const customerRoutable = useMemo(
() =>
selectedPids.size < 2
? []
: points
.filter((p) => selectedPids.has(p.pid) && isPlottable(p.lat, p.lon))
.sort((a, b) => a.pid - b.pid),
[points, selectedPids]
);
useEffect(() => {
if (!recordsPending && routeOn && customerRoutable.length < 2) {
setRouteOn(false);
setRouteOrder(null);
setRoad(null);
setRoadErr(null);
}
}, [routeOn, customerRoutable.length, recordsPending]);
/**
* ⭐⭐ OWNER ITEM 3 (2026-08-23) — OPENING **Route** ROUTES THE VIEW.
*
* Owner: *"I have to select first before the route populates? I want it so that by default,
* when I click the Route button. It already selects everything in that View as the route."*
* So opening the panel with nothing chosen takes the view's own pins as the cohort and solves
* them, instead of showing an empty planner and a sentence about shift-clicking.
*
* ⛔ IT ARMS THE LOCAL SOLVE AND **NOT** THE ROAD REQUEST, which is R3 honoured rather than
* bent. R3 forbids SPENDING a routing request on anything but a click; `planRoute` is local
* arithmetic that costs nothing and runs in single-digit milliseconds at the cap, so the
* sequence, the distance estimate and the drawn line are there on open, and the provider is
* asked only when somebody presses Driving route. `askRoadRef` is deliberately not set here.
*
* ⛔ AND IT NEVER OVERRIDES A CHOICE ALREADY MADE. A person who selected pins and then opened
* the panel keeps their selection; the auto-fill is for the empty case, which is the one the
* owner is describing.
*
* ⚠ ONCE PER OPENING, VIA A REF. `points` and `selectedPids` both move constantly (a pan does
* not, but an edit does), and an effect that re-ran on them would keep dragging the selection
* back to the whole view every time the user narrowed it by hand.
* ⚠ AND THE REF IS ARMED ONLY WHEN THERE WERE PINS TO TAKE. Opening the panel while the rows
* are still loading would otherwise consume the one shot on an empty map.
*
* ⛔ CAPPED AT `ROUTE_STOP_CAP`, IN THE VIEW'S OWN ORDER, AND SAID OUT LOUD. `rows` reaches
* this component through `useVisibleRows`' filter -> search -> SORT -> group pipeline, so
* "the first N" means the first N as the view is sorted -- the user's own ranking, which is
* the only ranking this surface has. The owner asked for "the top SKU"; the map has no SKU,
* and inventing one would be a plausible order nobody chose. Bulk selection now remains an
* explicit action, so simply opening the route rail cannot alter the current selection.
*/
/**
* Opening Routes is intentionally inert. This explicitly labelled control is the sole bulk
* selection door: it takes every record matched by the current View (never a hidden cap of
* mapped pins) and then starts the local planner.
*/
/** The depot joins BOTH index-parallel arrays below at position zero, and only there. */
const depotPoint = useMemo((): MapPoint | null => {
if (!depot || !isPlottable(depot.lat, depot.lon)) return null;
return {
pid: DEPOT_PID,
title: "Depot",
p: project(depot.lat, depot.lon),
lat: depot.lat,
lon: depot.lon,
colorKey: null,
size: null,
colorVal: null,
sizeVal: null,
};
}, [depot]);
const routable = useMemo(
() => depotPoint ? [depotPoint, ...customerRoutable] : customerRoutable,
[depotPoint, customerRoutable]
);
/** Selected records with no usable coordinate. Counted and shown, never
* folded silently into the stop total ([[no-unverifiable-aggregates]]). */
const unroutable = selectedPids.size - customerRoutable.length;
/** Selected records with no usable coordinate, BY NAME. W37-T36: the chip used to give a bare
* count, which tells you that something is missing and not which visit you are about to fail to
* make. Three names inline, the rest on the tooltip, so the bar cannot be swamped by a big
* selection while the full list stays one hover away. */
const unroutableNames = useMemo(() => {
// ⚠ Read from `rows` and NOT from `points`: a record with no coordinate never becomes a point
// in the first place, so filtering the pin list for unplottable pins finds exactly nothing.
// That mistake would have shipped a chip whose count said 4 and whose names said none.
const ok = new Set(customerRoutable.map((p) => p.pid));
return mapRows
.filter((r) => selectedPids.has(r.pid) && !ok.has(r.pid))
.map((r) => String(r[field.key] ?? "").trim() || `#${r.pid}`);
}, [mapRows, field.key, selectedPids, customerRoutable]);
const plan = useMemo(() => {
if (!routeOn || customerRoutable.length < 2) return null;
const stops: GeoStop[] = routable.map((p) => ({ lat: p.lat, lon: p.lon }));
// Default origin: the WESTERNMOST stop. Deterministic, stable while the user
// pans, and sayable out loud — unlike "whatever ended up at index 0". The
// picker below overrides it.
let start = 0;
if (!depotPoint) {
for (let i = 1; i < routable.length; i++)
if (routable[i].lon < routable[start].lon) start = i;
if (routeStartPid != null) {
const i = routable.findIndex((p) => p.pid === routeStartPid);
if (i >= 0) start = i;
}
}
const end = !roundTrip && !depotPoint && routeEndPid != null
? routable.findIndex((p) => p.pid === routeEndPid) : -1;
// A selected terminal is part of the solve, not an element moved after it. The latter can
// paint a correct-looking endpoint with kilometres calculated for another one. Round trips
// clear the terminal before arriving here and retain the established closed-tour planner.
const planned = end >= 0 && end !== start
? endpointRoutePlan(stops, haversineKm, { start, end, roundTrip })
: planRoute(stops, haversineKm, { start, roundTrip });
const { order, km } = planned;
// ⭐⭐ W38-T20 — THE HAND-REORDER STAYS IN **INDEX** SPACE, and that is a deliberate change of
// representation rather than a tidy-up. `stops`, `routable` and `order` are one index space
// already (`order.map(i => routable[i])` is what zips them back), and the visit NUMBER a
// record carries is the inverse of a permutation over exactly that space. Rebuilding the
// sequence out of MapPoints and then recovering indices from it would be a second, silent
// conversion between the two — and W38-T21 prepends a synthetic depot into this same index
// space, which is far harder to reason about across two representations than one.
// ⚠ EXACTLY THE OLD BEHAVIOUR: `order` is a permutation of every index and `ordered` was
// `order.map(i => routable[i])`, so filtering `order` by index-not-seen selects the same
// stops, in the same sequence, as filtering `ordered` by pid-not-seen did.
let seq = order;
// W37-T36 — a hand-picked order wins over the planner's, but only for the stops that are still
// selected. Anything the user has since deselected drops out; anything newly selected is
// appended in the planner's own order rather than being silently left off the route.
if (routeOrder) {
const idxByPid = new Map(
routable.filter((p) => p.pid !== DEPOT_PID).map((p, i) => [p.pid, depotPoint ? i + 1 : i])
);
const picked = routeOrder
.map((pid) => idxByPid.get(pid))
.filter((i) => i !== undefined) as number[];
const seen = new Set(picked);
seq = [
...(depotPoint ? [0] : []),
...picked,
...order.filter((i) => !seen.has(i) && (!depotPoint || i !== 0)),
];
}
/**
* ⭐⭐ W46-T21 / D-469 — WHY THE HAND ORDER IS CANONICALISED BEFORE IT IS HASHED.
*
* `routeFingerprint`'s canon carries an `h:<handOrder>` term, and the two sides of the
* staleness comparison disagreed about it STRUCTURALLY, not because anything changed:
* at SAVE the planner had solved the order, so `routeOrder` was null and the stored hash
* carried `h:` EMPTY; on REOPEN the arming effect sets `routeOrder` to the saved sequence,
* so the live hash carried `h:6534,...`. They can never be equal, so EVERY saved route read
* Stale forever, including one saved seconds earlier. That is D-469, and the "third term"
* it could not isolate is this: the same term, present on one side and absent on the other.
*
* ⛔ THE `h:` TERM IS NOT DELETED, because D-429 depends on it: a genuine HAND edit must still
* read as not-freshly-solved. Instead it contributes NOTHING when the applied sequence IS the
* planner's own answer, which is the only case where a hand order carries no information.
* A real hand edit differs from `order` and keeps its `h:`.
*
* ⭐ NO MIGRATION. Shape (ii) - re-hashing at save time with the order actually saved - would
* have left every already-stored hash permanently mismatched, including the 52 routes stamped
* 2026-08-23 that D-469 measured.
*
* ⚠ TWO OTHER TERMS ARE STILL ASYMMETRIC and this does NOT reach them: the column stores
* `roundTrip` and `startPid`, and neither reopen path restores them, so a route saved
* round-trip, or with an explicitly picked origin, still mismatches. Restoring them would
* flip the map's own round-trip toggle when a route opens, which is a visible behaviour change
* made for a staleness marker that this file no longer computes at all: W47-T09 deleted the
* derivation under R9, because it was always false on the shipped UI. Left deliberately, and
* recorded, for whoever next puts a staleness mark on screen.
*/
const seqEqualsOrder = seq.length === order.length && seq.every((v, i) => v === order[i]);
const ordered = seq.map((i) => routable[i]);
// ⛔⛔ THE PERMUTATION IS NOT THE RANK (A25 / A44). `seq[i]` is WHICH STOP is visited i-th;
// the number a record carries is the other way round, and `routeRanks` is the one inversion.
// It is called HERE, in the shipped path, and not only in the gate: a tested function the
// product does not use guards nothing (`paintedRadius`'s docstring is this repo's record of
// that, and the wave-29 client-px conversion is the scar).
const ranks = routeRanks(seq, routable.length);
return {
ordered,
km,
/** `{pid: visit number}` — what the route-order COLUMN stores, one integer per record. */
ranksByPid: routable.reduce((acc, p, i) => {
const n = ranks[i];
if (p.pid !== DEPOT_PID && n != null) acc[p.pid] = depotPoint ? n - 1 : n;
return acc;
}, {} as Record<number, number>),
/**
* The identity of the INPUTS this order was solved from, so staleness can be DERIVED at
* read time rather than stored. A saved column carries the fingerprint it was solved with;
* when this one differs, what is on screen would solve to different numbers.
*/
fingerprint: routeFingerprint(
routable.map((p) => ({ pid: p.pid, lat: p.lat, lon: p.lon } as RouteStamp)),
// ⚠ THE RESOLVED ORIGIN, NOT `routeStartPid`. The picker is null while the westernmost
// default applies, so keying on it would report STALE the moment somebody explicitly
// selects the stop that was ALREADY the origin — the numbers unchanged, the marker on.
// What the answer depends on is which stop the planner was actually given.
{ roundTrip, startPid: depotPoint ? null : routable[start].pid,
handOrder: seqEqualsOrder ? null : routeOrder }
),
/** The origin the planner was given, so the saved column records the same one the
* fingerprint was taken over. */
startPid: depotPoint ? null : routable[start].pid,
links: googleRouteUrls(
ordered.map((p) => ({ lat: p.lat, lon: p.lon })),
{ roundTrip, coarsePointer, maxStops: mapsPerLink }
),
/** The identity of THIS set of stops in THIS order. The road answer is only about the plan
* whose key it carries; anything else on screen makes it stale rather than wrong. */
key: ordered.map((p) => `${p.pid}@${p.lat.toFixed(6)},${p.lon.toFixed(6)}`).join(",") +
(roundTrip ? "|rt" : ""),
depot: depotPoint ? depot : null,
customerStops: customerRoutable.length,
};
}, [routeOn, routable, customerRoutable.length, depotPoint, depot, roundTrip, routeStartPid, routeEndPid,
coarsePointer, routeOrder, mapsPerLink]);
/** ⭐ ITEM 7 — a MODE change stales the drawn road exactly as a stop change does. Without the
* second clause, flipping to Walking would leave driving minutes on screen under a Walking
* toggle, which is the failure this whole seam was built to prevent. */
const roadStale =
!!road && !!plan && (road.key !== plan.key || road.mode !== travelMode);
/**
* W37-T36 — ask the routing service for the ROAD answer.
*
* ⛔ CALLED FROM A CLICK AND FROM NOTHING ELSE. There is deliberately no effect that watches
* `plan` and refetches, because R3 forbids computing a route on a render or a selection change
* and an effect on `plan` is exactly both. The stale marker is what covers the gap: the user
* sees that the drawn route no longer matches the stops and asks again when they want to.
*/
const fetchRoad = useCallback(async () => {
if (!plan || plan.ordered.length < 2) return;
const key = plan.key;
const stops = plan.ordered.map((p) => ({ lat: p.lat, lon: p.lon, pid: p.pid }));
setRoadBusy(true);
setRoadErr(null);
try {
const res = await routingFetch("/api/v1/geo/route", {
method: "POST",
credentials: "same-origin",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
stops,
roundTrip,
mode: travelMode,
// The server closes a round trip itself, so there is one authoritative definition of
// the return leg. Chosen endpoints remain explicit rather than inferred from an old
// saved ordering that may have been re-solved locally.
startPid: routeStartPid ?? undefined,
endPid: roundTrip ? undefined : routeEndPid ?? undefined,
}),
});
const body = await res.json().catch(() => null);
if (!routingAlive.current) return;
if (!res.ok) {
// The SERVER's sentence, not a generic one. It distinguishes a provider timeout, an
// upstream HTTP failure, an impossible road route and a request that is too large.
const message = body?.detail?.error?.message || body?.error?.message ||
body?.detail?.message || body?.detail;
setRoadErr(String(message ||
"Driving route unavailable. The straight-line estimate remains on the map; try again."));
setRoad(null);
return;
}
setRoad({
km: Number(body.km) || 0,
minutes: Number(body.minutes) || 0,
line: Array.isArray(body.line) ? body.line : [],
key,
attribution: String(body.attribution || ""),
// ⚠ THE SERVER'S mode, not the state's. The toggle can move while the request is in
// flight, and labelling the answer from the state would then caption a driving route
// "Walking" for exactly as long as nobody re-asked.
mode: body.mode === "walking" ? "walking" : "driving",
});
} catch {
setRoadErr("The routing service could not be reached. The straight-line estimate remains on the map; try again.");
setRoad(null);
} finally {
setRoadBusy(false);
}
}, [plan, roundTrip, routeEndPid, routeStartPid, travelMode, routingFetch]);
/**
* ⛔ THE ONE-SHOT THAT MAKES "PLAN ROUTE" A SINGLE CLICK WITHOUT BECOMING AN AUTO-FETCH.
*
* `plan` is null until `routeOn` flips, so the click handler cannot call `fetchRoad` directly:
* its closure still has the null plan. A ref set by the click and consumed here fires the
* request exactly once, on the render where the plan first exists.
*
* ⚠ This is deliberately NOT `useEffect(..., [plan])` doing the fetch. The effect runs on every
* plan change; only the ones a CLICK armed do anything. That distinction is R3: a selection
* change recomputes the plan and must not spend a request.
*/
useEffect(() => {
if (!askRoadRef.current || !plan) return;
askRoadRef.current = false;
void fetchRoad();
}, [plan, fetchRoad]);
// ─────────────────────────────── W38-T20: the order, as a column every colleague reads ───────
/**
* The saved route-order columns, refreshed from the server.
*
* ⚠ A READ, so it may run without a click, unlike `fetchRoad`. R3 is about not spending a
* ROUTING request on a render; this asks our own store for a short list of column names and is
* the only way the STALE marker can exist at all.
*/
const loadRouteDeliveries = useCallback(async (routeId: string): Promise<RouteDeliveryDto[]> => {
try {
const res = await routingFetch(
`/api/v1/customers/routes/${encodeURIComponent(routeId)}/deliveries`,
{ credentials: "same-origin" },
);
const body = res.ok ? await res.json().catch(() => null) : null;
if (!routingAlive.current) return [];
return Array.isArray(body?.deliveries) ? body.deliveries : [];
} catch {
return [];
}
}, [routingFetch]);
useEffect(() => {
let current = true;
setRouteDeliveries(null);
if (routePanelOpen && activeRouteId) void loadRouteDeliveries(activeRouteId).then((deliveries) => {
if (current) setRouteDeliveries(deliveries);
});
return () => { current = false; };
}, [activeRouteId, loadRouteDeliveries, routePanelOpen]);
const copyRouteLinks = useCallback(async () => {
if (!plan?.links.length) return;
const text = plan.links.map((link) => link.url).join("\n");
if (!navigator.clipboard?.writeText) {
setRouteCopyMsg("Clipboard access is unavailable in this browser.");
return;
}
try {
await navigator.clipboard.writeText(text);
setRouteCopyMsg(`${plan.links.length.toLocaleString()} Google Maps link${plan.links.length === 1 ? "" : "s"} copied.`);
} catch {
setRouteCopyMsg("The Google Maps links could not be copied.");
}
}, [plan]);
const scheduleNamedRouteDelivery = useCallback(async (
route: MapRouteDto,
request: RouteDeliveryRequest,
): Promise<string | null> => {
if (!routingAlive.current) return "This Routing App is no longer open.";
const result = await requestRouteDelivery(route.id, request, undefined, applicationId);
if (!routingAlive.current) return "This Routing App is no longer open.";
if (result.error || !result.delivery) return result.error || "The Route delivery was not saved.";
setRouteDeliveries((current) => [...(current || []).filter(
(delivery) => delivery.id !== result.delivery!.id
), result.delivery!]);
return null;
}, [applicationId]);
const deleteNamedRouteDelivery = useCallback(async (
route: MapRouteDto,
delivery: RouteDeliveryDto,
): Promise<string | null> => {
try {
const res = await routingFetch(
`/api/v1/customers/routes/${encodeURIComponent(route.id)}/deliveries/${encodeURIComponent(delivery.id)}`,
{ method: "DELETE", credentials: "same-origin" },
);
const body = await res.json().catch(() => null);
if (!routingAlive.current) return "This Routing App is no longer open.";
if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route delivery could not be removed.";
setRouteDeliveries((current) => (current || []).filter((item) => item.id !== delivery.id));
return null;
} catch {
return "The Route delivery could not be removed.";
}
}, [routingFetch]);
/**
* OWNER INSTRUCTION 8 (W46-T16) - CLICKING A SAVED ROUTE DRAWS ITS PATH AGAIN.
*
* The polyline is gated on `plan`, and `plan` is null until `routeOn` is armed over two
* routable stops. Wave 44 (`cc429a0`, "unify map route and zone navigation") retired the
* route-order navigator, and the old picker callback - the ONLY writer of `routeOrder` +
* `routeOn` for a saved route - lost its surface with it. It survived from then only in the
* compatibility `void [...]` list below, reachable from no click, until W47-T09 deleted it
* under R9. Since wave 44 every door a person can take to a saved Route (`RouteNav`'s
* `.cg-w44-route-open` button, and the
* `aios:route-open` event) sets `activeRouteId` and nothing else, so `plan` stays null and
* the map draws nothing while erroring nothing. That is the regression, and it predates
* wave 45 rather than arriving with it.
*
* Opening a named Route now arms exactly what the retired picker armed: the stops join
* `addedPids` (so a stop outside the current View still earns a pin through `mapRows`), the
* selection is REPLACED by the route's stop order, `routeOrder` takes that order verbatim so
* `plan.ordered` follows the SAVED sequence rather than the solver's, and the origin picker
* is cleared. It is one path for both kinds of route: a legacy-compatible projection and a
* normalized record both reach the client as `visibleStopIds` ordered by `ordered_stops`.
*
* NO ROAD REQUEST (R3). This is the local straight-line plan only; the provider is asked when
* somebody presses Driving route, exactly as the retired picker had it.
*
* ONCE PER OPENED ROUTE, VIA A REF KEYED ON THE ROUTE'S OWN STOP SEQUENCE. Keying on the id
* alone would be spent on the pass where the `aios:route-open` listener has set an id that
* `namedRoutes` does not carry yet, and would leave `routeOrder` stale after a stop is moved.
* The sequence key re-arms when the SAVED route changes and never fights a hand reorder made
* on the map, which does not touch `visibleStopIds`. Closing the detail clears the key so
* reopening the same route arms it again.
*
* A ROUTE WITH FEWER THAN TWO VISIBLE STOPS IS LEFT ALONE rather than armed into the
* `customerRoutable < 2` teardown effect above.
*/
const armedRouteRef = useRef<string>("");
/** ⭐⭐ OWNER 2026-08-31 item 1 - WHICH added pids a ROUTE put there, so a clear can withdraw
* exactly those. `addedPids` has two writers: opening a Route arms its stops, and the map's
* own "add a record" search adds one by hand. Dropping the whole set on a clear would take
* the hand-picked record with it, which is somebody else's work; dropping none is the defect
* the owner reported. This ref is the difference between the two. */
const routeAddedRef = useRef<Set<number>>(new Set());
useEffect(() => {
if (!activeNamedRoute) {
armedRouteRef.current = "";
return;
}
const stops = activeNamedRoute.visibleStopIds;
if (stops.length < 2) return;
const signature = `${activeNamedRoute.id}:${stops.join(",")}`;
if (armedRouteRef.current === signature) return;
armedRouteRef.current = signature;
for (const pid of stops) routeAddedRef.current.add(pid);
setAddedPids((prev) => {
const next = new Set(prev);
for (const pid of stops) next.add(pid);
return next;
});
onSelectPids([...stops], "replace");
setRouteOrder([...stops]);
setRouteStartPid(null);
setRouteOn(true);
}, [activeNamedRoute, onSelectPids]);
/**
* ⭐⭐ OWNER 2026-08-31 item 1 — AN EMPTIED SELECTION WITHDRAWS WHAT THE ROUTES PUT ON THE MAP.
*
* The host's Clear button (`CustomerGrid.tsx`'s selection bar) empties the selection and drops
* the managed OR clause; the map's half is here, because `addedPids` is MapView's own state and
* the host has no handle on it. Without this, the grid loses the rows and the map keeps the
* pins — half a fix, and the half a person is looking at while they press the button.
*
* ⚠ ONLY ROUTE-ORIGIN PIDS, and only when the selection is EMPTY. A record added by hand from
* the map's own search stays; a Route still ticked always holds a selection, so this cannot
* fire underneath one.
*/
useEffect(() => {
if (selectedPids.size > 0 || routeAddedRef.current.size === 0) return;
const withdraw = routeAddedRef.current;
routeAddedRef.current = new Set();
armedRouteRef.current = "";
setSelectedRouteIds((current) => (current.size ? new Set<string>() : current));
setAddedPids((prev) => {
if (![...withdraw].some((pid) => prev.has(pid))) return prev;
const next = new Set(prev);
for (const pid of withdraw) next.delete(pid);
return next;
});
}, [selectedPids]);
/**
* ⭐⭐ W47-T07 (owner instruction 9) — EVERY TICKED ROUTE ON THE MAP AT ONCE, EACH IN ITS OWN
* COLOUR. Owner: *"we also need a checkbox for us to be able to see each route all together on
* the map. That means we need the ability to color each routes too so its easy to see on the
* map."*
*
* ⛔ THIS IS A GENERALISATION, NOT A SECOND ROUTE SYSTEM. `plan` draws ONE route - the opened
* one - with its solved order and its road answer, and it keeps doing exactly that. These are
* the OTHER ticked routes, drawn from the stop order the record already carries
* (`visibleStopIds`), so nothing here asks the planner or the road provider for anything.
*
* ⭐ THE COLOUR IS THE RECORD'S OWN, AND IT ALREADY PERSISTS: `route_system.py::_color` stamps
* every new Route with a distinct default from `_ROUTE_COLORS` by ordinal, and the sidebar
* swatch has always read `route.color`. So the line and the swatch cannot disagree - they are
* one value - which is the half of this ticket a screenshot has to show.
*
* ⛔ IT GOES THROUGH `zonePaint`. A Route whose colour arrived empty would otherwise paint the
* SVG initial `fill`/`stroke`, which is BLACK - the exact defect W47-T02 closed for Zones, and
* a new render site is a new chance to reopen it.
*
* ⚠ A STOP THAT IS NOT ON THE MAP IS DROPPED, NOT FAKED. `points` carries only rows that
* actually plot, so a route whose stops sit outside the current filter draws the part it can
* and is skipped entirely below two points. That is a true picture of a partial route rather
* than a line to nowhere.
*/
const overlaidRoutes = useMemo(() => {
if (!view || selectedRouteIds.size === 0) return [];
const byPid = new Map(points.map((point) => [point.pid, point.p]));
return namedRoutes
.filter((route) => selectedRouteIds.has(route.id))
.map((route) => ({
id: route.id,
color: zonePaint(route.color),
pts: (route.visibleStopIds || [])
.map((pid) => byPid.get(pid))
.filter((at): at is { x: number; y: number } => !!at),
}))
.filter((overlay) => overlay.pts.length > 1);
}, [namedRoutes, points, selectedRouteIds, view]);
/** The drawn road, projected once per answer. Straight-line fallback stays in `plan`, so a map
* that never got a road answer still shows the sequence it worked out for itself. */
const roadPath = useMemo(() => {
if (!road || road.line.length < 2) return null;
return road.line
.map((c) => {
const p = project(c[0], c[1]);
return `${p.x.toFixed(2)},${p.y.toFixed(2)}`;
})
.join(" ");
}, [road]);
/**
* W37-T37 — SELECTED RECORDS THAT COULD GAIN A LOCATION.
*
* ⛔ SELECTED, and that word is the whole guard. There is no expression here that means "every
* record without a pin": R3 forbids geocoding a table, and the way to forbid it is to have no
* code that can express it. Somebody chose these rows on this screen.
*/
const geocodable = useMemo(() => {
const addrKey = coordField?.geocode?.addressField;
if (!addrKey || !coordField || selectedPids.size === 0) return [];
const placed = new Set(points.map((p) => p.pid));
return mapRows.filter((r) => selectedPids.has(r.pid) && !placed.has(r.pid));
}, [mapRows, coordField, selectedPids, points]);
/** The estimate, in the words a person plans with. ⚠ Built from the SERVER's measured
* seconds-per-address, never from the published rate limit: the limit is a floor on politeness
* and was measured at a third of the real latency, so quoting it promises a minute and takes
* three. */
const geoEstimate = useMemo(() => {
const secs = Math.round(geocodable.length * geoSeconds);
if (secs < 90) return `about ${Math.max(5, secs)} seconds`;
const mins = Math.round(secs / 60);
return `about ${mins} minute${mins === 1 ? "" : "s"}`;
}, [geocodable.length, geoSeconds]);
const runGeocode = useCallback(async () => {
const addrKey = coordField?.geocode?.addressField;
if (!addrKey || (!onGeocoded && !geocodeSessionOnly) || geocodable.length === 0) return;
setGeo({ busy: true, done: 0, total: geocodable.length, found: 0, error: null });
let found = 0;
try {
// ⛔ BATCHED BY THE SERVER'S OWN `maxBatch`, and the loop lives HERE rather than there on
// purpose: a single request that sat on the connection for eight minutes would be killed by
// every proxy between us, and would report nothing until it finished. Small calls mean the
// count on screen moves, and an interrupted run keeps the records it already placed.
for (let i = 0; i < geocodable.length; i += geoBatch) {
const slice = geocodable.slice(i, i + geoBatch);
const res = await fetch("/api/v1/geo/geocode", {
method: "POST",
credentials: "same-origin",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
records: slice.map((r) => ({ key: r.pid, row: r })),
config: { addressField: addrKey, country: coordField?.geocode?.country },
}),
});
const body = await res.json().catch(() => null);
if (!routingAlive.current) return;
if (!res.ok) {
setGeo((g) => ({
...g, busy: false,
error: (body && body.detail && body.detail.error && body.detail.error.message) ||
"The address lookup service did not answer.",
}));
return;
}
const located = (body.results || [])
.filter((r: { found?: boolean }) => r && r.found)
.map((r: { key: number; lat: number; lon: number }) => ({
pid: Number(r.key), lat: r.lat, lon: r.lon,
}));
const writes = located.map((r: { pid: number; lat: number; lon: number }) => ({
pid: r.pid,
// The cell shape contract C7 fixes, at the precision `googleMapsUrl` already uses so
// the cell, the pin and the hand-off link agree to the digit.
value: `${r.lat.toFixed(6)},${r.lon.toFixed(6)}`,
}));
found += located.length;
// ⭐ HANDED OVER PER BATCH, not at the end. A run over 300 records is minutes long, and
// a person who navigates away mid-run should keep every coordinate already paid for.
if (located.length && geocodeSessionOnly) {
setSessionCoordinates((current) => {
const next = new Map(current);
for (const point of located) next.set(point.pid, { lat: point.lat, lon: point.lon });
return next;
});
} else if (writes.length) {
onGeocoded?.(writes);
}
setGeo((g) => ({ ...g, done: Math.min(g.total, i + slice.length), found }));
}
setGeo((g) => ({ ...g, busy: false }));
} catch {
setGeo((g) => ({ ...g, busy: false, error: "The address lookup could not be reached." }));
}
}, [coordField, onGeocoded, geocodable, geoBatch, geocodeSessionOnly]);
/** The depot has no row, so it uses the address-list form of the same bounded lookup and wait. */
/**
* ⭐ OWNER ITEM 9 — TAKE THIS CUSTOMER OFF THE ROUTE.
*
* ⛔ IT DESELECTS RATHER THAN KEEPING A LOCAL EXCLUSION LIST, and that is the whole reason the
* panel stays coherent: the head counts `selectedPids`, the stop list counts `plan.ordered`,
* and an exclusion set would have made those two disagree the moment anybody used this. The
* hand-picked order drops it too, or a removed stop would be re-appended by `plan`'s "anything
* newly selected joins in the planner's order" clause the next time the selection moved.
*/
const removeStop = useCallback(
(pid: number) => {
if (pid === DEPOT_PID) return;
onSelectPids([...selectedPids].filter((x) => x !== pid), "replace");
setRouteOrder((prev) => (prev ? prev.filter((x) => x !== pid) : prev));
setAddedPids((prev) => {
if (!prev.has(pid)) return prev;
const next = new Set(prev);
next.delete(pid);
return next;
});
},
[onSelectPids, selectedPids]
);
/**
* ⭐ OWNER ITEM 9 — ADD A RECORD THE VIEW IS NOT SHOWING.
*
* It joins `addedPids` (so `mapRows` gains it and it earns a pin) AND the selection (so every
* count in this panel keeps meaning the same thing). Appended to a hand-picked order rather
* than inserted, because the person adding it is the one who knows where in the day it goes.
*/
const addRecord = useCallback(
(pid: number) => {
setAddedPids((prev) => (prev.has(pid) ? prev : new Set(prev).add(pid)));
onSelectPids([pid], "add");
setRouteOrder((prev) => (prev && !prev.includes(pid) ? [...prev, pid] : prev));
},
[onSelectPids]
);
/**
* ⭐ OWNER ITEM 9 — WHAT THE "Add a record" SEARCH MAY OFFER.
*
* ⛔ THE WHOLE BOOK MINUS WHAT IS ALREADY ON THE ROUTE, and "the whole book" is `allRows` (see
* the prop's own note): after the row wall, before the view's filter. Records already selected
* are excluded because offering them would let a person "add" a stop and see nothing change.
* ⚠ NOT FILTERED BY WHETHER A RECORD HAS A LOCATION. One that has none is addable and then
* lands in the "No location, so not routed" chip, which is the disclosure that already exists;
* hiding it here would make a customer the user can name simply absent from the search, with no
* sentence anywhere saying why.
*/
/**
* ⛔⛔ OWNER, 2026-08-23 — NAMED RECORDS FIRST, UNNAMED LAST, AND THAT IS WHY THE LIST
* LOOKED EMPTY OF ANYTHING USEFUL UNTIL YOU TYPED.
*
* Owner: *"when I click the 'search the database' under the routes, the dropdown shows ??? for
* populating the route. Only when I search and type something does it show something."*
*
* This built EVERY title as `name || "#" + pid` and then sorted the whole mixed list with
* `localeCompare`, which files punctuation ahead of letters. `PICKER_LIST_CAP` then takes the
* first 40 — so with an unsearched query the panel showed forty rows of `#12345` and not one
* customer name, and typing anything at all filtered those placeholder titles away and revealed
* the real records underneath. The bug was never the search; it was the ORDER the cap sliced.
*
* ⚠ THE UNNAMED ARE NOT DROPPED, THEY ARE MOVED. A record with no value in the identity column
* is still addable — it may be exactly the stop somebody is looking for — and hiding it would
* make a record the user can see in the grid simply absent from the search with nothing saying
* why. It sorts last and says what it is instead of wearing a bare id.
*/
const addableRecords = useMemo(() => {
if (!allRows || allRows.length === 0) return [];
const named: { pid: number; title: string; sort: string }[] = [];
const rest: { pid: number; title: string }[] = [];
for (const r of allRows) {
if (selectedPids.has(r.pid)) continue;
const raw = String(r[field.key] ?? "").trim();
// ⛔ THE FIRST LETTER OR DIGIT ONWARD IS WHAT A PERSON ALPHABETISES BY. Leading
// punctuation is not part of a name, so `'AMBIANCE` and `AMBIANCE` file together instead
// of the apostrophe deciding.
const sort = raw.replace(/^[^\p{L}\p{N}]+/u, "");
if (sort) named.push({ pid: r.pid, title: raw, sort });
// — no letter and no digit anywhere: `?`, `-`, `--`. Not a name; it is a record whose
// name was never filled in, wearing a placeholder somebody typed.
else if (raw) rest.push({ pid: r.pid, title: `${raw} (record ${r.pid})` });
else rest.push({ pid: r.pid, title: `Unnamed record ${r.pid}` });
}
named.sort((a, b) => a.sort.localeCompare(b.sort));
rest.sort((a, b) => a.pid - b.pid);
return [...named.map(({ pid, title }) => ({ pid, title })), ...rest];
}, [allRows, selectedPids, field.key]);
const moveStop = useCallback(
(pid: number, delta: number) => {
if (!plan || pid === DEPOT_PID) return;
const ids = plan.ordered.filter((p) => p.pid !== DEPOT_PID).map((p) => p.pid);
const at = ids.indexOf(pid);
const to = at + delta;
if (at < 0 || to < 0 || to >= ids.length) return;
const next = [...ids];
next.splice(to, 0, next.splice(at, 1)[0]);
setRouteOrder(next);
},
[plan]
);
// ⭐ "Keep these compatibility hooks live UNTIL ROUTE-ORDER COLUMNS ARE RETIRED SERVER-SIDE"
// is what this list used to say. They are retired: every tenant schema holds zero of them and
// the four doors are deleted. So the entries that existed only to serve a legacy COLUMN went
// with it -- `routeCols`, the `routeEdit*` bag, `updateRouteDetails` and the listing fetch that
// put a 404 in the console on every panel open. What remains below is the retired-PANEL surface
// (W47-T09 / R9), which is a different retirement and still parks its state here unread.
void [
formatDuration, ROUTE_STOP_CAP, RecordPicker, setDepot, setTravelMode, travelModes,
roadBusy, roadErr, routeCopyMsg,
openErr, naming, nameDraft, setNameDraft,
saveBusy, saveMsg, saveErr, unroutable, unroutableNames,
copyRouteLinks,
removeStop, addRecord, addableRecords, moveStop,
// ⛔ R14 (W50-T14, 2026-09-03) — `requestRoutePinMembership` PARKS HERE, IT IS NOT DELETED.
// R14 retired the pin CLICK and the pin ENTER entries to it, which were its only two callers,
// so without this line `noUnusedLocals` refuses the file. The machinery itself stays whole and
// asserted (`verify_map.py`'s `no-arbitrary-route`, `actual-membership`, `single-stop-door`
// and `visible-confirmation` legs all still hold): what R14 removed is one DOOR, not the room.
// ⚠ `confirmRoutePinMembership` and the confirm dialog are still wired to each other and are
// deliberately left that way; they are simply unreachable until something sets a prompt again.
requestRoutePinMembership,
// W47-T09 / R9 deleted the always-false staleness derivation and, with it, the two retired
// callbacks that were its only real writers. These are what those two left behind: state the
// panel still allocates, plus the host callback that revealed a freshly saved route column.
// ⛔ NONE OF IT IS A NEW RETIREMENT. Each name was already reachable from no click; listing
// it here keeps the state and the prop in place, unread, for whoever puts the panel back.
onRouteFieldCreated, saveTarget, setOpenedRoute, setOpenErr, nextLabel, setNaming,
setSaveBusy, setSaveMsg, setSaveErr,
];
const paint = useCallback(
(p: MapPoint) => {
const k = p.colorKey ?? "";
const category = !colorBuckets ? DEFAULT_PIN
: k === "" ? OVERFLOW : colorBuckets.swatch.get(k) ?? OVERFLOW;
// R23: the bound size measure's sign overrides its category colour.
if (sizeField && typeof p.size === "number" && Number.isFinite(p.size) && p.size < 0) return NEGATIVE_PIN;
return category;
},
[colorBuckets, sizeField]
);
const radius = useCallback(
(p: MapPoint) => {
// `sizeRange` is null without a size pick, so one helper decides every bubble's radius.
return pointRadius(p.size, sizeRange, R_PLAIN, R_MIN, R_MAX, R_NULL);
},
[sizeRange]
);
/**
* Client coords -> the svg's own user-space coords.
*
* ⚠ The maths lives in `clientToUser` (mapProjection) rather than here, and
* that placement is the fix's other half. Wave 8 wrote the conversion inline
* in this .tsx — where the gate's negative controls, every one of which
* mutates the compiled `mapProjection.js`, could not reach it. So the box-
* select legs passed on coordinates handed to them ALREADY in user space, and
* a broken conversion shipped green for four waves. See `clientToUser`.
*/
const localPoint = useCallback(
(clientX: number, clientY: number): Pt => {
if (!svgEl) return { x: 0, y: 0 };
return clientToUser(clientX, clientY, svgEl.getBoundingClientRect(), VIEW_W, VIEW_H);
},
[svgEl]
);
/**
* ⚠ Wheel zoom MUST be a native, non-passive listener. React registers
* `wheel` PASSIVELY at the root, so `e.preventDefault()` inside an `onWheel`
* prop is a silent no-op: the page scrolls out from under the map while you
* zoom, which reads as "the zoom is broken". Nothing in a screenshot shows
* this, and no assertion on the rendered DOM can see it either.
*
* The zoom maths itself is `zoomAt` — the function the gate already proves
* holds the point under the cursor still. Wave 8 re-derived that formula
* inline here, so the tested copy and the shipped copy were two copies.
*/
useEffect(() => {
if (!svgEl) return;
const onWheelNative = (e: WheelEvent) => {
e.preventDefault();
const { x, y } = localPoint(e.clientX, e.clientY);
touchedRef.current = true;
setView((v) => (v ? zoomAt(v, Math.exp(-e.deltaY * 0.0016), x, y, kMin, kMax) : v));
};
svgEl.addEventListener("wheel", onWheelNative, { passive: false });
return () => svgEl.removeEventListener("wheel", onWheelNative);
}, [svgEl, localPoint, kMin, kMax]);
/** Zoom about the viewport centre — the button and keyboard gesture, where
* there is no cursor to hold still. */
const zoomBy = useCallback(
(factor: number) => {
touchedRef.current = true;
setView((v) => (v ? zoomAt(v, factor, VIEW_W / 2, VIEW_H / 2, kMin, kMax) : v));
},
[kMin, kMax]
);
/**
* ⭐⭐ OWNER ITEM 1 (2026-08-23) — TURN THE MAP, 5 DEGREES A CLICK.
*
* Owner: *"we need to add two more button for that navigation. Rotate left and Rotate right.
* Where every click is say rotating the map by 5 degrees."*
*
* ⛔ `touchedRef` IS SET, AND WITHOUT IT THE BEARING WOULD NOT SURVIVE THE NEXT EDIT. The
* seeding effect above re-fits whenever `fit` changes UNLESS the user has touched the camera,
* and `fit` changes on every points change — a cell edit, a filter, an arriving row. Rotating
* without panning would then look like the map springing back to north on its own.
*
* ⚠ ABOUT THE VIEWPORT CENTRE, which is what a compass control means by "turn". `rotateAt`
* is `zoomAt`'s sibling and holds that point still, so the geography under the middle of the
* frame is the geography you were looking at.
*/
const rotateBy = useCallback((deg: number) => {
touchedRef.current = true;
setView((v) => (v ? rotateAt(v, deg, VIEW_W / 2, VIEW_H / 2) : v));
}, []);
/**
* ⛔ AND FIT PUTS NORTH BACK UP. `fit` is a fresh `{k, tx, ty}` with no `rot`, so replacing
* the view with it resets the bearing by construction rather than by a line that could be
* forgotten. It is deliberate rather than incidental: a compass with no way back to north is a
* control with no undo, and `fitView` would otherwise have to frame the bounding box of the
* ROTATED points to keep every pin on screen. "Fit to data" is the reset, and the button's
* title says so.
*/
const doFit = useCallback(() => {
touchedRef.current = false;
setView(fit);
}, [fit]);
const panBy = useCallback((dx: number, dy: number) => {
touchedRef.current = true;
setView((v) => (v ? { ...v, tx: v.tx + dx, ty: v.ty + dy } : v));
}, []);
/**
* ⛔⛔ W46-T28 — THE ONE PLACE A CLICK-DRAWN OUTLINE BECOMES A SAVEABLE BOUNDARY, and the
* reason the owner could not save. Before this, that conversion lived ONLY in the `Enter`
* branch of `onFrameKeyDown`, which fires only while `.cg-map-frame` itself holds focus. The
* shape a user draws by clicking is drawn on the map and then NAMED in the panel, so by the
* time they are done the focus is in a text input and `Enter` never reaches the map. The
* panel's only draft control was "Stop drawing", which DISCARDS the points. So the outline
* never reached `drawnZoneGeometry`, the Save button stayed `disabled`, and a disabled button
* cannot explain itself: the refusal was real and completely silent.
*
* ⚠ It returns the geometry as well as storing it, because a caller in the same tick cannot
* read the state it just set. `null` means it refused, and it has already said why in
* `zoneErr` — a caller must not then report a second, vaguer reason over the top.
*/
const finishZoneDraft = useCallback((): ZoneGeometry | null => {
const draft = zoneKeyboardDraft;
if (!draft || !view) return null;
let geometry: ZoneGeometry;
if (draft.shape === "polygon") {
if (draft.points.length < 3) {
setZoneErr("Add at least three vertices, then finish the shape.");
return null;
}
const coordinates = draft.points
.map((screen) => unproject(fromScreen(screen, view)))
.map(({ lon, lat }) => [lon, lat]);
geometry = { type: "Polygon", coordinates: [[...coordinates, coordinates[0]]] };
} else {
if (!draft.center) {
setZoneErr("Place the circle center first, then its edge.");
return null;
}
// ⛔ W46-T28 — A CIRCLE WITH NO EDGE CLICK IS A ONE METRE ZONE. `cursor` still sits on
// `center` until the second click, and `Math.max(1, 0)` below would happily mint a Zone
// too small to see and holding no records: instruction 16's own complaint, saved. The
// panel button puts that one click away, so the refusal is stated rather than shipped.
if (draft.center.x === draft.cursor.x && draft.center.y === draft.cursor.y) {
setZoneErr("Click the circle edge to give the Zone a size, then finish the shape.");
return null;
}
const center = unproject(fromScreen(draft.center, view));
const edge = unproject(fromScreen(draft.cursor, view));
geometry = {
type: "Circle",
center: [center.lon, center.lat],
radiusMeters: Math.max(1, Math.round(haversineKm(
{ lat: center.lat, lon: center.lon }, { lat: edge.lat, lon: edge.lon }
) * 1000)),
};
}
setDrawnZoneGeometry(geometry);
setZoneKeyboardDraft(null);
setZoneErr(null);
return geometry;
}, [zoneKeyboardDraft, view]);
/** The camera had NO keyboard path at all before wave 9 — scroll wheel only,
* which is unusable without a mouse and unreachable for anyone driving the
* page from the keyboard. */
const onFrameKeyDown = useCallback(
(e: ReactKeyboardEvent<HTMLDivElement>) => {
if (zoneKeyboardDraft) {
const keyboardStep = e.shiftKey ? 24 : 8;
const moved = { ...zoneKeyboardDraft.cursor };
if (e.key === "ArrowLeft") moved.x = Math.max(8, moved.x - keyboardStep);
else if (e.key === "ArrowRight") moved.x = Math.min(VIEW_W - 8, moved.x + keyboardStep);
else if (e.key === "ArrowUp") moved.y = Math.max(8, moved.y - keyboardStep);
else if (e.key === "ArrowDown") moved.y = Math.min(VIEW_H - 8, moved.y + keyboardStep);
else if (e.key === " ") {
if (zoneKeyboardDraft.shape === "polygon")
setZoneKeyboardDraft({ ...zoneKeyboardDraft, points: [...zoneKeyboardDraft.points, zoneKeyboardDraft.cursor] });
else if (!zoneKeyboardDraft.center)
setZoneKeyboardDraft({ ...zoneKeyboardDraft, center: zoneKeyboardDraft.cursor });
setZoneErr(null);
e.preventDefault();
return;
} else if (e.key === "Enter") {
if (!view) return;
// W46-T28 — the same commit the panel's "Finish shape" button calls. Two controls,
// one conversion: a second copy is how the two endings drift apart.
finishZoneDraft();
e.preventDefault();
return;
} else if (e.key === "Escape") {
setZoneKeyboardDraft(null);
setZoneErr(null);
e.preventDefault();
return;
} else return;
setZoneKeyboardDraft({ ...zoneKeyboardDraft, cursor: moved });
e.preventDefault();
return;
}
const step = e.shiftKey ? 160 : 60;
switch (e.key) {
case "ArrowLeft": panBy(step, 0); break;
case "ArrowRight": panBy(-step, 0); break;
case "ArrowUp": panBy(0, step); break;
case "ArrowDown": panBy(0, -step); break;
case "+": case "=": zoomBy(1.6); break;
case "-": case "_": zoomBy(1 / 1.6); break;
// ⭐ ITEM 1 — the bracket keys turn the map, the same 5 degrees the buttons do. Not the
// arrows: those are the pan, and shift-arrow is already the bigger pan step.
case "[": rotateBy(-ROTATE_STEP); break;
case "]": rotateBy(ROTATE_STEP); break;
case "0": doFit(); break;
// Esc abandons a marquee mid-drag. It falls THROUGH when there is no
// drag, so it keeps closing whatever the host has open.
case "Escape": if (!drag) return; setDrag(null); break;
default: return;
}
e.preventDefault();
},
[panBy, zoomBy, rotateBy, doFit, drag, view, zoneKeyboardDraft, finishZoneDraft]
);
const startKeyboardZoneDrawing = useCallback(() => {
setZoneKeyboardDraft({
shape: zoneDrawShape,
cursor: { x: VIEW_W / 2, y: VIEW_H / 2 },
points: [],
});
setZoneErr(null);
requestAnimationFrame(() => mapFrameRef.current?.focus());
}, [zoneDrawShape]);
/** W46-T17 — A CLICK ON THE MAP IS THE PRIMARY WAY TO DRAW A ZONE. The arrow
* keys and Space in `onFrameKeyDown` still work and are still the only path
* for someone with no pointer, so that handler stays; what changed is that
* nobody has to be TOLD about it to draw a shape. The cursor moves to the
* click as well as the point being kept, so the rubber band that follows the
* pointer starts from where the user just clicked. */
const addZoneDraftVertex = useCallback((at: Pt) => {
setZoneKeyboardDraft((draft) => {
if (!draft) return draft;
if (draft.shape === "polygon")
return { ...draft, cursor: at, points: [...draft.points, at] };
if (!draft.center) return { ...draft, cursor: at, center: at };
return { ...draft, cursor: at };
});
setZoneErr(null);
}, []);
const onPointerDown = useCallback(
(e: ReactPointerEvent<SVGSVGElement>) => {
if (e.button !== 0 || !view) return;
const { x, y } = localPoint(e.clientX, e.clientY);
movedRef.current = false;
// ⛔⛔ THE CAPTURE IS TAKEN LAZILY, IN `onPointerMove`, AND MOVING IT THERE IS THE WHOLE
// FIX FOR W38-T09 (found by wave-38 QA on the deployed build). This line used to read
// `e.currentTarget.setPointerCapture(e.pointerId)`, unconditionally, on every pointerdown
// anywhere in the SVG -- including on a pin. Pointer capture retargets the REST of the
// gesture to the capture element, so `pointerup`, `mouseup` and the synthesised `click`
// all landed on the `<svg>` and a pin's own `onClick` NEVER RAN. Measured live:
// pointerdown -> cg-map-pin mousedown -> cg-map-pin
// pointerup -> cg-map-svg mouseup -> cg-map-svg click -> cg-map-svg
// ⚠ RELEASING ON `pointerup` DOES NOT SAVE IT, and that was the tempting wrong fix: the
// release below already ran and the click was still retargeted. Reproduced in a 20-line
// isolation page with zero app code, IDENTICALLY in headed and headless Chromium, so it is
// browser behaviour rather than a test-harness artifact.
// ⭐ THE PIN'S HANDLER WAS ALWAYS CORRECT. `onOpen`, `pinSelect`, the drawer and the cohort
// path were all provably healthy (keyboard Enter opened the record; shift-drag, which the
// SVG handles itself and so is immune to the retargeting, selected 2,381 pins). Only
// pointer DELIVERY to a pin was broken -- and it had been since wave 8, thirty waves before
// the ticket that wired this handler. `git log -S "setPointerCapture"` returns one commit.
downRef.current = { id: e.pointerId, cx: e.clientX, cy: e.clientY };
// Shift (or Ctrl/Cmd) turns the drag into a SELECTION rectangle; a plain
// drag pans. Both gestures are on the same button because a map that
// needs a mode toggle to select is a map people never select on.
if (e.shiftKey || e.ctrlKey || e.metaKey)
setDrag(lassoTool ? { kind: "lasso", pts: [{ x, y }] } : { kind: "rect", x0: x, y0: y, x1: x, y1: y });
else panRef.current = { x, y, tx: view.tx, ty: view.ty };
},
[view, localPoint, lassoTool]
);
const onPointerMove = useCallback(
(e: ReactPointerEvent<SVGSVGElement>) => {
const { x, y } = localPoint(e.clientX, e.clientY);
// ⭐ W46-T17 — the in-progress outline TRACKS THE POINTER while drawing is
// armed. Without this the first click leaves `points` and `cursor` on the
// same coordinate, so the polyline has zero length and the shape reads as
// invisible all over again. A pan or a marquee owns the pointer instead.
if (zoneKeyboardDraft && !drag && !zoneMove && !zoneVertex && !panRef.current)
setZoneKeyboardDraft((draft) =>
draft && (draft.cursor.x !== x || draft.cursor.y !== y)
? { ...draft, cursor: { x, y } }
: draft);
// ⭐ W46-T28 — ONE VERTEX FOLLOWS THE POINTER. It sits above the whole-boundary branch
// because a handle is a smaller, more specific target sitting ON the boundary: without
// this order, grabbing a corner would translate the entire Zone instead of reshaping it.
// ⚠ Every move recomputes from `zoneVertex.geometry`, the shape as it was when the drag
// STARTED, so the answer is a function of where the pointer is now and not of how it got
// there. There is no travel threshold here on purpose: a corner nudged two pixels is a
// deliberate adjustment, where the same two pixels on a whole boundary is a mis-click.
if (zoneVertex && view) {
movedRef.current = true;
const at = unproject(fromScreen({ x, y }, view));
setZoneGeometryDraft({
id: zoneVertex.zone.id,
geometry: moveZoneVertex(zoneVertex.geometry, zoneVertex, { lon: at.lon, lat: at.lat }),
});
return;
}
if (zoneMove && view) {
if (Math.abs(x - zoneMove.start.x) + Math.abs(y - zoneMove.start.y) <= 2) return;
movedRef.current = true;
const origin = unproject(fromScreen(zoneMove.start, view));
const current = unproject(fromScreen({ x, y }, view));
setZoneGeometryDraft({
id: zoneMove.zone.id,
geometry: translateZoneGeometry(zoneMove.geometry, {
lon: current.lon - origin.lon,
lat: current.lat - origin.lat,
}),
});
return;
}
// ⭐⭐ THE LAZY CAPTURE (W38-T09's fix). A gesture only becomes a drag once it has TRAVELLED,
// so the capture is taken here rather than on pointerdown. A zero-movement click therefore
// never captures and reaches the pin it was aimed at; a pan or a marquee captures the
// instant it stops being a click, which is what keeps the pointer inside this handler when
// the cursor leaves the SVG mid-drag. Both directions proven in isolation before this
// landed: a plain click fires the pin's own `onClick`, and a real drag still logs the
// capture and retargets exactly as it did before.
// ⚠ THE THRESHOLD IS IN CLIENT PIXELS, deliberately unlike the two below it. Those compare
// LOCAL (viewBox) coordinates to decide whether a gesture counts as travel for selection;
// this one asks whether the BROWSER should stop delivering events to what is under the
// cursor, which is a screen-space question at every zoom.
const dn = downRef.current;
if (dn && dn.id === e.pointerId && !e.currentTarget.hasPointerCapture(e.pointerId)
&& Math.abs(e.clientX - dn.cx) + Math.abs(e.clientY - dn.cy) > 3)
e.currentTarget.setPointerCapture(e.pointerId);
if (drag) {
// ⚠ W37-T30: this used to set `movedRef` UNCONDITIONALLY, and that is what swallowed a
// shift-CLICK. Holding shift starts a marquee on pointerdown, so a shift-click is a
// marquee that never travels; one stray pointermove then marked the gesture "moved" and
// the pin's onClick returned early. Measured on the render probe: the click fired, the
// handler ran, and the selection did not change.
// The threshold is the pan branch's own rule, applied to the same question, and a marquee
// that really was drawn clears it long before `drawn` (> 3 px) lets it select anything.
const from = drag.kind === "rect" ? { x: drag.x0, y: drag.y0 } : drag.pts[0];
if (Math.abs(x - from.x) + Math.abs(y - from.y) > 2) movedRef.current = true;
setDrag((d) => {
if (!d) return d;
if (d.kind === "rect") return { ...d, x1: x, y1: y };
// `pointermove` fires far faster than a loop needs vertices, so a slow
// hand tracing 200 px would otherwise build a thousand-point polygon
// that every pin is then tested against on every frame. Drop a sample
// that has not travelled ~2 px — the viewBox is fixed relative to the
// screen, so this threshold means the same thing at every zoom.
const last = d.pts[d.pts.length - 1];
if (Math.abs(x - last.x) + Math.abs(y - last.y) < 2) return d;
return { kind: "lasso", pts: [...d.pts, { x, y }] };
});
return;
}
const pan = panRef.current;
if (!pan) return;
if (Math.abs(x - pan.x) + Math.abs(y - pan.y) > 2) movedRef.current = true;
touchedRef.current = true;
setView((v) => (v ? { ...v, tx: pan.tx + (x - pan.x), ty: pan.ty + (y - pan.y) } : v));
},
[drag, localPoint, zoneMove, zoneVertex, view, zoneKeyboardDraft]
);
/**
* Table's opt-in selects on click and opens on double-click. The default surface keeps R10.
*
* ⛔⛔ W38-T09 (ruling R10) — A SINGLE CLICK ON A PIN OPENS THE RECORD. This SUPERSEDES the
* single-click-SELECTS half of W37-T30 (D-135), which was built deliberately one wave ago. The
* paragraph W37-T30 wrote is kept below rather than deleted, because its argument is still the
* argument that has to be traded against, and a reader who only sees the winner cannot tell a
* decision from an accident.
*
* ⭐ WHAT W37-T30 ARGUED, AND IT WAS NOT WRONG AT THE TIME. Owner item 19 moved the whole
* product off click-to-open: in the grid "the single click that used to open a record now
* highlights it", and opening moved to a deliberate affordance (CustomerGrid.tsx, the
* hover-only Expand). The map went on firing `onOpen` on a bare click, so the one view built
* around choosing a SET of records was the one view where choosing was impossible, and the
* "N selected" bar, "Add to cohort" and the route planner all sat behind a gesture the map did
* not have.
*
* ⭐ WHAT R10 TRADES IT FOR. A pin is not a row. A row lives in a sheet where the cursor already
* means "this cell", so click-to-highlight costs a user nothing; a pin is a target you had to
* AIM at, and the thing you wanted after aiming is the record. Every set-building gesture the
* map grew for item 19 SURVIVES, and not one of them is the plain click: shift-drag and the
* lasso build a cohort, shift-alt-drag extends one, a modifier click toggles a single pin in or
* out, and the keyboard keeps Space for select and Enter for open.
*
* ⚠ SO `pinSelect`'s NON-ADDITIVE BRANCH IS NOW KEYBOARD-ONLY, not dead. A plain Space still
* replaces the selection with the focused pin; a pointer no longer has that gesture at all.
* Deleting the branch as unreachable would take the keyboard's only "just this one" with it.
*
* ⛔ AND `movedRef` IS NOW LOAD-BEARING FOR A WORSE REASON THAN THE ONE IT WAS WRITTEN FOR.
* Before R10, a pan or a box-drag that happened to finish on top of a pin mis-SELECTED it.
* After R10 the same stray gesture would OPEN a drawer over the map. Whoever next reads that
* early return as noise should read this sentence instead: its failure mode got louder.
*
* Toggle rather than plain accumulate is done here rather than asked for from the host, because
* `onSelectPids` offers "replace" and "add" only, and a second shift-click that cannot undo the
* first is a trap on a map where pins overlap.
*/
const pinSelect = useCallback(
(pid: number, additive: boolean) => {
if (!additive) {
onSelectPids([pid], "replace");
return;
}
if (selectedPids.has(pid)) {
onSelectPids([...selectedPids].filter((x) => x !== pid), "replace");
return;
}
onSelectPids([pid], "add");
},
[onSelectPids, selectedPids]
);
/**
* ⭐⭐ R14 (W50-T14) REWROTE THREE OF THIS LABEL'S FOUR BRANCHES, because they described a
* gesture the pin no longer has. Until 2026-09-03 a plain click with the Routes panel open
* asked to add or remove a stop instead of opening the record, and this label promised exactly
* that. R14 retired the shortcut, so `openHint` is now UNCONDITIONAL and leads every branch:
* click or Enter opens the record whatever else is on screen.
*
* ⛔ NO BRANCH MAY PROMISE THE MEMBERSHIP PROMPT AGAIN. What the Route-mode branches still say
* is a FACT about the active route (no route open, read-only, already a stop or not) plus where
* the two visible membership doors are; none of them claims the pin itself edits the route.
* Policed by `verify_ui.py::pin_label_states_the_gesture` and `verify_map.py`'s `truthful-copy`.
*/
const pinAriaLabel = useCallback((point: MapPoint) => {
const title = point.title || "Untitled record";
if (pinClickSelects) {
const selection = selectedPids.has(point.pid) ? "Selected." : "Not selected.";
return `${title}. ${selection} Click a pin to select it. Shift-click to add or remove it. Double-click or press Enter to open the record. Press Space to select.`;
}
const openHint = "Click or press Enter to open the record.";
const selectionHint = "Shift-click or press Space to select.";
if (!routePanelOpen)
return `${title}. ${openHint} ${selectionHint}`;
if (!activeNamedRoute)
return `${title}. ${openHint} No route is open, so route stops cannot be changed. Open a route first. ${selectionHint}`;
if (!activeNamedRoute.permission.canEdit)
return `${title}. ${openHint} ${activeNamedRoute.name} is read-only, so its stops cannot be changed. ${selectionHint}`;
const action = activeNamedRoute.visibleStopIds.includes(point.pid) ? "remove" : "add";
return `${title}. ${openHint} ${action === "remove" ? `A stop on ${activeNamedRoute.name}. Use the route panel to remove it.` : `Not a stop on ${activeNamedRoute.name}. Use the route panel to add it.`} ${selectionHint}`;
}, [activeNamedRoute, routePanelOpen, pinClickSelects, selectedPids]);
const onPointerUp = useCallback(
(e: ReactPointerEvent<SVGSVGElement>) => {
// W46-T28 — the reshape lands the same way a boundary move does: the draft geometry the
// pointer built is what gets persisted, and the draft is cleared either way so a failed
// save cannot leave the map showing a shape the server never accepted.
if (zoneVertex) {
const geometry = zoneGeometryDraft?.id === zoneVertex.zone.id
? zoneGeometryDraft.geometry
: null;
setZoneVertex(null);
setZoneGeometryDraft(null);
if (geometry) void persistZoneGeometry(zoneVertex.zone, geometry);
if (e.currentTarget.hasPointerCapture(e.pointerId))
e.currentTarget.releasePointerCapture(e.pointerId);
return;
}
if (zoneMove) {
const geometry = zoneGeometryDraft?.id === zoneMove.zone.id
? zoneGeometryDraft.geometry
: null;
setZoneMove(null);
setZoneGeometryDraft(null);
if (geometry) void persistZoneGeometry(zoneMove.zone, geometry);
if (e.currentTarget.hasPointerCapture(e.pointerId))
e.currentTarget.releasePointerCapture(e.pointerId);
return;
}
// ⭐ W46-T17 — a click that did not travel places a vertex. It sits above
// the marquee branch so an armed drawing owns the plain click, and below
// `zoneMove` so dragging an existing Zone still wins. `movedRef` is the
// same "this was a drag, not a click" rule the pins use, so a pan while
// armed still pans and drops nothing.
// ⛔ `zoneKeyboardDraft` IS IN THIS CALLBACK'S DEPENDENCY ARRAY and must
// stay there: without it, arming the tool changes no dependency, the
// memoized closure keeps reading `null`, and the first clicks after
// arming silently do nothing until some other dependency happens to
// change. That intermittency is exactly what the bug reported.
if (zoneKeyboardDraft && view && !drag && !movedRef.current) {
addZoneDraftVertex(localPoint(e.clientX, e.clientY));
panRef.current = null;
if (e.currentTarget.hasPointerCapture(e.pointerId))
e.currentTarget.releasePointerCapture(e.pointerId);
return;
}
if (drag && view) {
// A gesture smaller than a few px is a mis-click, not a selection —
// clearing the user's set on a stray shift-click would be its own bug.
// ONE rule for both shapes, measured on the lasso's own bounds; a loop
// also needs three points before it is a polygon at all.
const b =
drag.kind === "rect"
? normRect(drag.x0, drag.y0, drag.x1, drag.y1)
: pathBounds(drag.pts);
const drawn = b.x1 - b.x0 > 3 && b.y1 - b.y0 > 3 && (drag.kind === "rect" || drag.pts.length >= 3);
if (drawn) {
const hits: number[] = [];
for (const p of points) {
const s = toScreen(p.p, view);
const held =
drag.kind === "rect"
? s.x >= b.x0 && s.x <= b.x1 && s.y >= b.y0 && s.y <= b.y1
: pointInPolygon(s, drag.pts);
if (held) hits.push(p.pid);
}
onSelectPids(hits, e.altKey ? "add" : "replace");
// A selection gesture is also a deliberate geographic outline. Keep its exact
// lon/lat geometry ready for C3's Save Zone action; the membership snapshot above
// remains the answer to "which current records were in it".
if (zoneEditorOpen && zoneDrawShape === "circle") {
const centerScreen = { x: (b.x0 + b.x1) / 2, y: (b.y0 + b.y1) / 2 };
const edgeScreen = { x: b.x1, y: centerScreen.y };
const center = unproject(fromScreen(centerScreen, view));
const edge = unproject(fromScreen(edgeScreen, view));
setDrawnZoneGeometry({
type: "Circle",
center: [center.lon, center.lat],
radiusMeters: Math.max(1, Math.round(haversineKm(
{ lat: center.lat, lon: center.lon }, { lat: edge.lat, lon: edge.lon }
) * 1000)),
});
} else {
const outline = drag.kind === "rect"
? [
{ x: b.x0, y: b.y0 }, { x: b.x1, y: b.y0 },
{ x: b.x1, y: b.y1 }, { x: b.x0, y: b.y1 },
]
: drag.pts;
const coordinates = outline
.map((screen) => unproject(fromScreen(screen, view)))
.map(({ lon, lat }) => [lon, lat]);
if (coordinates.length >= 3)
setDrawnZoneGeometry({ type: "Polygon", coordinates: [[...coordinates, coordinates[0]]] });
}
}
setDrag(null);
}
panRef.current = null;
if (e.currentTarget.hasPointerCapture(e.pointerId))
e.currentTarget.releasePointerCapture(e.pointerId);
},
[drag, view, points, onSelectPids, zoneMove, zoneVertex, zoneGeometryDraft, persistZoneGeometry,
zoneDrawShape, zoneEditorOpen, zoneKeyboardDraft, addZoneDraftVertex, localPoint]
);
/**
* ⭐⭐ W37-T37 — THE LOOKUP CONTROL IS BUILT ONCE AND RENDERED IN TWO PLACES, and the second
* place is the whole reason this is a variable rather than inline JSX.
*
* ⛔ IT SHIPPED UNREACHABLE THE FIRST TIME AND ONLY LOOKING FOUND IT. The control lived in the
* map bar; the bar lives after the `!view || !fit` early return below; and a database whose
* records have addresses and no coordinates has NO POINTS, so it takes that return. The feature
* was therefore invisible in precisely the situation it exists for, and visible only once you no
* longer needed it. Every gate was green: the door scan found the control, `tsc` was clean, and
* the component rendered. [[reachable-is-not-the-same-as-built]] is this exact shape.
*/
const geoControl = coordField?.geocode?.addressField && (onGeocoded || geocodeSessionOnly) ? (
<span className="cg-map-geo">
{geo.busy ? (
<>
<span className="cg-map-geo-run">
Looking up addresses: <strong>{geo.done.toLocaleString()}</strong> of{" "}
{geo.total.toLocaleString()}
</span>
{/* ⚠ The rate limit is a LICENCE TERM here, not a performance excuse, so the surface
says why it is slow instead of letting it read as a hang. */}
<span className="cg-map-geo-note">
about one address a second, which is what the free map service allows
</span>
</>
) : geocodable.length > 0 ? (
<button
type="button"
className="cg-btn cg-map-geo-cta"
onClick={() => void runGeocode()}
title={geocodeSessionOnly
? `Look up ${geocodable.length.toLocaleString()} address${
geocodable.length === 1 ? "" : "es"
} and place the records on this map. Takes ${geoEstimate}.`
: `Look up ${geocodable.length.toLocaleString()} address${
geocodable.length === 1 ? "" : "es"
} and fill ${coordField.label}. Takes ${geoEstimate}.`}
>
Look up {geocodable.length.toLocaleString()} address
{geocodable.length === 1 ? "" : "es"} ({geoEstimate})
</button>
) : null}
{!geo.busy && geo.total > 0 && (
<span className="cg-map-geo-note">
Located {geo.found.toLocaleString()} of {geo.total.toLocaleString()}
{geo.found < geo.total && ". The rest had no address on file or could not be matched."}
{geocodeSessionOnly && geo.found > 0 && " These locations stay on this map for this session."}
</span>
)}
{geo.error && <span className="cg-cal-nodate">{geo.error}</span>}
</span>
) : null;
const renderHeader = (barActions?: ReactNode) => {
// The Routing frame carries the App mark and the Odoo mark; a plain map bar carries neither.
const actions = routeApplication && applicationName
? <><AppFrameMarks mark="route" connector="odoo" />{barActions}</> : barActions;
return routeApplication && applicationName
? <AppFrame appName={applicationName} actions={actions} />
: <div className="cg-map-bar">{actions}</div>;
};
if (!view || !fit) {
const empty = (
<div className="cg-mode-empty">
{geocodeSessionOnly
? "No records with a location to map yet."
: "No records with a location to map yet. Set latitude and longitude fields in View schema to plot records."}
{/* The way OUT of the empty state, offered from inside it. Selecting records and looking
up their addresses is the one action that turns this screen into a map. */}
{geoControl && <div className="cg-map-geo-empty">{geoControl}</div>}
{geoControl && geocodable.length === 0 && selectedPids.size === 0 && (
<div className="cg-map-geo-note">
Select the records you want placed, then look up their addresses.
</div>
)}
</div>
);
return routeApplication && applicationName
? <div className="cg-mapview cg-app-route-surface">
{renderHeader(routingFilters && <div className="cg-routing-filter-bar">{routingFilters}</div>)}
{empty}
</div>
: empty;
}
const hovered = hoverPid != null ? points.find((p) => p.pid === hoverPid) : undefined;
const rect = drag?.kind === "rect" ? normRect(drag.x0, drag.y0, drag.x1, drag.y1) : null;
const lassoPts = drag?.kind === "lasso" && drag.pts.length > 1 ? drag.pts : null;
// ⭐ ITEM 1 — `rotate` sits BETWEEN the translate and the scale, which is the transform
// `toScreen` computes and `fromScreen` inverts (`t + R . k . p`, read right to left). Any other
// order paints a map whose pins, hit tests and hover cards disagree about where things are.
const tf =
`translate(${view.tx.toFixed(2)} ${view.ty.toFixed(2)}) ` +
`rotate(${(view.rot ?? 0).toFixed(2)}) scale(${view.k.toFixed(6)})`;
// Strokes live in the transformed group, so they are pre-divided by the zoom.
// ⚠ This is the map's ONE stroke mechanism — see the note over `hairline` in
// mapProjection.ts. No `.cg-map*` rule may add `vector-effect:
// non-scaling-stroke` on top; that double-cancel is the wave-9 blur bug and
// `scalingConflicts()` gates the stylesheet against it.
const hair = (w: number) => hairline(w, view.k);
/**
* ⛔ W47-T03 — THE UNSAVED SHAPE AND THE CONTROLS THAT OWN IT SHARE ONE CONDITION, and it is
* this literal expression rather than `zoneEditorOpen` alone because the Zone editor aside is
* gated on all three. `drawnZoneGeometry` SURVIVES "Back to Zones" and a switch to the Routes
* tab, so painting on `zoneEditorOpen` alone would leave a dashed boundary on the map with no
* Save zone and no Discard anywhere on screen: an unsaved state nobody can resolve, which is
* instruction 20's confusion wearing the opposite mask.
*
* ⛔ AND THE RENDER SITE ADDS `!zoneKeyboardDraft` ON TOP OF THIS, exactly as the panel row
* does, because `startKeyboardZoneDrawing` does NOT clear `drawnZoneGeometry` — the clears live
* in `beginNewZone`, `beginEditZone` and `saveZone` only. Finish a shape, then choose "Draw by
* clicking" again, and the panel row hides itself while the dashed boundary would have stayed
* painted with no control anywhere: the same orphan through the other door. Both sides must
* read `zoneEditorPanelOpen && !zoneKeyboardDraft && <geometry>` or they drift apart again.
*
* ⛔ W51-T28 MOVED THE DECLARATION UP, IT DID NOT ADD A SECOND ONE. `useEscapeClose` has to
* register above the `!view || !fit` early return, so `zoneEditorPanelOpen` and its chooser
* sibling now live beside those hooks. Declaring the expression twice is exactly the drift this
* comment warns about, so there is one const and both the Escape claim and the render sites
* read it.
*/
const gratOpacity = graticuleOpacity(view.k);
// I18 — the Google hand-off, and W37-T35 changed what it is FOR.
// It used to be the answer to "I need to see the actual street", because the
// vendored basemap stopped at roughly metro scale. Real tiles go to street
// level themselves, so this link is no longer an apology for a missing
// capability: it is a hand-off to a tool that does routing, transit and
// street imagery, which this view does not.
// ⚠ The old note here read "Nothing is fetched and no coordinate leaves the
// page unless the user deliberately clicks". The second half still holds and
// is the part that matters: a tile request carries a z/x/y grid square and
// never a record. The first half does not, and is corrected in the header.
const centre = unproject(fromScreen({ x: VIEW_W / 2, y: VIEW_H / 2 }, view));
const areaUrl = googleMapsUrl(centre.lat, centre.lon, googleZoomForK(view.k));
const sizeDomain = sizeRange && !sizeRange.none && sizeRange.max > sizeRange.min
? magnitudeDomain(sizeRange.min, sizeRange.max)
: null;
const sizeLegend = sizeDomain ? [sizeDomain.lo, (sizeDomain.lo + sizeDomain.hi) / 2, sizeDomain.hi] : null;
const navigatorTabs = (
<div className="cg-map-navigator-tabs" role="tablist" aria-label="Map assets">
<button type="button" role="tab" aria-selected={mapNavigator === "routes"}
onClick={() => { setZoneNavigatorOpen(false); setZoneEditorOpen(false); }}>
Routes
</button>
<button type="button" role="tab" aria-selected={mapNavigator === "zones"}
onClick={() => { setZoneNavigatorOpen(true); setActiveRouteId(null); }}>
Zones
</button>
</div>
);
return (
<div
className={"cg-mapview" + (routeApplication ? " cg-app-route-surface" : "")}
/* Both custom properties, from ONE number. The unsaved shape stays exactly half, which is
the invariant `map-panels.css` says has already survived three retunes. */
style={{
"--lp-zone-fill": String(zoneFillOpacity),
"--lp-zone-fill-unsaved": String(zoneFillOpacity / 2),
} as React.CSSProperties}
>
{renderHeader(<>
{routeApplication && routingFilters && <div className="cg-routing-filter-bar">{routingFilters}</div>}
{/* The count is "N of M", never a bare N: a pin can only be drawn for a
row the host geocoded, and a lone "1,402" silently redefines the
toolbar's 1,550 ([[no-unverifiable-aggregates]]). */}
<span className="cg-cal-note cg-map-count">
<span><strong>{points.length.toLocaleString()}</strong> of {mapRows.length.toLocaleString()} mapped</span>
</span>
{routeSelectionWarning && !routePanelOpen && (
<aside className="cg-route-popover" aria-label="Route selection notice">
<span className="cg-w44-route-warning" role="status">{routeSelectionWarning}</span>
</aside>
)}
{geoControl}
{/* Every gesture the map has, named. `alt` (add to the selection rather
than replace it, onPointerUp) shipped in wave 8 and was disclosed
NOWHERE, so "select these as well" was a feature only the source
knew about. It needs shift too — alt alone still pans. */}
<span className="cg-map-hint">
{pinClickSelects ? <>
Click a pin to select · shift-click to add or remove · double-click or press Enter to open
· scroll to zoom · drag to pan · {lassoTool ? "shift-drag to lasso" : "shift-drag to select"}
{" "}· shift-alt-drag to extend the selection
</> : routeApplication ? "Click to open · scroll to zoom" : <>
Scroll to zoom · drag to pan · {lassoTool ? "shift-drag to lasso" : "shift-drag to select"}{" "}
· shift-alt-drag to extend the selection · click or press Enter on a pin to open the
record · shift-click or press Space on a pin to add or remove it from the selection
</>}
</span>
</>)}
{/* ⭐⭐ W51-T32 - THE MAP AND THE 380 px ROUTE COLUMN SHARE ONE FLEX ROW, WHICH IS WHY
THE THREE NAVIGATOR PANELS MOVED OUT OF THE TOOLBAR. They used to be toolbar children
floated over the canvas, and the mechanism that made that unfixable is document order
inside an SVG: a pin painted under the floating column could not receive a pointer
event, and no stacking value on either side changes that. Wave 50's QA measured 427 px
of live map covered and a coordinate click on a covered pin opening nothing at all.
The repair is LAYOUT: the canvas and the column are siblings in a row, the canvas
yields the width the column takes, and every pin is back in the open.
⚠ The row also RETIRES four competing declarations in three other stylesheets, all of
them keyed on the toolbar-child path, so they simply stop matching rather than needing
an override this ticket is not allowed to write.
⚠ The frame block below deliberately keeps its former indentation. Re-indenting 820
lines would bury a structural move in a whitespace diff and would rewrite two
multi-line template literals inside it. */}
<div className="cg-map-stage">
{/* ⭐⭐ W41-T48 — OPENING A RECORD FOLDS THE RAIL, and R14 (2026-09-03) removed the
`!routePanelOpen` gate from this frame's `onPointerDown`. That gate existed only because
a pin click in Route mode did not open a record; it now does, on every pin, so the map
must fold the rail in Route mode exactly as it does outside it. */}
<div
ref={mapFrameRef}
className="cg-map-frame"
tabIndex={0}
role="group"
aria-label={zoneKeyboardDraft
? `Zone ${zoneKeyboardDraft.shape} drawing canvas. Click the map to add points, then press Enter to finish.`
: "Map canvas. Arrow keys pan, plus and minus zoom, square brackets rotate, zero fits to data and faces north."}
onKeyDown={onFrameKeyDown}
// Inline App detail preserves the rail. Data openings keep their minimization event.
onPointerDown={() => { if (!routeApplication) signal(NAV_MINIMIZE_EVENT); }}
>
<svg
ref={setSvgEl}
viewBox={`0 0 ${VIEW_W} ${VIEW_H}`}
preserveAspectRatio="xMidYMid meet"
className={"cg-map-svg" + (drag ? " is-selecting" : "")}
role="img"
aria-label={`Map of ${points.length.toLocaleString()} records`}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={onPointerUp}
>
<rect className="cg-map-water" x={0} y={0} width={VIEW_W} height={VIEW_H} />
<g transform={tf}>
{/* --- W37-T35: the raster basemap, UNDER everything, inside the same transform.
⛔ AND THE VENDORED GEOMETRY BELOW IS HIDDEN WHILE IT PAINTS. Drawing a
generalised coastline on top of a real one does not add detail, it adds a SECOND
coastline a few pixels off the first, plus a graticule fighting the tiles' own
grid. Two basemaps disagreeing about where Florida is looks like a rendering bug
to everyone except the person who knows there are two of them. --- */}
{tileLayer && (
<g className="cg-map-tiles" aria-hidden="true">
{/* Painted under the images so a tile still in flight shows map-coloured ground
rather than the page behind it, which reads as a hole rather than as loading. */}
<rect
className="cg-map-tilebed"
x={tileLayer.bed.x}
y={tileLayer.bed.y}
width={tileLayer.bed.w}
height={tileLayer.bed.h}
/>
{tileLayer.items.map((t) => (
<image
key={t.key}
className="cg-map-tile"
href={t.href}
x={t.x}
y={t.y}
width={t.s}
height={t.s}
preserveAspectRatio="none"
// The fallback's trigger. A tile 404 at the edge of coverage is ordinary, so
// this counts rather than switches; TILE_FAIL_LIMIT decides.
onError={() => setTileFails((f) => f + 1)}
/>
))}
</g>
)}
{/* Graticule every 10 degrees. It earns its place zoomed OUT, where
it is the only thing giving scale; once the real state borders
arrive it would be a second line system fighting the first, so it
fades away before they take over. Skipped entirely at zero
opacity — ~36 invisible lines are still 36 nodes to lay out. */}
{!tileLayer && gratOpacity > 0.01 && (
<g className="cg-map-grat" strokeWidth={hair(0.6)} opacity={gratOpacity}>
{Array.from({ length: 17 }, (_, i) => {
const y = project(0, -80 + i * 10).y;
return <line key={`p${i}`} x1={0} y1={y} x2={WORLD} y2={y} />;
})}
{Array.from({ length: 19 }, (_, i) => {
const x = project(-180 + i * 20, 0).x;
return <line key={`m${i}`} x1={x} y1={0} x2={x} y2={WORLD} />;
})}
</g>
)}
{/* One path, every US state ring. Filled AND stroked, so interior
state borders come free from the same geometry — no second pass
and no chance of the borders disagreeing with the coastline.
0.9 rather than wave 8's 1.1: that weight was tuned for a single
lone coastline, and it reads heavy once ~169 rings share it. */}
{!tileLayer && (
<>
<path className="cg-map-land" d={LAND_PATH} strokeWidth={hair(0.9)} />
{LAKE_PATHS.map((d, i) => (
<path key={i} className="cg-map-lake" d={d} strokeWidth={hair(0.8)} />
))}
</>
)}
{/* ⛔⛔ W47-T02 CAUSE 1, RENDER SITE 1 OF 4. `fill={ring.zone.color}` had no fallback
and an unset SVG `fill` paints BLACK, which is the boundary-shaped half of the
owner's "Huge Blob". Every fill and stroke goes through `zonePaint`. */}
{zonePolygons.map((ring) => (
<polygon
key={ring.key}
className="cg-map-zone"
points={ring.points.map((point) => `${point.x.toFixed(2)},${point.y.toFixed(2)}`).join(" ")}
fill={zonePaint(ring.zone.color)}
stroke={zonePaint(ring.zone.color)}
strokeWidth={hair(LP_ZONE_STROKE_WIDTH)}
tabIndex={0}
role="button"
aria-label={`${ring.zone.name} Zone. Enter selects records; arrow keys move the boundary.`}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault(); onSelectPids(ring.zone.memberships, "replace"); return;
}
const delta = event.key === "ArrowLeft" ? { lon: -0.0005, lat: 0 }
: event.key === "ArrowRight" ? { lon: 0.0005, lat: 0 }
: event.key === "ArrowUp" ? { lon: 0, lat: 0.0005 }
: event.key === "ArrowDown" ? { lon: 0, lat: -0.0005 } : null;
if (!delta) return;
event.preventDefault(); void persistZoneGeometry(ring.zone, translateZoneGeometry(ring.geometry, delta));
}}
onPointerDown={(event) => {
// W46-T17 — an armed drawing owns the pointer; dragging a saved
// boundary would otherwise eat the click meant for a vertex.
if (event.button !== 0 || !view || zoneKeyboardDraft) return;
event.stopPropagation();
movedRef.current = false;
const svg = event.currentTarget.ownerSVGElement;
svg?.setPointerCapture(event.pointerId);
setZoneMove({
zone: ring.zone,
geometry: ring.geometry,
start: localPoint(event.clientX, event.clientY),
});
}}
onClick={(event) => {
if (zoneKeyboardDraft) return;
event.stopPropagation();
if (movedRef.current) {
movedRef.current = false;
return;
}
if (!activeZoneIds.has(ring.zone.id)) toggleZone(ring.zone, true);
else onSelectPids(ring.zone.memberships, "replace");
}}
>
<title>{`${ring.zone.name}: click to select records, drag to move boundary`}</title>
</polygon>
))}
{/* ⛔⛔ W47-T02, RENDER SITE 2 OF 4, AND THE ONE SITE THAT CARRIES BOTH CAUSES.
CAUSE 1: `fill={zone.color}` had no fallback, so a colourless circle Zone painted
black. CAUSE 2: `r={radius}` was the raw projected `Math.abs(edge.x - center.x)`
with no clamp, so an absurd `radiusMeters` painted a disc over the whole canvas.
The two are independent and neither is redundant - see `zonePaint` and
`clampZoneRadius`. The clamp takes `view.k` because `r` lives inside `tf`. */}
{zoneCircles.map(({ zone, geometry, center, radius }) => (
<circle key={zone.id} className="cg-map-zone" cx={center.x} cy={center.y} r={clampZoneRadius(radius, view.k)}
fill={zonePaint(zone.color)} stroke={zonePaint(zone.color)} strokeWidth={hair(LP_ZONE_STROKE_WIDTH)} tabIndex={0} role="button"
aria-label={`${zone.name} Circle Zone. Enter selects records; arrow keys move the boundary.`}
onPointerDown={(event) => { if (event.button !== 0 || !view || zoneKeyboardDraft) return; event.stopPropagation(); movedRef.current = false; event.currentTarget.ownerSVGElement?.setPointerCapture(event.pointerId); setZoneMove({ zone, geometry, start: localPoint(event.clientX, event.clientY) }); }}
onClick={(event) => { if (zoneKeyboardDraft) return; event.stopPropagation(); if (movedRef.current) { movedRef.current = false; return; } onSelectPids(zone.memberships, "replace"); }}
onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); onSelectPids(zone.memberships, "replace"); return; } const delta = event.key === "ArrowLeft" ? { lon: -0.0005, lat: 0 } : event.key === "ArrowRight" ? { lon: 0.0005, lat: 0 } : event.key === "ArrowUp" ? { lon: 0, lat: 0.0005 } : event.key === "ArrowDown" ? { lon: 0, lat: -0.0005 } : null; if (delta) { event.preventDefault(); void persistZoneGeometry(zone, translateZoneGeometry(geometry, delta)); } }}>
<title>{`${zone.name}: circle radius ${Math.round(geometry.radiusMeters)} metres`}</title>
</circle>
))}
{/* ⛔⛔ W47-T03 — THE RENDER `drawnZoneGeometry` NEVER HAD. This is the whole of
owner instruction 20: finishing a shape moved it into a state nothing drew, so
the boundary vanished the instant it became real and only came back as a SAVED
Zone. It is dashed and lighter than a saved boundary because unsaved is a STATE
the user has to be able to read at a glance, not a difference they must infer.
⚠ THE DASH IS AN ATTRIBUTE, NOT A CSS RULE. Everything in this group is
pre-divided by the zoom through `hair`, so a `stroke-dasharray` declared in user
units would grow with the camera; `vector-effect: non-scaling-stroke` is the
other way to fix that and `verify_map.py`'s `map-css-no-non-scaling-stroke` leg
reds on it. The fill opacity stays in CSS, beside `--lp-zone-fill`.
⚠ `aria-hidden`, and the state is announced instead by the `role="status"` line
over the Save zone / Discard pair: a decorative outline that is `pointer-events:
none` is not something a screen reader can act on, and the sentence is. */}
{zoneEditorPanelOpen && !zoneKeyboardDraft && unsavedZoneShape && (
<g className="cg-map-zone-unsaved" aria-hidden="true">
{unsavedZoneShape.kind === "circle" ? (
<circle
cx={unsavedZoneShape.center.x}
cy={unsavedZoneShape.center.y}
r={clampZoneRadius(unsavedZoneShape.radius, view.k)}
fill={zonePaint(zoneColor)}
stroke={zonePaint(zoneColor)}
strokeWidth={hair(1.8)}
strokeDasharray={`${hair(7)} ${hair(5)}`}
/>
) : unsavedZoneShape.rings.map((points, index) => (
<polygon
key={index}
points={points}
fill={zonePaint(zoneColor)}
stroke={zonePaint(zoneColor)}
strokeWidth={hair(1.8)}
strokeDasharray={`${hair(7)} ${hair(5)}`}
/>
))}
</g>
)}
{/* ⭐⭐ W46-T28 — THE VERTEX HANDLES. Owner instruction 16: *"the zone vertices
should be a dot that is draggable so I can minimize or expand a zone."* Dragging
the boundary itself already MOVED a Zone; nothing could change its SHAPE.
⛔ THEY MOUNT HERE, INSIDE `<g transform={tf}>`, AND NOT IN THE DRAFT GROUP.
`.cg-zone-keyboard-draft` is `pointer-events: none` (map-panels.css, W46-T17) so
the in-progress outline cannot swallow the clicks that extend it. A dot placed in
there would be equally unhittable, which is the whole feature. Living inside the
camera transform also means a handle stays on its corner through every pan,
zoom and rotation for free.
⛔ AND THEY ARE HIDDEN WHILE DRAWING IS ARMED. T17 made a plain click add a
vertex to the NEW shape; leaving old handles on top of that would eat those
clicks and re-break the bug that ticket just fixed.
Only polygons: a circle has no vertices, and resizing one is its own control. */}
{!zoneKeyboardDraft && zonePolygons.flatMap((ring) => (
normalizedCustomerZones && !ring.zone.permission?.canEdit ? [] :
// ⛔⛔ AND A LASSO-DRAWN BOUNDARY GETS NO HANDLES, DELIBERATELY. A rectangle
// marquee stores 4 corners, a clicked outline stores what the user clicked, but
// the lasso stores EVERY SAMPLED POINTERMOVE: hundreds of coordinates. A dot on
// each would be a solid ring of dots hiding the very fill this ticket exists to
// make legible, and hundreds of tab stops rebuilt on every pointermove. A corner
// you cannot tell apart from its neighbour is not a handle anyway.
// ⚠ REPORTED, NOT SILENT (standing rule 1): the limit is named here and in the
// ticket handoff, and the whole-boundary drag and the arrow keys still reach
// those Zones. Lifting it needs vertex simplification, which is its own ticket.
ring.handles.length > ZONE_VERTEX_HANDLE_MAX ? [] :
/* ⛔ W47-T02 CAUSE 1, RENDER SITE 4 OF 4 - FOUND BY THE GATE, NOT BY THE SPEC. The
ticket named two zone shapes, a third was already live in the draft preview, and
this vertex dot is a FOURTH: it painted black on a colourless Zone exactly like
the rest. Its `r` is `hair(5)`, already bounded, so only cause 1 reaches here.
THIS is why the normaliser is one named helper rather than `|| X` sprinkled over
individual attributes - a per-site fix would have missed this site too. */
ring.handles.map((point) => (
<circle
key={`${ring.key}:v${point.vertexIndex}`}
className="cg-map-zone-vertex"
cx={point.x}
cy={point.y}
r={hair(5)}
fill={zonePaint(ring.zone.color)}
stroke={LP_INK}
strokeWidth={hair(LP_ZONE_STROKE_WIDTH)}
tabIndex={0}
role="button"
aria-label={`${ring.zone.name} boundary point ${point.vertexIndex + 1}. Drag it, or use the arrow keys, to reshape the Zone.`}
onPointerDown={(event) => {
if (event.button !== 0 || !view) return;
// The boundary under this dot has its own drag. Stopping here is what makes
// the handle the more specific target rather than a decoration on top of it.
event.stopPropagation();
movedRef.current = false;
event.currentTarget.ownerSVGElement?.setPointerCapture(event.pointerId);
setZoneVertex({
zone: ring.zone,
geometry: ring.geometry,
polygonIndex: ring.polygonIndex,
ringIndex: ring.ringIndex,
vertexIndex: point.vertexIndex,
});
}}
onClick={(event) => { event.stopPropagation(); movedRef.current = false; }}
onKeyDown={(event) => {
const delta = event.key === "ArrowLeft" ? { lon: -0.0005, lat: 0 }
: event.key === "ArrowRight" ? { lon: 0.0005, lat: 0 }
: event.key === "ArrowUp" ? { lon: 0, lat: 0.0005 }
: event.key === "ArrowDown" ? { lon: 0, lat: -0.0005 } : null;
if (!delta || !view) return;
event.preventDefault();
event.stopPropagation();
const source = unproject(fromScreen(point, view));
void persistZoneGeometry(ring.zone, moveZoneVertex(ring.geometry, {
polygonIndex: ring.polygonIndex,
ringIndex: ring.ringIndex,
vertexIndex: point.vertexIndex,
}, { lon: source.lon + delta.lon, lat: source.lat + delta.lat }));
}}
>
<title>{`${ring.zone.name}: drag this point to reshape the Zone`}</title>
</circle>
))
))}
{/* The planned path, UNDER the pins so it never hides a stop. Inside
the zoomed group, so it pans and scales with the geography; the
stroke is pre-divided by k like every other line here. */}
{/* ⭐ W37-T36 — THE ROAD, drawn from the service's own geometry. Two claims about the
same stops need two looks: this is solid and follows streets, the dashed line below
is the straight-line plan and stays provisional. A white halo underneath, because a
navy line over a raster basemap full of navy roads is invisible exactly where
somebody is trying to read it.
⚠ Greyed rather than removed when stale: it still describes a real route, just not
the one currently listed, and hiding it would lose the picture the moment somebody
nudges one stop. */}
{roadPath && (
<g className={"cg-map-roadwrap" + (roadStale ? " is-stale" : "")}
opacity={roadStale ? 0.35 : 1}>
<polyline className="cg-map-road-halo" strokeWidth={hair(5.5)} points={roadPath} />
<polyline className="cg-map-road" strokeWidth={hair(2.6)} points={roadPath} />
</g>
)}
{plan && plan.ordered.length > 1 && (
<polyline
className="cg-map-route-line"
strokeWidth={hair(1.8)}
// ⚠ The dash MUST be pre-divided by the zoom too — a CSS
// dasharray is in user units and would scale with the group,
// turning the route into a few disconnected strokes.
strokeDasharray={dashPattern(5, 4, view.k)}
points={
plan.ordered.map((p) => `${p.p.x},${p.p.y}`).join(" ") +
(roundTrip ? ` ${plan.ordered[0].p.x},${plan.ordered[0].p.y}` : "")
}
/>
)}
{/* ⭐ W47-T07: the ticked routes, each in its own persisted colour. Drawn BEFORE the
pins so a pin is never hidden under a line, and after `plan` so the route a person
actually opened stays the emphasised one. */}
{overlaidRoutes.map((overlay) => (
<polyline
key={overlay.id}
className="cg-map-route-overlay"
fill="none"
stroke={overlay.color}
strokeWidth={hair(2.2)}
points={overlay.pts.map((at) => `${at.x},${at.y}`).join(" ")}
/>
))}
{points.map((p) => {
const c = paint(p);
const on = selectedPids.has(p.pid) || customerDetail?.pid === p.pid;
const r = radius(p) / view.k;
return (
<circle
key={p.pid}
data-map-pid={p.pid}
className={
"cg-map-pin" +
(hoverPid === p.pid ? " is-hover" : "") +
(on ? " is-selected" : "")
}
cx={p.p.x}
cy={p.p.y}
r={hoverPid === p.pid ? r * 1.28 : r}
// ⭐ SELECTED IS A FILL CHANGE, NOT ONLY A RING (wave 41 item 18). The ring
// alone left a selected pin on a mid-tone swatch hard to pick out, so the fill
// moves to the one blue reserved for selection. Both values are NAMED tokens
// carried in `theme.ts`; see `LP_MAP_SELECTED` for why this exact blue and why
// the product primary is not it.
// ⚠ THE COST, ACCEPTED: while a pin is selected it stops showing its colour-by
// bucket. The HOVER CARD is what still carries that value: it prints
// `colorField.label` from `hovered.colorVal`, which is on MapPoint for exactly
// this. The legend does NOT rescue it, since a legend maps buckets to colours
// and cannot say which bucket THIS pin is in. One unmistakable selection is
// what the ruling asked for.
fill={on ? LP_MAP_SELECTED : c.fill}
stroke={on ? LP_INK : c.line}
strokeWidth={hair(on ? 2 : 1)}
role="button"
tabIndex={0}
// ⛔⛔ NO `aria-pressed` HERE, AND THE ABSENCE IS THE FIX (W46-T14 / D-419).
// Do not "restore" it in an a11y sweep. `aria-pressed` declares a TOGGLE
// button, whose default activation flips a state. After R10 (W38-T09) a
// plain click on a pin OPENS THE RECORD; only a modifier click or Space
// moves the selection. So the pressed state, while it tracked selection
// correctly, told a screen reader the wrong thing about the one gesture it
// would try. The selected/unselected fact is not lost: `pinAriaLabel` below
// states it in words, along with both gestures, which is the channel that
// matches what the control actually does.
// ⛔ THE ACCESSIBLE NAME IS THE ONLY CHANNEL A NON-SIGHTED USER HAS FOR A PIN'S
// gesture: a `<circle>` carries no tooltip, no hover card and no glyph, and the
// hint bar above is the SIGHTED half of this same disclosure. It said "Click to
// select, double click to open." until R10 made that false.
// Policed by `verify_ui.py::pin_label_states_the_gesture`.
aria-label={pinAriaLabel(p)}
onMouseEnter={() => setHoverPid(p.pid)}
onMouseLeave={() => setHoverPid((h) => (h === p.pid ? null : h))}
onFocus={() => setHoverPid(p.pid)}
onBlur={() => setHoverPid((h) => (h === p.pid ? null : h))}
onClick={(e) => {
// ⭐ W46-T17 — while Zone drawing is armed the map is a drawing
// surface, so a click that lands on a pin places a vertex and does
// NOT open a drawer over the shape being drawn. The SVG's own
// `onPointerUp` still sees the gesture and adds the point.
if (zoneKeyboardDraft) return;
// ⛔ NO LONGER MERELY "a finished pan is not a click" (R10): a drag that ends
// on a pin would now OPEN a drawer, not just move the selection. See the
// `pinSelect` doc comment above before touching this line.
if (movedRef.current) return;
// ⭐ THE SPLIT R10 ASKS FOR, and `verify_map.py::structural_scan` reads it
// STRUCTURALLY: the select lives inside this block and the open lives outside
// it, which is the one claim a substring search cannot make.
const additive = e.shiftKey || e.ctrlKey || e.metaKey;
// Table selects on click. The default surface keeps its existing open gesture.
if (pinClickSelects) {
pinSelect(p.pid, additive);
return;
}
if (additive) {
pinSelect(p.pid, true);
return;
}
// ⛔⛔ R14 (W50-T14, 2026-09-03) — THERE IS NO `routePanelOpen` BRANCH HERE ANY
// MORE, AND ITS ABSENCE IS THE FIX. Until this date the block that stood at
// this exact spot read `if (routePanelOpen) { requestRoutePinMembership(...);
// return; }`, so with the Routes panel open EVERY pin on the map answered a
// plain click with an add-or-remove-stop prompt and `onOpen` below was
// unreachable. Worse, with the panel open and no route active the prompt could
// not even be raised: the user got the notice "Open a route first." and the
// record still never opened. That is the defect R14 names, verbatim:
// *"clicking a PIN on the map while a route is open does not open the record;
// stop rows are not the complaint."*
// ⛔ DO NOT REINSTATE IT ANYWHERE IN THIS HANDLER, and do not move it to a
// double click or to a new modifier: membership keeps its two VISIBLE doors,
// the "Add record" picker in the Route panel and the per-stop remove control
// on a stop row, both of which call the API directly from `RouteNav.tsx`. A
// pin is a record, and a click on a record opens it.
// Policed by `verify_map.py::RETIRED_ROUTE_PIN_GUARDS` and its Route-mode NCs.
// ⭐⭐ W41-T48 (owner instruction 22) — OPENING A RECORD FOLDS THE RAIL, ON
// THE MAP EXACTLY AS IN THE GRID. `CustomerGrid.tsx::onCellClicked` raises
// this on every cell click; the map was the one surface that opened a record
// and left the navigation at full width. Raised here and NOT beside the
// modifier branch above, because a shift-click works the selection and never
// opens anything.
// ⛔ `e.detail <= 1`, AND IT IS NOT A MICRO-OPTIMISATION. A double click on a
// pin fires `click` TWICE and then `dblclick`, and the `onDoubleClick` below
// re-opens the same pid ON PURPOSE (see its own note) -- so a bare `signal()`
// beside each `onOpen` would raise a PUBLIC contract event three times for
// ONE gesture. `detail` is the browser's own count of where a click sits in
// the gesture (1, then 2, and 2 again on `dblclick`), so the first click of
// any gesture signals and its repeats cannot. A time window would have been a
// guess at the OS double-click threshold; this is that threshold's own answer.
// ⚠ `<= 1` rather than `=== 1`: a synthetic `element.click()` carries
// `detail === 0`, and a programmatic open is still an open.
if (!routeApplication && e.detail <= 1) signal(NAV_MINIMIZE_EVENT);
onOpen(p.pid);
}}
// ⚠ KEPT AFTER R10, AND IT IS NO LONGER AN ESCALATION. A plain click already
// opened the record, so this fires `onOpen` a second time on the SAME pid --
// idempotent, because the host's handler is a `setDetailPid` identity. It stays
// because removing it would make a double click on a pin do nothing at all,
// and because a user who learned the old gesture keeps getting the record.
// ⛔⛔ W41-T48 — AND THIS IS WHY IT RAISES NO `NAV_MINIMIZE_EVENT`. The absence
// is deliberate and is not an oversight for a later sweep to "fix": by the
// paragraph above, this handler is a REPEAT of an open the plain click already
// performed, on a pid the rail has already folded for. `onOpen` is idempotent
// and a duplicate event would be too (`Shell.tsx::onNavMinimize` is a bare
// `setNavCollapsed(true)`), but a public contract event that fires three times
// for one gesture is a lie to every listener added after this one.
// ⛔ R14 (2026-09-03) — the Route-mode early return that used to sit
// between the `preventDefault` and the open is gone with the pin-click
// membership shortcut it belonged to. It made a double click on a pin do
// NOTHING while the Routes panel was open; the paragraph above is the whole
// rationale for this handler and it does not have a Route-mode exception.
onDoubleClick={(e) => {
if (movedRef.current) return;
e.preventDefault();
// Table opens here. The default surface already opened on click.
if (pinClickSelects && !routeApplication) signal(NAV_MINIMIZE_EVENT);
onOpen(p.pid);
}}
onKeyDown={(e) => {
// ⚠ AFTER R10 THIS IS THE MIRROR, not the exception it used to be: Enter opens
// exactly as a plain click now does, and Space is the selection half exactly
// as a modifier click is. Space with a modifier toggles; Space alone still
// REPLACES the selection, which is the only surface left that can.
// ⛔ No `movedRef` check here, deliberately: a keypress has no drag to
// disambiguate, so the guard the pointer needs would only be superstition.
if (e.key === "Enter") {
e.preventDefault();
// ⛔ R14 (2026-09-03) — the Route-mode divert that stood here is retired with
// the pin-click one above. Enter is the plain click's MIRROR, so an
// exception on one and not the other is how a keyboard user and a pointer
// user come to disagree about what a pin does.
// W41-T48 — the keyboard mirror of the plain click, so it folds the rail
// for the same reason. ⚠ `!e.repeat` is this path's `e.detail <= 1`: a HELD
// Enter auto-repeats keydown for as long as the finger is down, and every
// one of those is the same gesture. The browser flags the repeats itself,
// so nothing here has to guess at a key-repeat rate either.
if (!routeApplication && !e.repeat) signal(NAV_MINIMIZE_EVENT);
onOpen(p.pid);
return;
}
if (e.key !== " ") return;
e.preventDefault();
pinSelect(p.pid, e.shiftKey || e.ctrlKey || e.metaKey);
}}
>
<title>{p.title}</title>
</circle>
);
})}
</g>
{/* I18 — the hover card. Wave 8 painted the title alone; a map whose
pins carry a colour and a size encoding should say what they ARE.
⚠ Every value goes through `formatDisplay`, the SAME formatter the
grid cells use, so a currency, a percentage or a date can never
read one way on the map and another way in the table.
Drawn in SVG screen space rather than as an HTML overlay: the
viewBox letterboxes under preserveAspectRatio, so an HTML card
would need the rendered scale re-derived, and this needs no
conversion at all. pointer-events stay off — a card that can
swallow the next click is a scar this codebase already carries. */}
{/* Stop numbers, in SCREEN space so they stay legible at every zoom.
pointer-events off: a badge sitting over a pin must not steal the
click that opens the record — re-rooting the route is the "Start"
picker's job, where it is visible and reversible. */}
{plan &&
plan.ordered.map((p, i) => {
if (p.pid === DEPOT_PID) return null;
const s = toScreen(p.p, view);
return (
<g
className="cg-map-stopno"
key={p.pid}
transform={`translate(${s.x.toFixed(2)} ${(s.y - 13).toFixed(2)})`}
>
<circle r={7.5} />
<text textAnchor="middle" dy="3.4">{i + 1 - (plan.depot ? 1 : 0)}</text>
</g>
);
})}
{hovered && (() => {
const s = toScreen(hovered.p, view);
const lines: string[] = [];
if (colorField)
lines.push(`${colorField.label}: ${formatDisplay(colorField, hovered.colorVal) || "(blank)"}`);
if (sizeField)
lines.push(`${sizeField.label}: ${formatDisplay(sizeField, hovered.sizeVal) || "(blank)"}`);
const title = hovered.title || "(untitled)";
// Inter's average advance at 11.5px. An estimate, deliberately
// generous: too wide is a slightly roomy card, too narrow is text
// spilling past its own background.
const w = Math.max(title.length, ...lines.map((l) => l.length)) * 6.2 + 20;
const h = 21 + lines.length * 14;
const b = cardBox(s.x, s.y, w, h, VIEW_W, VIEW_H);
return (
<g className="cg-map-card" aria-hidden="true">
<rect x={b.x} y={b.y} width={w} height={h} rx={5} />
<text className="cg-map-card-t" x={b.x + 10} y={b.y + 15}>{title}</text>
{lines.map((l, i) => (
<text className="cg-map-card-l" key={i} x={b.x + 10} y={b.y + 15 + 14 * (i + 1)}>
{l}
</text>
))}
</g>
);
})()}
{rect && (
<rect
className="cg-map-marquee"
x={rect.x0}
y={rect.y0}
width={rect.x1 - rect.x0}
height={rect.y1 - rect.y0}
/>
)}
{/* The loop paints as a POLYGON, so the shape on screen is the shape
the hit test uses — an open <polyline> would draw a mouth the
selection does not have. Same class as the rectangle: one marquee
look, and no new stylesheet rule (index.css is not this fence). */}
{lassoPts && (
<polygon
className="cg-map-marquee"
points={lassoPts.map((p) => `${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(" ")}
/>
)}
{/* ⛔⛔ W46-T17. THIS GROUP IS LAST ON PURPOSE, AND THAT IS THE WHOLE
INVISIBLE-ZONE BUG. It used to sit directly under the water rect,
ABOVE `<g transform={tf}>` in document order. SVG has no z-index:
it paints in document order, so the opaque tile bed and every
raster tile in that group painted straight OVER the draft. The
draft was rendering correctly and being buried, which is why the
vertex count went up while the screen showed nothing. Moved here,
after the marquee, it is on top of everything.
⚠ It is still OUTSIDE the transform, exactly as before, because
`cursor`, `points` and `center` are SCREEN coordinates; putting it
inside `tf` would double-apply the camera. --- */}
{zoneKeyboardDraft && (
/* ⛔⛔ W47-T02 CAUSE 1, RENDER SITE 3 OF 4 - AND THE ONE A TWO-SITE SPEC MISSES.
`beginEditZone` does `setZoneColor(zone.color)` RAW, so opening a colourless Zone
for edit puts "" into `zoneColor` and every preview shape below painted black too.
The ticket named two assemblies; the third is real, so it is fixed here rather
than left for the next report. The draft lives OUTSIDE `tf`, so its clamp takes no
zoom argument: these coordinates are already screen space. */
<g className="cg-zone-keyboard-draft" aria-hidden="true">
{zoneKeyboardDraft.shape === "polygon" && zoneKeyboardDraft.points.length > 0 && (
<polyline
points={[...zoneKeyboardDraft.points, zoneKeyboardDraft.cursor]
.map((point) => `${point.x},${point.y}`).join(" ")}
fill="none" stroke={zonePaint(zoneColor)} strokeWidth="3" strokeDasharray="6 4"
/>
)}
{zoneKeyboardDraft.shape === "circle" && zoneKeyboardDraft.center && (
<circle
cx={zoneKeyboardDraft.center.x} cy={zoneKeyboardDraft.center.y}
r={clampZoneRadius(Math.hypot(
zoneKeyboardDraft.cursor.x - zoneKeyboardDraft.center.x,
zoneKeyboardDraft.cursor.y - zoneKeyboardDraft.center.y
))}
fill={zonePaint(zoneColor)} fillOpacity={zoneFillOpacity} stroke={zonePaint(zoneColor)}
strokeWidth="3" strokeDasharray="6 4"
/>
)}
{zoneKeyboardDraft.points.map((point, index) => (
<circle key={`${point.x}:${point.y}:${index}`} cx={point.x} cy={point.y} r="4" fill={zonePaint(zoneColor)} />
))}
<circle cx={zoneKeyboardDraft.cursor.x} cy={zoneKeyboardDraft.cursor.y} r="6" fill={zonePaint(zoneColor)} stroke="white" strokeWidth="2" />
</g>
)}
</svg>
{/* --- I18 — the camera controls. Zoom in / zoom out / fit to data, the
affordance every map has, replacing wave 8's link-button-in-a-text-bar.
OUTSIDE the <svg> deliberately: a mousedown on a button inside it would
begin a pan. Icons are SVG strokes — no emoji, no glyph font. The zoom
buttons DISABLE at the limits, which is also how the honesty cap on
zoom-in makes itself visible instead of just feeling stuck.
⭐⭐ OWNER ITEM 1 (2026-08-23) — IT IS A NAVIGATION BAR NOW, AT THE TOP MIDDLE.
Owner: *"the navigation for 'Zoom in (+)' etc. should not be at the top left of the
Map. it should be at the top MIDDLE of the map, and horizontal. Make the icon bigger
so its easier to see. Make it look like a proper navigation bar."* Centred, 34px keys
with 20px glyphs, and two new ones: Rotate left and Rotate right, 5 degrees a click.
⚠ THE ROTATE PAIR BRACKETS THE CAMERA KEYS rather than sitting at one end. Turning
left and turning right are one control with two directions; splitting them would
leave a reader hunting for the second half of a pair. --- */}
<div className="cg-map-ctl" role="group" aria-label="Map camera">
<button
type="button"
className="cg-map-ctl-b"
title={`Rotate left (${ROTATE_STEP} degrees per click, or press the [ key)`}
aria-label="Rotate left"
onClick={() => rotateBy(-ROTATE_STEP)}
>
{/* A dial arrow turning anticlockwise. The arrowhead is what says WHICH way, so it is
drawn as a filled wedge rather than a stroked chevron: at 20px a two-line chevron
on a curve reads as a kink in the curve. */}
<svg viewBox="0 0 20 20" aria-hidden="true">
<path d="M5.2 7.4A6 6 0 1 1 4 11" />
<path className="cg-map-ctl-head" d="M2.4 4.2 6.2 8.1 2.1 8.6z" />
</svg>
</button>
<button
type="button"
className="cg-map-ctl-b"
// A greyed button with no reason reads as broken, not as honest —
// and filtering to a single metro can push the FITTED zoom past the
// cap, so this can be disabled the instant the view opens. Say why,
// and point at the thing that does go further.
// ⚠ W37-T35 REWROTE THIS SENTENCE because tiles made it false. It used to read
// "the basemap's detail ends here; use Open in Google Maps for street level", which
// was the honest thing to say about a vendored polygon and is simply untrue over a
// street map. Which limit you have actually reached now depends on which basemap is
// under you, so the copy says which.
title={
view.k >= kMax * (1 - 1e-9)
? tileLayer
? "Zoom in. You are as far in as the map provider goes."
: "Zoom in. The offline basemap runs out here, so use Open in Google Maps for street level."
: "Zoom in (+)"
}
aria-label="Zoom in"
disabled={view.k >= kMax * (1 - 1e-9)}
onClick={() => zoomBy(1.6)}
>
<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M8 3.6v8.8M3.6 8h8.8" /></svg>
</button>
<button
type="button"
className="cg-map-ctl-b"
title="Zoom out (−)"
aria-label="Zoom out"
disabled={view.k <= kMin * (1 + 1e-9)}
onClick={() => zoomBy(1 / 1.6)}
>
<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M3.6 8h8.8" /></svg>
</button>
<button
type="button"
className="cg-map-ctl-b"
// ⭐ ITEM 1 — THE TITLE EARNED A SECOND CLAUSE because the button gained a second
// job: `fit` carries no bearing, so this is also the way back to north. A control
// that silently un-rotates the map is a surprise; one that says it does is the undo.
title="Fit to data and face north (0)"
aria-label="Fit to data and face north"
onClick={doFit}
>
<svg viewBox="0 0 16 16" aria-hidden="true">
<path d="M2.6 5.8V2.6h3.2M10.2 2.6h3.2v3.2M13.4 10.2v3.2h-3.2M5.8 13.4H2.6v-3.2" />
<path d="M6.6 8h2.8M8 6.6v2.8" />
</svg>
</button>
{/* The selection SHAPE. Not a mode for selecting — shift-drag selects
either way — so the note over `onPointerDown` still stands. The
icon shows the shape you will get, which is the only "on" state
available: `.cg-map-ctl-b` has no pressed style and index.css
belongs to another session this wave, so a pressed look would have
been a control that cannot show its own state. */}
<button
type="button"
className="cg-map-ctl-b"
title={
lassoTool
? "Selection shape: lasso - shift-drag traces a freehand loop. Click for a rectangle."
: "Selection shape: rectangle - shift-drag draws a box. Click for a freehand lasso."
}
aria-label="Selection shape"
aria-pressed={lassoTool}
onClick={() => setLassoTool((v) => !v)}
>
{lassoTool ? (
<svg viewBox="0 0 16 16" aria-hidden="true">
<path d="M12.1 6.2c1.1 1.6.3 3.5-1.9 4.4-2.4 1-5.5.5-6.7-1.1-1-1.4-.1-3.1 2-3.9 2.2-.8 4.9-.5 6.1.6" />
<path d="M4.9 10.3 4.2 13.4" />
</svg>
) : (
<svg viewBox="0 0 16 16" aria-hidden="true">
<path d="M3.2 4.4h9.6v7.2H3.2z" />
</svg>
)}
</button>
{/* The street-level hand-off, aimed at whatever is on screen right
now. This is what makes the zoom cap honest rather than merely
restrictive: the map stops where its geometry stops, and points at
something that does not. */}
<a
className="cg-map-ctl-b"
href={areaUrl}
target="_blank"
rel="noopener noreferrer"
title="Open this area in Google Maps (new tab)"
aria-label="Open this area in Google Maps"
>
<GoogleMapsMark />
</a>
<button
type="button"
className="cg-map-ctl-b"
title={`Rotate right (${ROTATE_STEP} degrees per click, or press the ] key)`}
aria-label="Rotate right"
onClick={() => rotateBy(ROTATE_STEP)}
>
{/* The mirror of Rotate left, and drawn as its mirror rather than re-derived, so the
two cannot end up subtly different weights on the same bar. */}
<svg viewBox="0 0 20 20" aria-hidden="true">
<path d="M14.8 7.4A6 6 0 1 0 16 11" />
<path className="cg-map-ctl-head" d="M17.6 4.2 13.8 8.1 17.9 8.6z" />
</svg>
</button>
</div>
{/* --- W37-T35 — THE CREDIT LINE. ⛔ A LICENCE TERM, NOT DECORATION.
OpenStreetMap's terms require visible attribution wherever its tiles appear, and every
provider that could replace it says the same. Both the text and the link come from the
server's provider config, so a swap carries its own credit and cannot leave the
previous vendor's name on screen. It is rendered only while tiles are actually
painting: crediting a provider whose tiles failed to load would be a false statement
about what you are looking at. --- */}
{tileLayer && tiles.attribution && (
<div className="cg-map-credit">
<a href={tiles.attributionUrl} target="_blank" rel="noopener noreferrer">
{tiles.attribution}
</a>
</div>
)}
{/* --- legends (I3/I5). Floated over the map, never in the flow. --- */}
{(colorBuckets || sizeLegend || (sizeField && sizeRange && sizeRange.min < 0)) && (
<div className="cg-map-legends">
{colorField && colorBuckets && (
<div className="cg-map-legend">
<div className="cg-map-legend-t">{colorField.label}</div>
{colorBuckets.order.slice(0, SERIES.length + 1).map((k) => {
const c = k === "" ? OVERFLOW : colorBuckets.swatch.get(k) ?? OVERFLOW;
return (
<div key={k || "(blank)"} className="cg-map-legend-row">
<span
className="cg-map-swatch"
style={{ background: c.fill, borderColor: c.line }}
/>
<span className="cg-map-legend-k">{k === "" ? "(blank)" : k}</span>
<span className="cg-map-legend-n">
{(colorBuckets.counts.get(k) ?? 0).toLocaleString()}
</span>
</div>
);
})}
{colorBuckets.overflow > 0 && (
<div className="cg-map-legend-note">
{colorBuckets.overflow.toLocaleString()} further value
{colorBuckets.overflow === 1 ? " is" : "s are"} drawn grey. The palette
holds {SERIES.length} colours, and reusing one would make two values look
like the same value.
</div>
)}
</div>
)}
{sizeField && sizeRange && (
<div className="cg-map-legend">
<div className="cg-map-legend-t">{sizeField.label}</div>
{sizeLegend ? (
<div className="cg-map-sizerow">
{sizeLegend.map((v, i) => {
const r = bubbleRadius(v, sizeRange.min, sizeRange.max, R_MIN, R_MAX, R_NULL);
return (
<span key={i} className="cg-map-sizeitem">
<svg width={R_MAX * 2 + 2} height={R_MAX * 2 + 2} aria-hidden>
<circle
cx={R_MAX + 1}
cy={R_MAX + 1}
r={r}
fill={DEFAULT_PIN.fill}
stroke={DEFAULT_PIN.line}
/>
</svg>
<span className="cg-map-legend-k">{formatDisplay(sizeField, v)}</span>
</span>
);
})}
</div>
) : (
<div className="cg-map-legend-note">
Every mapped record has the same {sizeField.label.toLowerCase()}, so the
bubbles cannot differ in size.
</div>
)}
{sizeRange.min < 0 && (
<>
<div className="cg-map-legend-row">
<span
className="cg-map-swatch"
style={{ background: LP_RED, borderColor: LP_RED_DEEP }}
/>
<span className="cg-map-legend-k">Negative values</span>
</div>
<div className="cg-map-legend-note">
Size shows the value’s magnitude; values below zero are red.
</div>
</>
)}
{sizeRange.missing > 0 && (
<div className="cg-map-legend-note">
{sizeRange.missing.toLocaleString()} mapped record
{sizeRange.missing === 1 ? " has" : "s have"} no value, so they are drawn
at the smallest dot and never removed from the map.
</div>
)}
</div>
)}
</div>
)}
</div>
{/* ═══════════════════════════════════════════════════════════════════════════════════
THE ROUTE PANEL — rebuilt for owner items 2, 4, 6, 8 and 9.
⭐⭐ ITEM 2 IS THE STRUCTURAL ONE AND IT IS WHY THIS IS ONE REBUILD RATHER THAN FIVE
EDITS. The panel used to render its entire body inside `selectedPids.size >= 2`, so
clicking Route with nothing chosen produced a box containing one sentence telling you
off. The owner's answer: show the navigation, empty. So the chrome, the travel mode,
the stop list and the record search are UNCONDITIONAL, and only the parts that
genuinely describe a solved route (the distance, the visit numbers, the save target)
wait for `plan`.
⛔ `plan` IS NULL UNTIL `routeOn` FLIPS **AND** TWO STOPS CAN BE ROUTED, so every read
of `plan.*` below sits inside a `plan &&`. The old code was safe only because the whole
body was behind the two-selected wall this item removes; `plan.ordered[0]` with nothing
selected is a crash, not a blank.
═══════════════════════════════════════════════════════════════════════════════════ */}
{mapNavigator === "routes" && (
<aside id="cg-route-popover" className="cg-route-popover cg-route-nav-panel cg-route-index" aria-label="Routes">
{navigatorTabs}
<div className="cg-route-panel-scroll" role="region" aria-label="Route panel" tabIndex={0}>
{/* D-599 / W46-T22 - `zones` is the vocabulary a Route's Zone selector offers. It
is already loaded here to draw the map, so RouteNav gets a pass-through and
never a second fetch of its own. */}
<RouteNav
applicationName={applicationName}
applicationId={applicationId}
routes={namedRoutes}
routesLoaded={routesLoaded}
routesLoadError={routesLoadError}
onRetryRoutes={() => void loadNamedRoutes()}
folders={routeFolders}
selectedIds={selectedRouteIds}
activeRouteId={activeRouteId}
sources={routeSources}
storageKey={tableKey}
createdRoute={createdRoute}
onCreatedDismiss={() => setCreatedRoute(null)}
onToggle={(route) => void toggleNamedRoute(route)}
onActiveRouteChange={setActiveRouteId}
onOpenRecord={onOpen}
stopLabels={routeStopLabels}
stopCoords={routeStopCoords}
roundTrip={roundTrip}
onRoundTripChange={(value) => {
if (value) setRouteEndPid(null);
// A saved/manual order is an intentional route, but an endpoint change asks for
// a fresh constrained solve. Leaving it in place would make the dropdown move
// without changing the painted or timed route.
setRouteOrder(null);
setRoundTrip(value);
}}
routeStartPid={routeStartPid}
routeEndPid={routeEndPid}
onRouteStartChange={(pid) => {
setRouteOrder(null);
setRouteStartPid(pid);
if (pid === routeEndPid) setRouteEndPid(null);
}}
onRouteEndChange={(pid) => { setRouteOrder(null); setRouteEndPid(pid); }}
onStopAdded={(updated, sourceApplicationId) => {
if (!routingAlive.current || sourceApplicationId !== applicationId) return;
setNamedRoutes((current) => current.map((item) => item.id === updated.id
? { ...item, ...updated, folderId: item.folderId, navOrder: item.navOrder }
: item));
}}
onCreate={createNamedRoute}
onMoveToOrder={moveNamedRouteStop}
onUpdate={updateNamedRoute}
onDuplicate={duplicateNamedRoute}
onDelete={deleteNamedRoute}
onShare={shareNamedRoute}
onRouteMove={moveNamedRoute}
onRouteReorder={reorderNamedRoutes}
onFolderCreate={createNamedRouteFolder}
onFolderUpdate={updateNamedRouteFolder}
onFolderDelete={deleteNamedRouteFolder}
onFolderReorder={reorderNamedRouteFolders}
onCreateStart={() => setSaveTarget("")}
mapLinks={activeRouteMaps.links}
mapLinkRefusal={activeRouteMapsRefusal}
deliveries={routeDeliveries}
deliveryRecipients={routeDeliveryRecipients?.people ?? null}
zones={zones || []}
deliveryRecipientError={deliveryRecipientError}
onReloadDeliveryRecipients={() => { void loadRouteDeliveryRecipients(); }}
onSchedule={scheduleNamedRouteDelivery}
onDeleteDelivery={deleteNamedRouteDelivery}
/>
{routePinNotice && (
<span className="cg-w44-route-warning" role="status">{routePinNotice}</span>
)}
{routeSelectionWarning && (
<span className="cg-w44-route-warning" role="status">{routeSelectionWarning}</span>
)}
</div>
</aside>
)}
{zoneChooserPanelOpen && (
<aside id="cg-zone-popover" className="cg-route-popover cg-route-nav-panel cg-zone-nav" aria-label="Zone chooser">
{navigatorTabs}
<div className="cg-route-panel-scroll" role="region" aria-label="Zone panel" tabIndex={0}>
<div className="cg-route-popover-head">
<button type="button" className="cg-route-index-back" onClick={closeZoneChooser}>Back</button>
<span className="cg-views-title">Zones</span>
</div>
<div className="cg-map-zones" role="group" aria-label="Choose visible Zones">
<div id="cg-map-zone-choices" className="cg-map-zone-choices" role="group" aria-label="Visible map Zones">
{(zones || []).length === 0 ? (
<span className="cg-map-zone-empty">No Zones yet.</span>
) : (zones || []).map((zone) => (
<div className="cg-map-zone-option" key={zone.id}>
<label className="cg-map-zone-choice">
<input
type="checkbox"
checked={activeZoneIds.has(zone.id)}
disabled={!zone.visible}
onChange={(event) => toggleZone(zone, event.target.checked)}
/>
<span className="cg-map-zone-swatch" style={{ backgroundColor: zone.color }} aria-hidden="true" />
<span>{zone.visible ? zone.name : `${zone.name} (hidden)`}</span>
</label>
<button type="button" className="cg-map-zone-edit"
disabled={normalizedCustomerZones && !zone.permission?.canEdit}
onClick={() => beginEditZone(zone)} aria-label={`Edit ${zone.name}`}>
Edit
</button>
</div>
))}
</div>
<button type="button" className="cg-btn cg-btn--primary" onClick={beginNewZone}>New Zone</button>
{/* ⛔ W46-T28 — `zoneErr` USED TO RENDER IN THE EDITOR PANEL ONLY, and half the
things that set it happen with the editor closed: `persistZoneGeometry` fires
from a boundary drag and now from a vertex drag, both of which happen right
here on the map with this list open. A rejected reshape would have failed in
silence, the shape snapping back with no reason given. Standing rule 1: a
refusal is reported, never silently enforced. */}
{zoneErr && <span className="cg-cal-nodate" role="status">{zoneErr}</span>}
</div>
</div>
</aside>
)}
{zoneEditorPanelOpen && (
<aside id="cg-zone-popover" className="cg-route-popover cg-route-nav-panel cg-zone-nav" aria-label={zoneEditor ? `Edit ${zoneEditor.name}` : "Create Zone"}>
{navigatorTabs}
<div className="cg-route-panel-scroll" role="region" aria-label="Zone panel" tabIndex={0}>
<div className="cg-route-popover-head">
<button type="button" className="cg-route-index-back" onClick={closeZoneEditor}>Back to Zones</button>
<span className="cg-views-title">{zoneEditor ? "Edit Zone" : "New Zone"}</span>
</div>
<div className="cg-map-zones cg-map-zone-editor">
<label className="cg-map-zone-control">
Zone name
<input
className="cg-input"
value={zoneName}
maxLength={120}
aria-label="Zone name"
placeholder="Name this Zone"
onChange={(event) => setZoneName(event.target.value)}
/>
</label>
<fieldset className="cg-zone-shape-picker">
<legend>Boundary</legend>
<div role="group" aria-label="Zone boundary shape">
<button type="button" aria-pressed={zoneDrawShape === "polygon"}
onClick={() => setZoneDrawShape("polygon")}>Polygon</button>
<button type="button" aria-pressed={zoneDrawShape === "circle"}
onClick={() => setZoneDrawShape("circle")}>Circle</button>
</div>
<span>Choose a shape, then drag on the map, or draw it by clicking.</span>
{!zoneKeyboardDraft ? (
<button type="button" className="cg-link-btn cg-zone-draw-btn" onClick={startKeyboardZoneDrawing}>
<DrawZoneIcon />
Draw by clicking
</button>
) : (
<>
{/* ⛔⛔ W46-T28 — "FINISH SHAPE" IS THE MISSING CONTROL, not a convenience.
Pressing Enter only commits the outline while the MAP holds focus, and
naming the Zone moves focus into the input beside this. Without a button
in the panel, the only ending on offer was "Stop drawing", which throws
the points away, so a drawn shape could never reach the Save button. */}
<div className="cg-zone-draw-actions">
<button type="button" className="cg-link-btn cg-zone-draw-btn is-armed"
onClick={() => { finishZoneDraft(); }}>
<DrawZoneIcon />
Finish shape
</button>
<button type="button" className="cg-link-btn cg-zone-draw-btn"
onClick={() => { setZoneKeyboardDraft(null); setZoneErr(null); }}>
Stop drawing
</button>
</div>
<span role="status" aria-live="polite">
{zoneKeyboardDraft.shape === "polygon"
? `${zoneKeyboardDraft.points.length} ${zoneKeyboardDraft.points.length === 1 ? "vertex" : "vertices"}. Click the map to add one, then choose Finish shape, or press Enter on the map.`
: zoneKeyboardDraft.center
? "Center placed. Click its edge, then choose Finish shape."
: "Click the map to place the circle center, then click its edge."}
</span>
</>
)}
</fieldset>
{/* ⭐⭐ W47-T03, RULING R4 — THE FINISHED SHAPE CARRIES ITS OWN TWO ENDINGS.
Before this there was no such thing as a finished-but-unsaved Zone on screen:
"Finish shape" cleared the only painted state and the user was left holding a
boundary they could not see, in front of a primary button that gave no sign it
now had something to save. The pair sits exactly where Finish shape / Stop
drawing were, because it is the same flow one step later.
⛔ SAVE GOES THROUGH `saveZone`, NOT A SECOND WRITE PATH. `saveZone` already
reads `drawnZoneGeometry`, already states its own refusal in `zoneErr` when the
name is missing, and already clears the geometry on success so this row and the
dashed shape retire together the moment the solid saved Zone appears.
⚠ Discard clears the geometry ONLY. It does not close the editor or reset the
name and colour: throwing away a boundary the user disliked should not also
throw away the two fields they typed before drawing it. */}
{!zoneKeyboardDraft && drawnZoneGeometry && (
<>
<div className="cg-zone-draw-actions cg-zone-unsaved-actions">
<button type="button" className="cg-link-btn cg-zone-draw-btn is-armed"
disabled={zoneBusy || (normalizedCustomerZones && !!zoneEditor && !zoneEditor.permission?.canEdit)}
onClick={() => { void saveZone(zoneEditor || undefined); }}>
Save zone
</button>
<button type="button" className="cg-link-btn cg-zone-draw-btn"
onClick={() => { setDrawnZoneGeometry(null); setZoneErr(null); }}>
Discard
</button>
</div>
<span className="cg-zone-unsaved-note" role="status" aria-live="polite">
Shape finished. It is not saved yet, and shows as the dashed outline on the
map until you choose Save zone.
</span>
</>
)}
{zoneEditor && (
<button
type="button"
className="cg-btn"
disabled={zoneBusy || (normalizedCustomerZones && !zoneEditor.permission?.canEdit)}
onClick={() => void setZoneVisible(zoneEditor, !zoneEditor.visible)}
>
{zoneEditor.visible ? "Hide Zone" : "Show Zone"}
</button>
)}
<label className="cg-map-zone-control">
Color
<select className="cg-route-select" value={zoneColor} aria-label="Zone color" onChange={(event) => setZoneColor(event.target.value)}>
{ZONE_COLOR_CHOICES.map((choice) => <option key={choice.value} value={choice.value}>{choice.label}</option>)}
</select>
</label>
{/* ⭐ OWNER 2026-08-31 - the opacity is a dial now, not a constant. It sits beside
Color because both are how a Zone READS rather than what it covers, and it takes
effect on every Zone the moment it moves: the value is the custom property the
saved-Zone rule already consumes.
⚠ The reading is shown as a PERCENTAGE because that is the unit the instruction
was given in ("80% opacity"), while the stored value stays the 0-1 fraction every
consumer expects - the conversion happens at this boundary and nowhere else. */}
<label className="cg-map-zone-control">
Fill opacity
<input
type="range"
className="cg-zone-opacity-range"
min={0}
max={100}
step={5}
value={Math.round(zoneFillOpacity * 100)}
aria-label="Zone fill opacity"
aria-valuetext={`${Math.round(zoneFillOpacity * 100)} percent`}
onChange={(event) => setZoneFillOpacity(Number(event.currentTarget.value) / 100)}
/>
<span className="cg-zone-opacity-read">{Math.round(zoneFillOpacity * 100)}%</span>
</label>
{/* ⛔⛔ W46-T28 — A MISSING NAME OR BOUNDARY NO LONGER DISABLES THIS BUTTON, and
that is the point rather than a loosening. A disabled control cannot say why it
is disabled, so the owner's "it won't even let me save" arrived with no reason
on screen at all. `saveZone` already has the message for both cases ("Name a
Zone and draw its boundary on the map.") and `zoneErr` renders at the foot of
this panel, so letting the click through turns a silent refusal into a stated
one. Permission and in-flight state still disable it: those are not the user's
mistake to correct. */}
<button
type="button"
className="cg-btn cg-btn--primary"
disabled={zoneBusy || (normalizedCustomerZones && !!zoneEditor && !zoneEditor.permission?.canEdit)}
onClick={() => {
// An outline still being drawn is committed first, and its geometry handed
// straight down: state set in this tick is not readable from `saveZone`.
if (zoneKeyboardDraft) {
const pending = finishZoneDraft();
// `finishZoneDraft` has already put the real reason in `zoneErr`. Falling
// through would overwrite it with a vaguer one.
if (!pending) return;
void saveZone(zoneEditor || undefined, pending);
return;
}
void saveZone(zoneEditor || undefined);
}}
title={drawnZoneGeometry || zoneKeyboardDraft
? (zoneEditor ? "Replace this Zone boundary with the drawn shape" : "Save the drawn Zone")
: zoneEditor ? "Save Zone details" : "Draw a boundary first"}
>
{zoneEditor ? "Update Zone" : "Save Zone"}
</button>
{zoneEditor && (!normalizedCustomerZones || zoneEditor.permission?.canDelete) && (
<button type="button" className="cg-btn cg-btn--danger" disabled={zoneBusy}
onClick={() => setPendingZoneDelete(zoneEditor)}>
Delete Zone
</button>
)}
{zoneErr && <span className="cg-cal-nodate" role="status">{zoneErr}</span>}
</div>
</div>
</aside>
)}
{routeApplication && <RouteCustomerPane detail={customerDetail}
onBack={() => onCustomerBack?.()} />}
</div>
{/* ═══════ W51-T28 / R6 — EVERY CONFIRM THIS SURFACE ASKS FOR, IN ONE PLACE ═══════════
⛔ MOUNTED AT THE COMPONENT ROOT, NOT BESIDE THE CONTROL THAT OPENS IT. Two of these
were `window.confirm` calls inside a panel, and one lived inside the routes popover's
own subtree. A dialog rendered inside a subtree that closes itself in the same handler
unmounts before it paints, and the person sees nothing at all.
⛔ NO Z-INDEX IS SET HERE AND NONE IS NEEDED, AND W51-T32 MADE THAT MORE TRUE RATHER
THAN LESS. The three navigator panels are now ordinary items in the map row, painting in
the flow at the browser's default stacking; only the transient selection notice still
floats at `--cg-z-mapchrome` (65). `ConfirmDialog` portals to <body> at `--cg-z-overlay`
(110), so dialog over panel over pins still holds on the scale in `index.css :root`, and
"raising" the dialog would be re-breaking the three-way order by hand. */}
<ConfirmDialog
open={pendingZoneDelete !== null}
title={`Delete ${pendingZoneDelete?.name ?? "Zone"}?`}
/* ⭐ A REAL COUNT, NOT A ROUNDED REASSURANCE (standing rules 1 and 8). `memberships` is
the Zone's member pids and is already on the object the chooser drew, so the sentence
states what deleting the shape actually leaves behind. */
body={(() => {
const kept = (pendingZoneDelete?.memberships || []).length;
return kept === 1
? "1 stop keeps its records; the zone shape is removed"
: `${kept.toLocaleString()} stops keep their records; the zone shape is removed`;
})()}
confirmLabel="Delete zone"
tone="destructive"
busy={zoneBusy}
/* ⛔⛔ CLEARED ON SETTLE, NOT BEFORE THE DISPATCH, AND THE ORDER IS THE WHOLE POINT OF
`busy`. Clearing first closes the dialog in the same batched render, so `open` is
already false by the time `zoneBusy` flips and the locked buttons never paint: a prop
that cannot render, with a gate needle pinning it, is precisely the shape this file's
other legs exist to refuse. Re-entrancy is covered by `busy` disabling both buttons and
by `ConfirmDialog` refusing to dismiss while busy, so nothing is lost by waiting. */
onConfirm={() => {
const zone = pendingZoneDelete;
if (!zone || zoneBusy) return;
void deleteZone(zone).finally(() => setPendingZoneDelete(null));
}}
onCancel={() => setPendingZoneDelete(null)}
/>
<ConfirmDialog
open={pendingRouteInclude !== null}
/* ⚠ A SHORT NOUN PHRASE, per the kit's own contract and DESIGN.md section 2: the
question lives in the body, and the button names the act. The zone delete ABOVE is
the ONE title written as a question, because its exact wording is the done-when. */
title="Route outside this filter"
body={`${pendingRouteInclude?.name ?? "This route"} is outside this filter. Only this route's managed membership group is included.`}
confirmLabel="Include route"
tone="primary"
onConfirm={confirmPendingRouteInclude}
onCancel={() => setPendingRouteInclude(null)}
/>
{/* ⚠ UNREACHABLE TODAY, AND CONVERTED ANYWAY. R14 (W50-T14) retired the pin click and the
pin Enter, which were `requestRoutePinMembership`'s only two callers, so nothing sets
`routePinPrompt` at present. The machinery is deliberately kept whole and wired
(verify_map.py's `single-stop-door` / `actual-membership` / `visible-confirmation` legs
all still hold it), so leaving the one native-shaped prompt behind would have left R6
half-applied for whoever reinstates a door. */}
<ConfirmDialog
open={routePinPrompt !== null}
title={routePinPrompt?.present ? "Add a route stop" : "Remove a route stop"}
body={routePinPrompt
? `${routePinPrompt.title} will be ${routePinPrompt.present ? "added to" : "removed from"} ${activeNamedRoute?.name || "this Route"}.`
: undefined}
confirmLabel={routePinPrompt?.present ? "Add stop" : "Remove stop"}
tone={routePinPrompt?.present ? "primary" : "destructive"}
busy={routePinBusy}
onConfirm={() => void confirmRoutePinMembership()}
onCancel={() => setRoutePinPrompt(null)}
/>
</div>
);
}
export type MapViewProps = Omit<Parameters<typeof MapViewSurface>[0], "field" | "onOpen" | "pinClickSelects"> & {
field?: Field; fields?: Field[];
onOpen: (pid: number, row?: Row) => void;
routingFilterNodes?: FilterNode[];
routingFilterConj?: Conjunction;
onCatalogData?: (fields: Field[], rows: Row[]) => void;
};
interface RegistryTemplateApplication {
id: string;
name: string;
type: string;
templateKind?: unknown;
sourceDatabase?: unknown;
fieldMap?: unknown;
openTarget?: { database?: unknown };
compatibleDatabases?: unknown[];
config?: { schemaVersion: 1; display: Record<string, unknown> };
revision?: number;
capabilities?: { edit?: boolean };
}
type TemplateApplicationState =
| { phase: "idle" }
| { phase: "loading"; key: string }
| { phase: "ready"; key: string; application: RegistryTemplateApplication | null }
| { phase: "error"; key: string; message: string };
/** Resolve an Application deep link from the registry before selecting a specialized renderer.
* CustomerGrid still applies the definition's ordinary display config; this wrapper only handles
* the route and catalog discriminators which deliberately share the trusted Map mode. */
export function MapView(props: MapViewProps) {
// C3: a hosted map reads no hash. Its database is the grid's own, and an address names no Application.
const hosted = props.hosted === true;
const target = hosted ? undefined : readDataPath();
const applicationId = target?.application ?? "";
const database = hosted ? props.tableKey : target?.database ?? "";
const requestKey = applicationId && database ? `${database}::${applicationId}` : "";
const [state, setState] = useState<TemplateApplicationState>(() => requestKey
? { phase: "loading", key: requestKey }
: { phase: "idle" });
const requestGeneration = useRef(0);
const applicationRef = useRef<RegistryTemplateApplication | null>(null);
const catalogSaveQueue = useRef<Promise<void>>(Promise.resolve());
useEffect(() => {
const mine = ++requestGeneration.current;
applicationRef.current = null;
if (!applicationId || !database) {
setState({ phase: "idle" });
return;
}
const controller = new AbortController();
setState({ phase: "loading", key: requestKey });
void fetch(`${API_V1}/applications?database=${encodeURIComponent(database)}`, {
credentials: CREDENTIALS,
signal: controller.signal,
}).then(async (response) => {
const body = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(String(
body?.detail?.message ?? body?.detail ?? "The Application could not be loaded.",
));
}
const applications = Array.isArray(body?.applications)
? body.applications as RegistryTemplateApplication[]
: [];
const application = applications.find((candidate) => candidate.id === applicationId) ?? null;
if (!application) throw new Error("This Application is no longer available.");
const compatible = application.openTarget?.database === database ||
application.compatibleDatabases?.includes(database) === true;
if (!compatible) throw new Error("This Application cannot open this database.");
if (controller.signal.aborted || mine !== requestGeneration.current) return;
const live = hosted ? undefined : readDataPath();
if (!hosted && (live?.application !== applicationId || live?.database !== database)) return;
applicationRef.current = application;
setState({ phase: "ready", key: requestKey, application });
}).catch((error: unknown) => {
if (controller.signal.aborted || mine !== requestGeneration.current) return;
setState({
phase: "error",
key: requestKey,
message: error instanceof Error ? error.message : "The Application could not be loaded.",
});
});
return () => controller.abort();
}, [applicationId, database, requestKey, hosted]);
if (applicationId && (state.phase === "idle" || state.key !== requestKey || state.phase === "loading")) {
return (
<LogoLoader className="cg-app-launch-state" />
);
}
if (applicationId && state.phase === "error" && state.key === requestKey) {
return <div className="cg-app-launch-state is-error" role="alert">{state.message}</div>;
}
const application = state.phase === "ready" && state.key === requestKey ? state.application : null;
const surface = applicationTemplateSurface(application);
// R33: the registry serves a Routing or Catalog App with its C1 Odoo binding as `fieldMap`.
const fieldMap = application?.fieldMap && typeof application.fieldMap === "object" &&
!Array.isArray(application.fieldMap)
? application.fieldMap as Record<string, unknown>
: {};
if (surface === "catalog") {
const key = String(fieldMap.key ?? "");
const title = String(fieldMap.title ?? "");
if (!application || !key || !title) {
return <div className="cg-app-launch-state is-error" role="alert">The Catalog could not read its product fields.</div>;
}
const definition: CatalogApplicationDefinition = {
id: application.id,
name: application.name,
templateKind: "catalog",
sourceDatabase: String(application.sourceDatabase ?? database),
fieldMap: {
key,
title,
...(fieldMap.image ? { image: String(fieldMap.image) } : {}),
...(fieldMap.sku ? { sku: String(fieldMap.sku) } : {}),
...(fieldMap.price ? { price: String(fieldMap.price) } : {}),
...(fieldMap.category ? { category: String(fieldMap.category) } : {}),
...(fieldMap.description ? { description: String(fieldMap.description) } : {}),
},
};
const display = application.config?.display ?? {};
const catalogs = Array.isArray(display.catalogs) ? display.catalogs as CatalogSpec[] : [];
const catalogSpec = display.catalog && typeof display.catalog === "object" &&
!Array.isArray(display.catalog)
? display.catalog as CatalogViewSpec
: { titleField: title, imageField: definition.fieldMap.image };
const onSave = (nextCatalogs: CatalogSpec[], nextSpec: CatalogViewSpec): Promise<void> => {
const generation = requestGeneration.current;
// Serialize saves, including after a refusal. Each edit sends the complete local draft,
// and builds on the most recent server config instead of an earlier render's closure.
const save = catalogSaveQueue.current.then(async () => {
const current = applicationRef.current;
if (generation !== requestGeneration.current || current?.id !== application.id) {
throw new Error("This Application is no longer available.");
}
if (current.capabilities?.edit !== true) {
throw new Error("You cannot edit this Application.");
}
const response = await fetch(`${API_V1}/applications/${encodeURIComponent(current.id)}`, {
method: "PATCH",
credentials: CREDENTIALS,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
config: {
schemaVersion: 1,
display: {
...current.config?.display,
mode: "map",
catalogs: nextCatalogs,
catalog: nextSpec,
},
},
}),
});
const body = await response.json().catch(() => ({}));
if (!response.ok) {
// X2: every refusal is `{error: {code, message}}`; show the server's sentence.
throw new Error(String(body?.error?.message ?? body?.detail?.message ??
"The Catalog could not be saved."));
}
const updated = body?.application as RegistryTemplateApplication | undefined;
if (!updated || updated.id !== current.id || !updated.config ||
typeof updated.revision !== "number") {
throw new Error("The Catalog save could not be confirmed.");
}
if (generation !== requestGeneration.current) return;
applicationRef.current = updated;
setState((live) => live.phase === "ready" && live.key === requestKey
? { ...live, application: updated }
: live);
});
catalogSaveQueue.current = save.catch(() => {});
return save;
};
return <div className="cg-app-frame-catalog"><AppFrame appName={application.name}
actions={<AppFrameMarks mark="catalog" connector="odoo" />}>
<CatalogApp definition={definition}
key={`${requestKey}::${requestGeneration.current}`}
database={database}
scope={{
filters: props.activeView?.config.filters ?? [],
filterConj: props.activeView?.config.filterConj ?? "and",
sorts: props.activeView?.config.sorts ?? [],
}}
onOpen={props.onOpen}
onData={props.onCatalogData}
editor={{
catalogs,
catalogSpec,
canEdit: application.capabilities?.edit === true,
onSave,
}}
/>
</AppFrame></div>;
}
if (surface === "route" && application) {
const titleKey = String(fieldMap.title ?? "");
const latitudeKey = String(fieldMap.latitude ?? "");
const longitudeKey = String(fieldMap.longitude ?? "");
const addressKey = String(fieldMap.address ?? "");
const routeField: Field = props.field ?? { key: titleKey, label: "Record title", type: "text", source: "odoo" };
const coordinateFields = latitudeKey && longitudeKey
? {
latitude: { ...routeField, key: latitudeKey, label: "Latitude" },
longitude: { ...routeField, key: longitudeKey, label: "Longitude" },
}
: props.coordinateFields;
// The general geocoder reads its address contract from coordField. An empty key carries that
// contract without pretending an address-only Application owns a coordinate column.
const routeCoordField = addressKey
? {
...(props.coordField ?? routeField),
key: props.coordField?.key ?? "",
label: props.coordField?.label ?? "Route location",
geocode: {
addressField: addressKey,
...(props.coordField?.geocode?.country
? { country: props.coordField.geocode.country }
: {}),
},
}
: props.coordField;
return (
<RouteApplicationMapView
key={application.id}
titleKey={titleKey || routeField.key}
applicationId={application.id}
props={{
...props,
field: titleKey ? { ...routeField, key: titleKey, label: "Record title" } : routeField,
coordinateFields,
coordField: routeCoordField,
applicationName: application.name,
geocodeSessionOnly: Boolean(addressKey),
routeApplication: true,
}}
Surface={MapViewSurface}
/>
);
}
if (!props.field) {
return <div className="cg-app-launch-state is-error" role="alert">The Map key field is unavailable.</div>;
}
return <MapViewSurface {...props} field={props.field} pinClickSelects />;
}
// ---------------------------------------------------------------------------
// customer-grid / MapView.tsx
// "Map" is a VIEW beside Grid/List/Calendar/Kanban, not a module: it projects
// the SAME pipeline output the grid paints, so the toolbar count, filters and
// sorts mean exactly what they mean on the grid; only the projection changes.
//
// Wave 8 grows it up (I2/I3/I5/I6, contracts C2/C3/C7):
// I2 wheel/pinch zoom, drag to pan, and a box-select that feeds the grid's
// OWN selection — so the existing "N selected · Add to cohort" bar serves
// the map with no second cohort picker to keep in sync.
// I3 colour pins by any single-select field (`display.colorField`) + legend.
// I5 size pins by any numeric/measure field (`display.sizeField`) + legend.
// I6 a less templatic picture: water wash, land fill, thin C1 strokes,
// graticule, hover halos.
//
// C7 CALL — NO map library, and that call still stands. C7 allowed maplibre-gl
// "with a self-hosted vector/raster-free style"; a tileless maplibre would have
// rendered exactly the geometry below for +230 KB gz on a 251 KB budget.
//
// ⭐⭐ WAVE 37 (R3/R14, W37-T35) — THE MAP NOW FETCHES TILES, AND THE OLD NOTE
// HERE SAID THE OPPOSITE. It read: "Nothing is fetched and no coordinate leaves
// the page unless the user deliberately clicks." That was true for two waves and
// is FALSE now, so it is rewritten rather than left to rot. What is true today:
//
// - a RASTER BASEMAP is fetched, by the browser, straight from the tile
// provider. Panning the map therefore tells that provider roughly where you
// are looking. It does NOT tell them who: no record, no name and no address
// is ever sent, because a tile request carries only a z/x/y grid square that
// millions of other people also request;
// - the provider is a SEAM, not a vendor. `/api/v1/geo/providers` serves a URL
// template plus a credit line, both environment-driven, so pointing this at
// a paid vendor is configuration and not a rewrite. That seam is the whole
// reason R14 could defer the Google key without dropping the feature;
// - the DEFAULT is OpenStreetMap, which needs no key and no billing account.
// Its credit line is a LICENCE TERM and is rendered, not optional;
// - GEOCODING is still not automatic and never will be from here (R3). It has
// its own door, it takes an explicit list of addresses, and it is rate
// limited in code. Nothing on this surface geocodes anything;
// - if the tiles fail to load, the vendored vector basemap below is still
// here and takes over. A map that has lost its network draws the coastline
// it always drew rather than an empty rectangle.
//
// Honesty rules (rule 8b), carried and extended:
// - rows WITHOUT coordinates are never silently hidden: the count line reads
// "N of M mapped", so the unmapped share is the gap between the two numbers;
// - a pin per row at its geocoded position, no clustering and no jitter (two
// customers at one address overlap rather than being drawn where they are
// not);
// - the colour legend STATES it when a field has more choices than the
// palette has entries, rather than recycling a colour onto a second meaning;
// - a row with no value under the size field gets the smallest dot and the
// legend says so — it is never dropped from the map.
// ---------------------------------------------------------------------------
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { LogoLoader } from "../ui/LogoLoader";
import type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent, ReactNode } from "react";
import type { CatalogSpec, Conjunction, Field, FilterNode, Row, ViewConfig } from "./types";
import { API_V1, CREDENTIALS, NAV_MINIMIZE_EVENT, signal } from "../apiContract";
import { formatDisplay } from "./cells";
import { readDataPath } from "./dataPath";
import { AppFrame } from "./AppFrame";
// C1: Routing and Catalog are Odoo Apps; verify_icons.py holds these two marks to TEMPLATES.
import { AppFrameMarks } from "../apps/templateMarks";
import { CatalogApp } from "../apps/catalog/CatalogApp";
import { RouteApplicationMapView } from "../apps/routing/RouteApplicationMapView";
import type { CatalogApplicationDefinition, CatalogViewSpec } from "./CatalogView";
import { applicationTemplateSurface } from "./viewModes";
import { LAND_PATH, LAKE_PATHS } from "./mapGeometry";
import { routingPreferenceKey, bubbleSizeRange, pointRadius, routeFilterSignatureOf } from "./routePrefs";
import type { RoutingCustomerDetail } from "./RouteNav";
import { RouteCustomerPane } from "./RouteNav";
import {
BASEMAP_DETAIL_K,
bubbleRadius,
magnitudeDomain,
cardBox,
clientToUser,
dashPattern,
fitView,
formatDuration,
fromScreen,
googleMapsUrl,
googleRouteUrls,
googleZoomForK,
graticuleOpacity,
hairline,
haversineKm,
isPlottable,
normRect,
parseLatLon,
pathBounds,
planRoute,
pointInPolygon,
project,
rotateAt,
routeFingerprint,
routeRanks,
ROUTE_STOP_CAP,
toScreen,