import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { ReactElement } from "react";
import { createPortal } from "react-dom";
import { FolderMark } from "./icons";
import {
formatSeconds, haversineKm, parseRouteAnswer, previewSeconds,
routeCaveats, routeSaving, routeTimeLabel, routeTimeTone,
} from "./mapProjection";
import type { GeoStop, RouteAnswer } from "./mapProjection";
import { AnchoredOverlay, BodyPortal } from "./OverlaySurface";
import { normalizedRouteMapLinks, routePrintStops, routeReversePrintLabels } from "./routeLinks";
import type { NormalizedRouteMapLink } from "./routeLinks";
import { routingPreferenceKey } from "./routePrefs";
import { submitRouteStopMove } from "./routeStopMove";
import { boundedGoogleMapsUrl } from "./routeZoneTypes";
import {
locatedRouteMovePlan,
mergeLocatedOrderAtAnchors,
routeLocationPartition,
routeApplicationPath,
routeStopIdentity,
RoutingStopLabelErrors,
} from "./routeZoneApi";
// W51-T28 / R6 + C8 — the wave-51 base kit's ONE confirm dialog. Consumed, never re-implemented.
import { TruncatedName } from "../home/TruncatedName";
import { ConfirmDialog } from "../ui/ConfirmDialog";
import { useEscapeClose } from "../ui/useEscapeClose";
import type {
MapRouteDto, MapRouteFolderDto, MapRouteSource, MapRouteUpdate, MapZoneDto,
RouteDeliveryRecipient, RouteDeliveryDto, RouteDeliveryRequest,
} from "./routeZoneTypes";
import "../styles/wave42/route-nav.css";
import "./route-nav.css";
import "../styles/wave46/route-print.css";
import "../styles/sdlc78/routing.css";
/** Google's own Maps mark from `public/brand/`, relative to the document as vite `base: "./"` makes
* every asset. No `import.meta` here: gates compile this file to CommonJS, where it is an error. */
export const GOOGLE_MAPS_MARK_SRC = "./brand/google-maps.svg";
/** The decorative 16 px Maps mark. The text beside it carries the name. */
export function GoogleMapsMark({ className = "cg-gmaps-mark" }: { className?: string }) {
return ;
}
type Result = Promise;
type RouteAction = "rename" | "duplicate" | "star" | "share" | "delete";
/* ═════════════════════════════ W46-T19 / INSTRUCTION 9 / R9 / C2 ═════════════════════════════
*
* The drive time at the top of the Route, the saving a reorder would win, and the number that
* moves while a stop is being dragged.
*
* ⛔⛔ THE DEBOUNCE IS A COURTESY LIMIT, NOT A NICETY. The door behind `ROUTE_DOOR` calls a free,
* unauthenticated public routing service, twice per request (the order as it stands, then the
* order it would choose), behind a process-wide 1100 ms throttle. One settled figure therefore
* costs at least 2.2 s of that service's time. A drag emits dozens of events a second, so the
* only safe wiring is the one C2 names: arithmetic during the drag, ONE request on drop, and
* every earlier request cancelled the moment a new drag starts, or a slow answer lands on an
* order nobody is looking at any more.
*/
/* ═════════════════════════════ W46-T20 / INSTRUCTION 10 / R6 / C6 ════════════════════════
*
* "ADD an export button for routes regardless to give to the sales team", plus R6's addition:
* "i also want the google map link clickable in that PDF."
*
* The export is the browser's own Save as PDF behind a print stylesheet, which is the pattern
* the catalog export already proves here. Set on `` for the duration of one print and
* taken off again however the dialog ends; `styles/wave46/route-print.css` carries the
* isolation keyed off it.
*
* ⛔ A NAME OF ITS OWN, NEVER `cg-cat-printing`. The catalog's print block un-hides exactly
* `.cg-cat-print-portal` and hides every other child of ``, so borrowing its class would
* print a blank sheet with nothing anywhere reporting a fault.
*/
const ROUTE_PRINTING_CLASS = "cg-w46-route-printing";
/** The honest backstop when neither `afterprint` nor the print media query reports an end. */
const PRINT_RELEASE_MS = 120_000;
const ROUTE_DOOR = "/api/v1/geo/route";
/**
* OWNER 2026-08-31 item 2 - the six defaults a new Route is stamped with, offered back as an
* edit. ⛔ THIS LIST IS A MIRROR OF `route_system.py::_ROUTE_COLORS` AND MUST STAY ONE. The
* server is the authority: `_color` falls back to `_ROUTE_COLORS[ordinal % len]` for anything
* `_COLOR_RE` refuses, so a swatch offered here that the server does not recognise would save
* as a different colour than the one the person pressed. The free picker beside them is why the
* list does not need to grow: it is a shortcut, not the vocabulary.
*/
const ROUTE_SWATCHES = ["#6E4AC7", "#1F4E78", "#C85A54", "#2F8F83", "#B57716", "#A14B8B"];
/** The rail's own top level, as a map key. A bare string keeps `foldersByParent` and
* `routesByFolder` one type instead of `Map`, and no folder id can collide
* with it: `route_system.py` mints folder ids, and none of them is empty. */
const ROOT_LEVEL = "";
/* ⛔ TWO DRAG TYPES, ONE PER ROW KIND, and that is the same discrimination `ViewSidebar` makes
with `FOLD_DRAG_TYPE` against a view's own channel. Sharing one channel would let a folder
dropped on a Route reorder the Routes, and the handler that fired first would decide which. */
const ROUTE_DRAG = "application/x-aios-route";
const ROUTE_FOLDER_DRAG = "application/x-aios-route-folder";
/** Owner item 3 - the ONE mark every Route row wears. Deliberately the SAME waypoint path
* `viewModes.tsx::IconRouteZone` draws, at the same 1.5 stroke: the toolbar button that opens
* this rail and the rows inside it are one family, and a second route glyph would read as two. */
function IconRoute() {
return (
);
}
const SETTLE_DEBOUNCE_MS = 400;
/** ⛔ BOTH HALVES OF THE FIGURE MUST ASK THE SAME QUESTION, or the number jumps on drop by the
* size of a closing edge and the reorder gets blamed for it. That is why the round-trip answer
* travels as ONE value into `previewSeconds` during the drag and into the request body on drop.
*
* ⭐⭐ 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"*. They are right, and the
* record says so in code: `MapView.tsx` holds `roundTrip` state whose only writer, `setRoundTrip`,
* sits in the retired `void []` compatibility list, so the value was pinned at false with no
* control anywhere. The solver (`mapProjection.ts::planRoute`, `twoOptOrder`, `tourLength`) and
* the server door (`routes_geo.py`, which reads `roundTrip` off the body) were both live the
* whole time. So this is a control being re-attached to an algorithm, not a feature being built.
* It is a PROP rather than local state because the map's drawn plan and this panel's timer must
* answer the same question; two copies is how they come to disagree. */
const ROUTE_MODE = "driving";
/**
* The order a drag would leave behind: `moved` taken out and put back where `over` sits now.
*
* ⛔ PURE, AND DELIBERATELY OUTSIDE THE COMPONENT. It is the only thing the drag path computes,
* so keeping it here makes "the drag calls no network" a property of a function that has no
* closure to hide one in.
*/
function orderAfterMove(pids: number[], moved: number, over: number): number[] {
const from = pids.indexOf(moved);
const to = pids.indexOf(over);
if (from < 0 || to < 0 || from === to) return pids;
const next = [...pids];
next.splice(to, 0, next.splice(from, 1)[0]);
return next;
}
function mayRouteAction(route: MapRouteDto, action: RouteAction): boolean {
return route.capabilities?.[action] === true;
}
export interface RoutingCustomerDetail {
pid: number;
name: string;
fields: { key: string; label: string; value: string }[];
}
function routingFieldUrl(value: string): string | null {
try {
const url = new URL(value);
return /^https?:\/\//i.test(value.trim()) && (url.protocol === "http:" || url.protocol === "https:")
? url.href : null;
} catch {
return null;
}
}
export function RouteCustomerPane({ detail, onBack }: {
detail: RoutingCustomerDetail | null;
onBack: () => void;
}) {
const pane = useRef(null);
const opener = useRef(null);
const previousPid = useRef(null);
const [closingPid, setClosingPid] = useState(null);
const closing = detail != null && closingPid === detail.pid;
const close = () => {
if (!detail) return;
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) onBack();
else setClosingPid(detail.pid);
};
useEscapeClose(detail != null, close, { container: () => pane.current });
useLayoutEffect(() => {
if (detail) {
const active = document.activeElement;
if ((active instanceof HTMLElement || active instanceof SVGElement) && !pane.current?.contains(active))
opener.current = active;
pane.current?.querySelector(".cg-routing-detail-back")?.focus({ preventScroll: true });
} else if (previousPid.current !== null && opener.current?.isConnected) {
opener.current.focus({ preventScroll: true });
}
previousPid.current = detail?.pid ?? null;
setClosingPid(null);
}, [detail?.pid]);
if (!detail) return null;
return {
if (event.target === event.currentTarget && closing) onBack();
}}>
;
}
export function RouteNav(props: Parameters[0]) {
return ;
}
function RouteNavContent({ routes, folders, selectedIds, activeRouteId, sources, storageKey,
createdRoute, onCreatedDismiss, onToggle, onActiveRouteChange, onOpenRecord, onCreate,
onMoveToOrder, onUpdate, onDuplicate, onDelete, onShare, onRouteMove, onRouteReorder, stopLabels = {},
stopCoords = {},
onFolderCreate, onFolderUpdate, onFolderDelete, onFolderReorder, onCreateStart, mapLinks, mapLinkRefusal, deliveries, onSchedule,
onDeleteDelivery, deliveryRecipients, deliveryRecipientError, onReloadDeliveryRecipients, zones = [],
roundTrip = false, onRoundTripChange, routeStartPid = null, routeEndPid = null, onRouteStartChange, onRouteEndChange, onStopAdded,
routesLoadError = false, onRetryRoutes,
applicationName = "", applicationId, routesLoaded = true }: {
routes: MapRouteDto[];
folders: MapRouteFolderDto[];
selectedIds: ReadonlySet;
activeRouteId: string | null;
sources: MapRouteSource[];
storageKey: string;
createdRoute: MapRouteDto | null;
onCreatedDismiss: () => void;
onToggle: (route: MapRouteDto) => void;
onActiveRouteChange: (routeId: string | null) => void;
onOpenRecord: (pid: number) => void;
/** Row-derived identity for every stop the host can name. Keyed by pid; both fields may be
* empty, and `routeStopIdentity` owns what is shown when they are.
* ⚠ OPTIONAL because this component also mounts in a render harness with no host grid behind
* it; MapView always supplies it. The default is `{}`, which routes every stop through
* `routeStopIdentity`'s final arm rather than rendering a blank. */
stopLabels?: Record;
/** W46-T19 — where each stop IS, keyed by pid, in the coordinates the host already geocoded.
* The drive time, the drag preview and the reorder offer all need a position rather than a
* name, and `stopLabels` deliberately carries neither.
* ⚠ OPTIONAL for the same reason `stopLabels` is: this component mounts in a render harness
* with no host grid behind it. An absent or partial map is stated on screen, never rounded
* down to a confident zero. */
stopCoords?: Record;
onCreate: (name: string, source: MapRouteSource) => Result;
onMoveToOrder: (route: MapRouteDto, customerPid: number, order: number) => Result;
onUpdate: (route: MapRouteDto, patch: MapRouteUpdate) => Result;
onDuplicate: (route: MapRouteDto) => Result;
onDelete: (route: MapRouteDto) => Promise;
onShare: (route: MapRouteDto) => Result;
onRouteMove: (route: MapRouteDto, folderId: string | null) => Result;
onRouteReorder: (order: string[]) => Result;
onFolderCreate: (name: string, parent: string | null) => Result;
onFolderUpdate: (folder: MapRouteFolderDto, patch: { name?: string; parent?: string | null }) => Result;
onFolderDelete: (folder: MapRouteFolderDto) => Result;
onFolderReorder: (order: string[]) => Result;
onCreateStart: () => void;
mapLinks: NormalizedRouteMapLink[];
mapLinkRefusal: string | null;
deliveries: RouteDeliveryDto[] | null;
deliveryRecipients: RouteDeliveryRecipient[] | null;
deliveryRecipientError: string | null;
onReloadDeliveryRecipients: () => void;
onSchedule: (route: MapRouteDto, request: RouteDeliveryRequest) => Result;
onDeleteDelivery: (route: MapRouteDto, delivery: RouteDeliveryDto) => Result;
/** D-599 / W46-T22 - the Zones this database has, so a Route can be put in one. The host
* already holds them to draw the map, so this is a pass-through and never a second fetch.
* ⚠ OPTIONAL with a `[]` default for the same reason `stopLabels` is: this component also
* mounts in a render harness with no host behind it. An empty list renders the selector
* disabled with a sentence, never a silently empty dropdown. */
zones?: MapZoneDto[];
/** Owner 2026-08-31 - one way, or back to where the driver started. Owned by the host so the
* map's drawn plan and this panel's drive time cannot answer different questions. */
roundTrip?: boolean;
onRoundTripChange?: (value: boolean) => void;
/** Planner endpoints are owned by MapView, so the rail cannot disagree with the drawn route. */
routeStartPid?: number | null;
routeEndPid?: number | null;
onRouteStartChange?: (pid: number | null) => void;
onRouteEndChange?: (pid: number | null) => void;
/** The Route the membership door answered with, so the host's read model gains the new stop
* without a second fetch. Mirrors what `moveNamedRouteStop` already does on a reorder. */
onStopAdded?: (route: MapRouteDto, applicationId?: string) => void;
/** Present only when this trusted route surface was launched by a saved Application. */
applicationName?: string;
applicationId?: string;
/** False until the first saved-Route read answers, so an empty list is not read as "none". */
routesLoaded?: boolean;
/** True when the last saved-Route read failed; the listed routes are the last good read. */
routesLoadError?: boolean;
onRetryRoutes?: () => void;
}) {
const stopLabelErrors = useContext(RoutingStopLabelErrors);
/* ⭐⭐ OWNER 2026-08-31 item 3 - THE ROUTES RAIL IS THE VIEWS RAIL, NOT A COUSIN OF IT.
Owner: *"I need the routes LIST navigation and the routes itself to have the exact same
interface just like how we have it with view, where you can just click it and drag it AND
its fucking compact. Make it the exact same layout. The only difference is the icon."* and,
in the grill: *"exactly like how Views rail is, with the +create for folder and find at the
top. Exactly the same. instead of number it should all just be the same Route icon."*
⛔ SO THE BREADCRUMB PATH IS GONE, AND THAT IS THE STRUCTURAL HALF OF THE ASK. A folder used
to be a place you NAVIGATED INTO (`levelAt` + `folderPath` + an `Up` button), which is a
different interaction from the Views rail's disclosure groups however similar the rows look.
Folders now open and shut in place, and the stored key holds the SHUT set rather than the
current level - so a person who never touches a folder sees every Route, which is the
behaviour a rail whose whole job is "pick one" should have.
⚠ THE ROW CLASSES ARE THE VIEWS RAIL'S OWN (`.cg-view-row`, `.cg-view-main`, `.cg-view-text`,
`.cg-view-name`, `.cg-view-more`, `.cg-fold*`, `.cg-create-new`, `.cg-find-view`), reused
rather than copied. Copying them into a `cg-w44-route-*` twin is how the two lists drift
apart again the first time either is polished, and "exact same layout" is a promise that
only a shared contract can keep. */
const routingAlive = useRef(true);
useEffect(() => {
routingAlive.current = true;
return () => { routingAlive.current = false; };
}, []);
const routePathKey = routingPreferenceKey(`aios-routes-shut-${storageKey}`, applicationId);
const [shutFolders, setShutFolders] = useState>(() => {
if (typeof window === "undefined") return new Set();
try {
const raw = window.localStorage.getItem(routePathKey);
const parsed = raw ? JSON.parse(raw) : null;
return new Set(Array.isArray(parsed) ? parsed.filter((id) => typeof id === "string") : []);
} catch { return new Set(); }
});
/** Owner item 3 - "find at the top". Local, never persisted: a search is a way of LOOKING at
* the rail, not a property of it, which is the rule `ViewSidebar`'s own box already follows. */
const [routeQuery, setRouteQuery] = useState("");
/* ═════════════════ W50-T10 / INSTRUCTION 9 — THE FOUR MENUS PORTAL NOW ═════════════════
*
* Owner: *"Clicking the '...' on each route (Duplicate/Star/Share/Delete) expands the whole
* thing, and it cannot be closed."* All four menus in this rail were in-flow `
`s toggled
* only by their own button: no outside-click dismiss, no Escape, no focus restore, and each one
* pushed the rows below it down as it opened. `AnchoredOverlay` owns all four behaviours
* already, so every one of them is now a portalled overlay instead.
*
* ⛔ THE ANCHOR RIDES IN THE STATE, AND IT IS READ FROM `event.currentTarget` IN THE HANDLER
* BODY — never inside the updater. React sets `currentTarget = null` the moment the handler
* returns, and a functional updater is re-invoked when React drains the queue, by which time it
* reads null and the overlay degrades to a zero-rect at the viewport origin. `ViewSidebar.tsx`
* carries the full account: that one line was the difference between its rail working and the
* whole app going white, reproduced on the shipped build by `_qa_live_rail.py` on 2026-08-04.
*
* ⚠ NO CSS CAME WITH THIS. `body > .cg-overlay` already sits at `--cg-z-overlay` (110), which
* outranks `--cg-z-mapchrome` (65) that the route popover stacks at, so a portalled menu is
* above it by construction. Minting a z token here would be a second answer to a solved
* question.
*/
const [createMenu, setCreateMenu] = useState<{ anchor: HTMLElement } | null>(null);
/** The row being carried, and the row it would land ABOVE. Same two marks the Views rail uses. */
const [rowDrag, setRowDrag] = useState(null);
const [rowOver, setRowOver] = useState(null);
const [creating, setCreating] = useState(false);
const [creatingFolder, setCreatingFolder] = useState(false);
const [name, setName] = useState("");
const [folderName, setFolderName] = useState("");
const [sourceId, setSourceId] = useState("selection");
const [error, setError] = useState(null);
const [orderErrors, setOrderErrors] = useState>({});
/** Owner 2026-08-31 - the add-record door's own two pieces of state. */
const [addStop, setAddStop] = useState<{ anchor: HTMLElement } | null>(null);
const [addStopQuery, setAddStopQuery] = useState("");
const [titleDraft, setTitleDraft] = useState(null);
const [editMapsUrl, setEditMapsUrl] = useState("");
/** D-599 - the Route's Zone, as a draft, saved by the same Save button as the Maps URL. */
const [editZoneId, setEditZoneId] = useState("");
/** OWNER 2026-08-31 item 2 - the Route's colour, as a draft, on the same Save button.
* Seeded from the record so the swatch a person sees selected is the colour the map draws. */
const [editColor, setEditColor] = useState(ROUTE_SWATCHES[0]);
const [deliveryRecipient, setDeliveryRecipient] = useState("");
const [deleteConfirm, setDeleteConfirm] = useState(false);
const [menu, setMenu] = useState<{ id: string; anchor: HTMLElement } | null>(null);
/* ⭐⭐ W51-T28 / R6 — THE PENDING DELETE IS HOISTED TO THE COMPONENT, AND THAT IS THE WHOLE
TRICK. Both row menus close themselves (`setMenu(null)`) in the same handler that used to
raise `window.confirm`, and each menu is a conditional subtree
(`{menu && menu.id === item.id && (`). A dialog rendered inside that
subtree unmounts in the same commit and the person sees nothing at all. So the menu records
WHAT was asked for, and the dialog is mounted from the component's own returned JSX, outside
every menu conditional and outside `renderLevel`.
⚠ ONE state serves both deletes because it is DISCRIMINATED. Two booleans would let a folder
delete and a route delete be pending at once, which is two dialogs on one screen. */
const [pendingDelete, setPendingDelete] = useState<
| { kind: "folder"; folder: MapRouteFolderDto }
| { kind: "route"; item: MapRouteDto }
| null
>(null);
const [renameId, setRenameId] = useState(null);
/** W54-T21 - raised by the rename's Escape claim so the blur it causes does not save. */
const renameEscaping = useRef(false);
const [busy, setBusy] = useState(false);
const [deliveryMapsPerLink, setDeliveryMapsPerLink] = useState(10);
const [deliveryNotice, setDeliveryNotice] = useState(null);
const [deliveryError, setDeliveryError] = useState(null);
const [deliveryBusy, setDeliveryBusy] = useState(false);
const [mapCopyNotice, setMapCopyNotice] = useState(null);
const [mapCopyError, setMapCopyError] = useState(null);
const route = activeRouteId ? routes.find((item) => item.id === activeRouteId) : null;
const rail = useRef(null);
// ⚠ The Routes list unmounts while a Route is open, so its scroll is kept here for Back.
const listScroll = useRef(0);
const previousRouteId = useRef(null);
useLayoutEffect(() => {
if (!applicationName) return;
const list = rail.current?.querySelector(".cg-route-index-scroll");
if (!route && previousRouteId.current !== null && list) list.scrollTop = listScroll.current;
previousRouteId.current = route?.id ?? null;
}, [applicationName, route?.id]);
const source = sources.find((item) => item.id === sourceId) || sources[0];
const mapsUrl = boundedGoogleMapsUrl(route?.mapsUrl);
/**
* W46-T22 / INSTRUCTION 19 — a stop can be taken OFF a Route from the Route itself.
*
* ⛔ THE WHOLE STOP LIST IS NEVER SUBMITTED. `visibleStopIds` is permission filtered on the
* server, so PATCHing it back as this Route's `stops` would silently drop every stop outside
* the reader's customer book. The membership door removes exactly one pid and re-densifies the
* rest, which is why it exists.
* ⛔ R14 (2026-09-03) MADE THIS ONE OF MEMBERSHIP'S TWO REMAINING DOORS. The map used to
* offer a third: clicking a pin with the Routes panel open raised an add-or-remove prompt
* on the same endpoint. That shortcut is retired, because it stole the plain click from
* opening the record. Membership is now this per-stop control and the `Add record` picker
* below, both of them visible, and both of them still calling `/stops/membership`.
*
* ⚠ THE HOST OWNS `namedRoutes` AND THIS COMPONENT HAS NO CALLBACK INTO IT, so a confirmed
* removal is held here until the host refetches. The set self-heals rather than going stale:
* it is keyed to one Route id, and any pid the host no longer reports is pruned, so a stop
* re-added through the `Add record` picker reappears instead of staying invisible.
*/
const [removedStops, setRemovedStops] = useState<{ routeId: string; pids: number[] }>(
{ routeId: "", pids: [] }
);
const activeStopIds = route?.visibleStopIds;
const activeStopRouteId = route?.id || "";
useEffect(() => {
const present = new Set(activeStopIds || []);
setRemovedStops((current) => {
if (current.routeId !== activeStopRouteId) return { routeId: activeStopRouteId, pids: [] };
const pids = current.pids.filter((pid) => present.has(pid));
return pids.length === current.pids.length ? current : { routeId: activeStopRouteId, pids };
});
}, [activeStopIds, activeStopRouteId]);
const stopIds = useMemo(
() => (activeStopIds || []).filter(
(pid) => !(removedStops.routeId === activeStopRouteId && removedStops.pids.includes(pid))
),
[activeStopIds, activeStopRouteId, removedStops]
);
/**
* ⭐ OWNER 2026-08-31 - the records the add-record dropdown may offer: everything in the book
* this panel already holds, minus what is already a stop.
*
* Every match remains reachable through the picker.
*/
const stopSet = useMemo(() => new Set(stopIds), [stopIds]);
const addStopMatches = useMemo(() => {
const needle = addStopQuery.trim().toLowerCase();
const out: { pid: number; label: string }[] = [];
for (const [key, value] of Object.entries(stopLabels)) {
const pid = Number(key);
if (!Number.isSafeInteger(pid) || stopSet.has(pid)) continue;
const label = routeStopIdentity(value, pid);
if (needle && !label.toLowerCase().includes(needle)) continue;
out.push({ pid, label });
}
// ⛔ A NAMELESS RECORD SORTS LAST, AND THIS IS A MEASUREMENT, NOT A PREFERENCE. Tenant #0's
// customer book carries 57 records whose name in Odoo is literally "?" (counted on the
// deployed staging build). Plain `localeCompare` puts "?" before every letter, so all 57
// filled the first fifty rows and the menu opened on nothing anybody could pick. A label
// with no letter or digit in it is a placeholder rather than a name, so it goes to the end;
// it is still offered, still searchable, and no record is hidden.
const named = (label: string) => /[\p{L}\p{N}]/u.test(label);
out.sort((a, b) => (Number(named(b.label)) - Number(named(a.label)))
|| a.label.localeCompare(b.label));
return out;
}, [addStopQuery, stopLabels, stopSet]);
const addableStops = addStopMatches;
const recipientNames = useMemo(
() => new Set((deliveryRecipients || []).map((person) => person.username)),
[deliveryRecipients]
);
const knownFolders = useMemo(() => new Set(folders.map((folder) => folder.id)), [folders]);
const deliveryTimezone = useMemo(() => {
try { return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; }
catch { return "UTC"; }
}, []);
/** Child folders of one parent, in their stored order. `ROOT_LEVEL` is the rail's own top. */
const foldersByParent = useMemo(() => {
const map = new Map();
for (const folder of folders) {
const parent = folder.parent && knownFolders.has(folder.parent) ? folder.parent : ROOT_LEVEL;
const bucket = map.get(parent);
if (bucket) bucket.push(folder); else map.set(parent, [folder]);
}
for (const bucket of map.values()) bucket.sort((a, b) => (a.order || 0) - (b.order || 0));
return map;
}, [folders, knownFolders]);
/** Routes filed in one folder, in their stored rail order. A Route whose folder this reader
* cannot see falls to the top level rather than disappearing. */
const routesByFolder = useMemo(() => {
const map = new Map();
for (const item of routes) {
const parent = item.folderId && knownFolders.has(item.folderId) ? item.folderId : ROOT_LEVEL;
const bucket = map.get(parent);
if (bucket) bucket.push(item); else map.set(parent, [item]);
}
for (const bucket of map.values()) bucket.sort((a, b) => (a.navOrder || 0) - (b.navOrder || 0));
return map;
}, [routes, knownFolders]);
/** ⚠ A FOLDER SURVIVES THE FIND BOX WHEN A DESCENDANT MATCHES, never only when its own name
* does. Hiding a folder whose contents match is how a search convinces somebody a Route has
* been deleted. `ViewSidebar` holds the same rule for its groups. */
const query = routeQuery.trim().toLowerCase();
const folderMatches = useMemo(() => {
const hit = new Set();
if (!query) return hit;
const walk = (parent: string): boolean => {
let found = (routesByFolder.get(parent) || []).some(
(item) => item.name.toLowerCase().includes(query)
);
for (const child of foldersByParent.get(parent) || []) {
const inside = walk(child.id);
if (inside || child.name.toLowerCase().includes(query)) { hit.add(child.id); found = true; }
}
return found;
};
walk(ROOT_LEVEL);
return hit;
}, [foldersByParent, query, routesByFolder]);
const toggleFolder = (folderId: string) => {
setMenu(null);
setShutFolders((current) => {
const next = new Set(current);
if (next.has(folderId)) next.delete(folderId); else next.add(folderId);
try { window.localStorage.setItem(routePathKey, JSON.stringify([...next])); }
catch { /* The rail still opens and shuts when storage is unavailable. */ }
return next;
});
};
useEffect(() => {
setTitleDraft(null);
setEditMapsUrl(route?.mapsUrl || "");
setEditZoneId(route?.zoneId || "");
setEditColor((route?.color || ROUTE_SWATCHES[0]).toUpperCase());
setOrderErrors({});
setDeleteConfirm(false);
setError(null);
setDeliveryNotice(null);
setDeliveryError(null);
setMapCopyNotice(null);
setMapCopyError(null);
}, [route?.id, route?.mapsUrl, route?.name, route?.zoneId]);
useEffect(() => { setDeliveryRecipient(""); }, [route?.id]);
const copyMapLinks = () => {
setMapCopyNotice(null);
setMapCopyError(null);
const clipboard = typeof navigator === "undefined" ? null : navigator.clipboard;
if (!shownMapLinks.length || !clipboard?.writeText) {
setMapCopyError("Maps links could not be copied in this browser.");
return;
}
void clipboard.writeText(shownMapLinks.map((link) => link.url).join("\n"))
.then(() => setMapCopyNotice(
`${shownMapLinks.length.toLocaleString()} Maps link${shownMapLinks.length === 1 ? "" : "s"} copied.`
))
.catch(() => setMapCopyError("Maps links could not be copied. Open each link instead."));
};
const scheduleDelivery = (target: MapRouteDto) => {
const recipient = deliveryRecipient;
if (!recipient || !recipientNames.has(recipient)) {
setDeliveryError("Choose an active delivery recipient.");
return;
}
setDeliveryBusy(true);
setDeliveryError(null);
setDeliveryNotice(null);
void onSchedule(target, {
recipient,
timezone: deliveryTimezone,
mapsPerLink: deliveryMapsPerLink,
}).then((message) => {
if (message) setDeliveryError(message);
else setDeliveryNotice(`${target.name} will be delivered to ${recipient} daily at 08:00.`);
}).finally(() => setDeliveryBusy(false));
};
const removeDelivery = (target: MapRouteDto, delivery: RouteDeliveryDto) => {
setDeliveryBusy(true);
setDeliveryError(null);
setDeliveryNotice(null);
void onDeleteDelivery(target, delivery).then((message) => {
if (message) setDeliveryError(message);
else setDeliveryNotice(`${delivery.name} was removed.`);
}).finally(() => setDeliveryBusy(false));
};
const finish = (operation: Result) => {
setBusy(true);
void operation.then(setError).finally(() => setBusy(false));
};
const commitStopMove = (target: MapRouteDto, pid: number, raw: string) => {
holdTimerCard(true);
setBusy(true);
setOrderErrors((current) => {
const next = { ...current };
delete next[pid];
return next;
});
void submitRouteStopMove(target, pid, raw, onMoveToOrder).then((result) => {
if (result.error) {
const message = result.error;
setOrderErrors((current) => ({ ...current, [pid]: message }));
setTimerHold(null);
return;
}
setOrderErrors((current) => {
const next = { ...current };
delete next[pid];
return next;
});
}).finally(() => setBusy(false));
};
/**
* Put ONE record onto this Route, through the same membership door the x uses.
*
* ⛔ NO OPTIMISTIC ROW. The server answers with the whole Route and `onMoveToOrder`'s host
* already replaces the record from that answer; painting a stop locally first would show a
* position the server has not agreed to, and a refusal would then have to un-paint it.
*/
const commitStopAdd = (target: MapRouteDto, pid: number) => {
setBusy(true);
setError(null);
void (async () => {
try {
const res = await fetch(
routeApplicationPath(`/api/v1/customers/routes/${encodeURIComponent(target.id)}/stops/membership`, applicationId),
{
method: "POST", credentials: "same-origin",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ customerPid: pid, present: true }),
}
);
const payload = await res.json().catch(() => null);
if (!routingAlive.current) return;
if (!res.ok) {
setError(payload?.error?.message || payload?.detail?.message
|| "That record could not be added to this Route.");
return;
}
// The removal ledger is what hides a stop this session took OFF the Route. Adding the
// same record back has to clear its entry, or the row the server just returned would be
// filtered straight back out and the button would look broken.
setRemovedStops((current) => current.routeId === target.id
? { routeId: target.id, pids: current.pids.filter((item) => item !== pid) }
: current);
const routeUpdate = payload?.route as MapRouteDto | undefined;
if (routeUpdate) onStopAdded?.(routeUpdate, applicationId);
} catch {
setError("That record could not be added to this Route.");
} finally {
setBusy(false);
}
})();
};
const commitStopRemove = (target: MapRouteDto, pid: number) => {
setBusy(true);
setOrderErrors((current) => {
const next = { ...current };
delete next[pid];
return next;
});
void (async () => {
try {
const res = await fetch(
routeApplicationPath(`/api/v1/customers/routes/${encodeURIComponent(target.id)}/stops/membership`, applicationId),
{
method: "POST", credentials: "same-origin",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ customerPid: pid, present: false }),
}
);
const payload = await res.json().catch(() => null);
if (!routingAlive.current) return;
if (!res.ok) {
const message = payload?.error?.message || payload?.detail?.message
|| "This stop could not be removed.";
setOrderErrors((current) => ({ ...current, [pid]: message }));
return;
}
setRemovedStops((current) => current.routeId === target.id
? (current.pids.includes(pid) ? current : { routeId: target.id, pids: [...current.pids, pid] })
: { routeId: target.id, pids: [pid] });
} catch {
setOrderErrors((current) => ({ ...current, [pid]: "This stop could not be removed." }));
} finally {
setBusy(false);
}
})();
};
/* ── W46-T19: the drive time, the saving, and the number that moves during a drag ─────────
The whole feature is state and arithmetic here, and exactly one request, so that the two
numbers on screen can never come from two different questions. */
const [routeAnswer, setRouteAnswer] = useState(null);
const [timerError, setTimerError] = useState(null);
const [timerBusy, setTimerBusy] = useState(false);
const [applyBusy, setApplyBusy] = useState(false);
const [dragPid, setDragPid] = useState(null);
const [dragOrder, setDragOrder] = useState(null);
const [dragSeconds, setDragSeconds] = useState(null);
/* S78-T08: the timer card keeps its pre-move height from a stop's pickup until the new drive
time settles, so the stop list below it never jumps on drop or on Alt + Up / Alt + Down. */
const timerCardRef = useRef(null);
const [timerHold, setTimerHold] = useState<
{ height: number; from: RouteAnswer | null; committed: boolean } | null>(null);
const holdTimerCard = (committed: boolean) => {
const height = timerCardRef.current?.getBoundingClientRect().height ?? 0;
setTimerHold((current) => current ? { ...current, committed: current.committed || committed }
: height > 0 ? { height, from: routeAnswer, committed } : null);
};
/** W46-T20 — true only while one print is in flight. The printed sheet is mounted on
* `document.body` for exactly that long, so it costs nothing the rest of the time and can
* never be a second copy of the Route sitting invisibly in the panel. */
const [printing, setPrinting] = useState(false);
/** A reverse label is prepared before mounting the print portal, never requested from a
* browser/provider during print. The server may answer unavailable; that remains printable. */
const [preparingPrint, setPreparingPrint] = useState(false);
const [reversePrintLabels, setReversePrintLabels] = useState>({});
/** ⚠ A LATCH, BECAUSE `window.print()` MUST HAPPEN ONCE. React's development strict mode
* invokes an effect twice; without this the dialog opens, closes, and opens again. */
const printLatch = useRef(false);
/** The in-flight print's own release, held so an unmount can take the printing class back
* off `` without the effect needing a teardown of its own (see below). */
const releasePrint = useRef<(() => void) | null>(null);
useEffect(() => () => { releasePrint.current?.(); }, []);
/**
* W46-T20 — open the print dialog once the printed sheet is in the document, and give the
* app back to the person however the dialog ends.
*
* THREE WAYS OUT, because none of them is reliable alone: `afterprint` (which does not fire
* on a cancelled dialog in every engine), the `print` media query going false (Safari's
* route), and a timeout (the honest backstop). `finish` is idempotent, so whichever arrives
* first wins. Leaving the class on would hide the entire app behind a print rule.
*
* ⛔⛔ THIS EFFECT DELIBERATELY RETURNS NO TEARDOWN, AND THAT IS THE WHOLE FIX. A cleanup
* that cancelled the queued frame would run IMMEDIATELY under development strict mode, which
* mounts, tears down and mounts again: the frame would be cancelled before it ever fired and
* the Export button would silently do nothing in dev while working in production, which is
* the worst shape a defect can take. The latch above makes the second invocation a no-op
* instead, `finish` is the only teardown there is, and `releasePrint` above hands an unmount
* the same exit so the printing class can never be left behind.
*/
useEffect(() => {
if (!printing || printLatch.current) return;
printLatch.current = true;
const root = document.documentElement;
const media = window.matchMedia ? window.matchMedia("print") : null;
let done = false;
let timer: ReturnType | undefined;
function finish() {
if (done) return;
done = true;
root.classList.remove(ROUTE_PRINTING_CLASS);
window.removeEventListener("afterprint", finish);
media?.removeEventListener?.("change", onMedia);
if (timer !== undefined) clearTimeout(timer);
printLatch.current = false;
releasePrint.current = null;
setPrinting(false);
}
function onMedia(event: MediaQueryListEvent) {
if (!event.matches) finish();
}
releasePrint.current = finish;
root.classList.add(ROUTE_PRINTING_CLASS);
window.addEventListener("afterprint", finish);
media?.addEventListener?.("change", onMedia);
timer = setTimeout(finish, PRINT_RELEASE_MS);
// One frame, so the sheet has been laid out under the print rules before the engine
// snapshots it. Chrome blocks inside `print()` until the dialog closes; Firefox returns
// immediately. Both ends are handled above. `done` is re-read here because an unmount in
// that one frame has already released the print, and a dialog opened after the sheet was
// removed would print a blank page.
window.requestAnimationFrame(() => {
if (done) return;
try { window.print(); } catch { finish(); }
});
}, [printing]);
const settleTimer = useRef(null);
const settleAbort = useRef(null);
const settleGeneration = useRef(0);
/** C1 keeps both halves explicit: a missing coordinate is a named fixed anchor, never a stop
* silently omitted from either the UI or the apply merge. */
const locationPartition = useMemo(
() => routeLocationPartition(stopIds, stopLabels, stopCoords),
[stopIds, stopLabels, stopCoords],
);
const locatedStops = locationPartition.located;
const locatedPids = locationPartition.locatedPids;
const unlocated = locationPartition.unlocated;
/**
* ⭐⭐ W46-T22 / W46-T20 — THE MAPS LINKS MUST NOT OUTLIVE A REMOVED STOP.
*
* `mapLinks` and `mapLinkRefusal` are computed by MapView from the route's SERVER stop list, and
* removing a stop writes only `removedStops` here: the host is never told, so until
* `loadNamedRoutes` next fires the Google Maps section would still list, and Copy Maps links
* would still copy, a customer the person has just removed. The printed PDF is already safe
* because `routePrintStops` reads the pruned `stopIds`, and that is exactly why this one is
* worth closing: the two hand-offs a rep actually leaves the building with would otherwise
* DISAGREE about who is on the route.
*
* ⚠ Recomputed ONLY while a removal is pending. With none pending the host's own value is used
* verbatim, so the normal path keeps MapView's `coarsePointer` and this cannot drift from it.
*/
const removalPending = removedStops.routeId === activeStopRouteId && removedStops.pids.length > 0;
const prunedMapLinks = useMemo(
() => (removalPending ? normalizedRouteMapLinks(stopIds, locatedStops) : null),
[removalPending, stopIds, locatedStops]
);
const shownMapLinks = prunedMapLinks ? prunedMapLinks.links : mapLinks;
const shownMapLinkRefusal = prunedMapLinks ? prunedMapLinks.refusal : mapLinkRefusal;
const startUnavailable = routeStartPid !== null && !locatedPids.includes(routeStartPid);
const endUnavailable = routeEndPid !== null && !locatedPids.includes(routeEndPid);
const endpointChoicesReady = locatedPids.length >= 2;
// Endpoint and trip-shape choices change the route just as surely as a drag does. Include
// them in the debounce key so a chosen end cannot leave the previous open-path timing visible.
const timerKey = `${activeStopRouteId}:${locatedPids.join(",")}:${unlocated.map((stop) => `${stop.pid}:${stop.reason}`).join("|")}:${roundTrip ? "round" : "one"}:${routeStartPid ?? ""}:${roundTrip ? "" : routeEndPid ?? ""}`;
/**
* The number a drag moves. ⛔ ARITHMETIC ONLY: `previewSeconds` is `tourLength` over
* coordinates already on screen, so this runs at pointer speed and costs nothing. Nothing in
* this function, or in the two handlers that call it, may reach the network.
*/
const dragPreviewSeconds = (pids: number[]): number | null => {
if (locatedStops.length < 2) return null;
const seat = new Map(locatedStops.map((stop, index) => [stop.pid, index]));
const order: number[] = [];
for (const pid of pids) {
const index = seat.get(pid);
if (index !== undefined) order.push(index);
}
if (order.length < 2) return null;
const geo: GeoStop[] = locatedStops.map((stop) => ({ lat: stop.lat, lon: stop.lon }));
return previewSeconds(order, geo, haversineKm, roundTrip);
};
const cancelSettle = () => {
if (settleTimer.current !== null) {
window.clearTimeout(settleTimer.current);
settleTimer.current = null;
}
settleAbort.current?.abort();
settleAbort.current = null;
};
/** The one request. It is never called from a drag; only from the debounced timer below. */
const settleRoute = async (pids: number[]) => {
const byPid = new Map(locatedStops.map((stop) => [stop.pid, stop]));
const stops = pids.map((pid) => byPid.get(pid)).filter(Boolean)
.map((stop) => ({ lat: stop!.lat, lon: stop!.lon, pid: stop!.pid }));
if (stops.length < 2) {
setRouteAnswer(null);
return;
}
const controller = new AbortController();
settleAbort.current = controller;
const generation = settleGeneration.current + 1;
settleGeneration.current = generation;
setTimerBusy(true);
setTimerError(null);
try {
const res = await fetch(routeApplicationPath(ROUTE_DOOR, applicationId), {
method: "POST", credentials: "same-origin",
headers: { "Content-Type": "application/json" },
signal: controller.signal,
// ⛔ `pid` PER STOP IS LOAD-BEARING: without it the door answers with seat indices and
// the one-click apply has no record to move. `fallback: true` is what makes an
// arithmetic answer come back as `source: "haversine"` instead of an error.
body: JSON.stringify({
stops,
locatedPids: pids,
unlocated,
mode: ROUTE_MODE,
roundTrip,
fallback: true,
// The server owns the exact closing leg and constrained optimization. Pids make the
// selection stable across an order update; coordinates alone would turn it into seats.
startPid: routeStartPid ?? undefined,
endPid: roundTrip ? undefined : routeEndPid ?? undefined,
}),
});
const payload = await res.json().catch(() => null);
if (!routingAlive.current) return;
if (settleGeneration.current !== generation) return;
const answer = res.ok ? parseRouteAnswer(payload) : null;
if (!answer) {
setRouteAnswer(null);
setTimerError(payload?.error?.message || "This Route could not be timed just now.");
return;
}
setRouteAnswer(answer);
} catch (failure) {
if ((failure as { name?: string } | null)?.name === "AbortError") return;
if (settleGeneration.current !== generation) return;
setRouteAnswer(null);
setTimerError("This Route could not be timed just now.");
} finally {
if (settleGeneration.current === generation) setTimerBusy(false);
}
};
const scheduleSettle = (pids: number[]) => {
cancelSettle();
settleTimer.current = window.setTimeout(() => {
settleTimer.current = null;
void settleRoute(pids);
}, SETTLE_DEBOUNCE_MS);
};
useEffect(() => {
setRouteAnswer(null);
setTimerError(null);
if (locatedPids.length < 2) {
cancelSettle();
return;
}
scheduleSettle(locatedPids);
return () => cancelSettle();
// The key already carries the Route and its located stops in order; the callbacks below are
// recreated every render and would restart the request on every keystroke elsewhere.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [timerKey]);
const beginStopDrag = (pid: number) => {
holdTimerCard(false);
cancelSettle();
setDragPid(pid);
setDragOrder(stopIds);
setDragSeconds(dragPreviewSeconds(stopIds));
};
const previewStopDrag = (overPid: number) => {
const moved = dragPid;
if (moved === null || moved === overPid) return;
const base = dragOrder || stopIds;
const next = orderAfterMove(base, moved, overPid);
if (next === base) return;
setDragOrder(next);
setDragSeconds(dragPreviewSeconds(next));
};
const endStopDrag = () => {
setDragPid(null);
setDragOrder(null);
setDragSeconds(null);
};
const dropStopDrag = (target: MapRouteDto, overPid: number) => {
const moved = dragPid;
const order = moved === null ? null : orderAfterMove(dragOrder || stopIds, moved, overPid);
endStopDrag();
if (moved === null || !order) return;
const seat = order.indexOf(moved);
if (seat < 0 || stopIds[seat] === moved) return;
commitStopMove(target, moved, String(seat + 1));
scheduleSettle(order.filter((pid) => locatedPids.includes(pid)));
};
// A committed hold ends when the move has landed and a new drive time has settled. The timer
// bounds it when no new answer comes (a refused move, fewer than two located stops).
useEffect(() => {
if (!timerHold?.committed) return;
if (!busy && !timerBusy && routeAnswer !== null && routeAnswer !== timerHold.from) {
setTimerHold(null);
return;
}
const timer = window.setTimeout(() => setTimerHold(null), 8000);
return () => window.clearTimeout(timer);
}, [timerHold, busy, timerBusy, routeAnswer]);
/** One click fills only the Route's located slots with the optimized located permutation. */
const applyOptimizedOrder = (target: MapRouteDto) => {
const answer = routeAnswer;
if (!answer || applyBusy) return;
const merged = mergeLocatedOrderAtAnchors(
stopIds,
locatedPids,
answer.optimized.ordered,
);
const moves = merged && locatedRouteMovePlan(stopIds, merged, locatedPids);
if (!merged || !moves) {
setTimerError("The faster order no longer matches this Route's located stops.");
return;
}
setApplyBusy(true);
setTimerError(null);
void (async () => {
let failed = false;
for (const move of moves) {
const message = await onMoveToOrder(target, move.pid, move.position);
if (message) {
setTimerError(message);
failed = true;
break;
}
}
setApplyBusy(false);
if (!failed) scheduleSettle(answer.optimized.ordered);
})();
};
const dragging = dragOrder !== null;
const timerSaving = routeAnswer ? routeSaving(routeAnswer) : null;
const timerCaveats = routeAnswer ? routeCaveats(routeAnswer) : [];
const shownSeconds = dragging ? dragSeconds : dragPreviewSeconds(stopIds);
const settledLabel = routeAnswer ? routeTimeLabel(routeAnswer.current) : null;
const estimateLabel = shownSeconds === null ? null : `${formatSeconds(shownSeconds)} estimated`;
const timerLabel = !dragging && settledLabel ? settledLabel : estimateLabel;
const timerTone = !dragging && routeAnswer ? routeTimeTone(routeAnswer.current) : "estimated";
/* ═════════ W51-T28 / C8 — ESCAPE BACKS OUT OF AN OPEN SAVED ROUTE ══════════════════════
*
* ⭐ THE LADDER THIS COMPLETES, TOP DOWN: the kit dialog, then the open Route, then the map
* NAVIGATOR itself. The third rung is genuinely unreachable from this file and from MapView:
* `mapNavigator === "routes"` is `routePanelOpen && !zoneNavigatorOpen`, and `routePanelOpen`
* is `useState` in `CustomerGrid.tsx:3206` handed down as a read-only prop with no close
* callback and no event channel. An optional prop nobody passes, or a client-side emit with no
* listener, would each look exactly like a working close to a source scan while doing nothing
* at all, so neither is here and no gate leg claims the rung.
*
* ⛔ THE CLAIM IS DROPPED WHILE THE TITLE IS BEING RENAMED, and that is not fussiness. The
* arbiter's listener is CAPTURE PHASE on `document` and calls `stopPropagation`, so it runs
* ahead of React's own handlers and the rename input's `Escape`-cancels-the-draft would simply
* never fire again. Standing down while `titleDraft` is live leaves that behaviour exactly as
* it shipped, and one Escape still means one close everywhere else.
*
* ⛔ `!deleteConfirm` IS THE SAME RULE APPLIED TO THE OTHER LIVE OVERLAY IN THIS PANEL. The
* inline `role="alertdialog"` delete confirm below does not register with the arbiter and is
* deliberately left as it is, because `verify_w44_map_routes.py`'s `route-update-delete` leg
* pins that markup. Without this term Escape would resolve past it and close the whole Route
* out from under an open confirm, which is a behaviour this ticket would have INTRODUCED.
* ⚠ AND IT IS REACHED, THOUGH A GREP SAYS OTHERWISE. `grep deleteConfirm` finds no setter,
* because the setter is `setDeleteConfirm` and the capital D breaks the substring; `Delete
* Route` calls it, so that confirm really does open.
*
* ⚠ `cancelEditFirst` STAYS FALSE, matching the two Zone panels. One press, one close, which is
* what every other overlay in this app already does.
*/
const backToRoutes = useCallback(() => onActiveRouteChange(null), [onActiveRouteChange]);
useEscapeClose(route !== null && titleDraft === null && !deleteConfirm, backToRoutes);
/* ═════════ W54-T21 / D-673 — THE RUNGS THAT USED TO BE COVERED BY SILENCE ═══════════════
*
* ⛔⛔ THE STAND-DOWNS ABOVE ONLY WORKED WHILE NOTHING ELSE CLAIMED ESCAPE. Standing down means
* "let the key fall through", and until this ticket it fell through to NOBODY, so React's own
* handlers on the rename input and the search box still saw it and the delete confirm simply
* ignored the press. D-673 puts a claim UNDERNEATH this whole panel - `CustomerGrid.tsx` closes
* the navigator - so a fall-through now closes the entire navigator instead. Every surface the
* open Route stands down for therefore has to claim the key itself, or the press it was meant
* to reach would take the panel down with it.
*
* The route's close claim precedes these edit claims so the topmost edit receives Escape.
*
* ⚠ `renameEscaping` IS THE SAME ORDERING PROBLEM THE SHEET'S FORMULA EDITOR HAS. The arbiter
* blurs the focused element before it calls close, and the folder rename input's blur is what
* SAVES the new name, so a bare claim would have made Escape commit a rename it was pressed to
* cancel. The blur defers its decision by one microtask and this flag, raised by the close,
* wins that race by construction rather than by luck.
*
* ⚠ THE QUERY RUNG IS THE ONE BEHAVIOUR CHANGE, AND IT IS THE SMALL ONE. Escape with a typed
* route filter clears the filter and leaves the panel open, which is what the box's own
* handler always did; with the box empty there is nothing to clear and the press reaches the
* navigator's close. The box keeps its own handler because `verify_map.py` pins it.
*/
useEscapeClose(titleDraft !== null, () => setTitleDraft(null));
useEscapeClose(deleteConfirm, () => setDeleteConfirm(false));
useEscapeClose(renameId !== null, () => {
renameEscaping.current = true;
setRenameId(null);
});
useEscapeClose(routeQuery !== "", () => setRouteQuery(""));
const routeDetail = () => {
if (!route) return null;
// ⭐ W46-T25 / RULING R2's guard stood here: a Route projected from a legacy `route_order`
// column was refused until an administrator migrated it, because unlocking an unmigrated one
// would leave two divergent copies. R2's order was migrate, verify, unlock, delete — and it
// has now run to the end on every tenant schema, so there is no unmigrated Route left to
// refuse and no legacy column left behind one.
const canEdit = route.permission.canEdit;
// ⚠ POSITIONS ARE READ OFF THE LIST THE PERSON IS LOOKING AT. Earlier, Later and the typed
// Position box are all ordinal, and `routeStopMovePlan` validates against the ids it is
// handed, so a just-removed stop still counted here would make every arrow below it move the
// wrong stop for as long as the host had not refetched.
const stopView: MapRouteDto = { ...route, visibleStopIds: stopIds };
const editActionReason = !canEdit
? "Only the owner or an editor of the source View can change this Route."
: busy
? "Wait for the current Route update to finish."
: null;
const applyActionReason = editActionReason
|| (applyBusy ? "The faster order is being applied."
: locatedPids.length < 2 ? "Add map locations to at least two stops before optimizing."
: timerBusy ? "The located stops are still being measured."
: !routeAnswer ? "A measured route is needed before a faster order can be applied."
: !timerSaving?.offer ? "The current located order is already the fastest measured order."
: null);
// ⚠ THE LIST SHOWS THE DRAG, THE ROUTE STILL HOLDS THE SAVED ORDER. `stopView` above is
// built from `stopIds` on purpose: a drop is validated against the order the server last
// confirmed, never against the arrangement being previewed on screen.
const displayIds = dragOrder || stopIds;
// ⚠ THE SAVED ORDER, NOT THE DRAG PREVIEW. A sheet handed to a rep states what the Route
// IS, and `stopIds` is the order the server last confirmed. `routeStopIdentity` is passed in so
// the name on paper is the same function as the name on screen, and every stop is on the
// page whether or not it has a coordinate.
const printStops = routePrintStops(
stopIds, stopLabels, stopCoords,
(label, pid) => routeStopIdentity(label, pid, stopLabelErrors[pid]), reversePrintLabels,
);
// ⚠ THE NAME HAS EXACTLY ONE WRITER NOW. `Save` below sends only the Maps URL, so an
// abandoned draft in the title can never be committed by a control that says nothing about
// names, and a saved rename can never be overwritten by a stale copy of the old one.
const commitRouteRename = () => {
const next = (titleDraft || "").trim();
if (!next || busy) return;
if (next === route.name) { setTitleDraft(null); return; }
setBusy(true);
void onUpdate(route, { name: next }).then((message) => {
setError(message);
if (!message) setTitleDraft(null);
}).finally(() => setBusy(false));
};
return (
{/* ── W46-T23 / INSTRUCTION 19: THE ONE PLACE A ROUTE IS RENAMED. ──────────────
It used to be two: the row menu on the list, and a "Route name" box buried in the
edit block far below. Both are gone. The title itself turns into the field, so what
a person reads when they are not renaming is still a title. */}
{route.shared ? `Shared by ${route.owner || "another user"}` : route.sharedOut ? "Shared with others" : "Private"}
{/* ── W46-T19 / R9: the timer sits at the TOP, above the stops it is about. ─────────
The figure is muted and says "estimated" until a road answer settles, per C2, and
every caveat the answer carries is placed here rather than dropped. */}
{timerLabel || "No drive time yet"}
{dragging ? "While this stop moves"
: timerBusy ? "Measuring the drive"
: timerLabel ? "Drive time" : "Add two located stops"}
{/* ⭐⭐ OWNER 2026-08-31 - ONE WAY, OR BACK TO THE START. It sits INSIDE the timer,
against the figure it changes, because a round trip adds the closing edge and
therefore a different number; a control for it anywhere else would move a number
the reader is not looking at. */}
{onRoundTripChange && (
Trip
)}
{(onRouteStartChange || onRouteEndChange) && (
)}
{unlocated.length > 0 && (
Optimization covers {locatedPids.length.toLocaleString()} located stop{locatedPids.length === 1 ? "" : "s"}.
The {unlocated.length.toLocaleString()} named stop{unlocated.length === 1 ? "" : "s"} without a usable map location
stay at their current positions and are listed below.
)}
{/* S78-T08: a drag hides the apply block but keeps its box, so the stop list under the
pointer does not jump up when a stop is picked up. */}
Reordering {unlocated.length ? "the located stops" : "these stops"} saves {formatSeconds(timerSaving.seconds)}, about{" "}
{Math.abs(timerSaving.percent)}% of the drive.
Reordering {unlocated.length ? "the located stops" : "these stops"} would add {formatSeconds(timerSaving.seconds)} on the road,
so the current located order is the faster one.
)}
{timerCaveats.map((caveat) => (
{caveat}
))}
{timerError &&
{timerError}
}
{/* During a stop move the busy reason stays announced but takes no line, so the list holds. */}
{editActionReason && (
{editActionReason}
)}
{/* S63-T01: the primary action region ends before this independently scrolling list. */}
{/* ⭐⭐ OWNER 2026-08-31 - THE STOP LIST IS THE RAIL, SAME FORMATTING.
Owner: *"Same as the rail, same formatting too i believe"*, and then the exact scope:
*"The only difference with the rail is that route you can have an x button to remove a
record, and also an add record button where it provides the dropdown for the user to
add more customer to the route."* So the row wears `.cg-view-row` / `.cg-view-main` /
`.cg-view-text` / `.cg-view-name` exactly as a Route row does, drags whole rather than
by a grip, and carries the ordinal in the purple disc where the rail carries the Route
mark. The `` stays an ``: a drive IS an ordered list, and the class the panel's
own stylesheet targets rides alongside the rail's. */}
{stopIds.length ? (
{displayIds.map((pid, index) => (
{
if (!canEdit) return;
// S78-T08: a name tip opened by the press closes before the row moves.
const main = event.currentTarget.querySelector(".cg-view-main");
main?.dispatchEvent(new PointerEvent("pointerleave"));
if (main && document.activeElement === main) main.blur();
event.dataTransfer.effectAllowed = "move";
try { event.dataTransfer.setData("text/plain", String(pid)); }
catch { /* Some browsers refuse a payload; the drag still works. */ }
beginStopDrag(pid);
}}
onDragEnd={() => {
endStopDrag();
setTimerHold((current) => current && !current.committed ? null : current);
}}
onDragOver={(event) => {
if (dragPid === null) return;
event.preventDefault();
previewStopDrag(pid);
}}
onDrop={(event) => {
if (dragPid === null) return;
event.preventDefault();
dropStopDrag(stopView, pid);
}}>
{/* ⭐⭐ D-619 CLOSED WITHOUT REOPENING WHAT THE OWNER REMOVED. Deleting the per-stop
`< >` and the typed Position took the only KEYBOARD reorder with them, because
the drag grip is pointer-only. The owner's instruction was that drag replaces
those CONTROLS, not that reordering becomes pointer-only, so the gesture moves
onto the row's EXISTING focusable element: Alt + Up / Alt + Down, calling the
same `commitStopMove` the arrows called, with the same `stopView` target that
keeps a pruned list honest. No new tab stop, no new control, nothing wider.
⛔ ALT IS DELIBERATE. A bare ArrowUp/ArrowDown inside a scrolling panel is the
reader moving through the list, and stealing it would make the list impossible
to walk. `aria-keyshortcuts` is what announces the pair. */}
{/* ⛔ OWNER 2026-08-31, TWICE: *"the < > for the route panel where you can choose
the numbers i thought they're deleted. I still see them up"*. Move earlier,
Position, Move and Move later are gone; DRAG IS THE GESTURE, exactly as it now
is for a Route row. The x stays because removing a stop is not a reorder and a
drag cannot express it - it is the one difference the owner named.
⚠ THE COST, SAID OUT LOUD: those four controls were the KEYBOARD path, so a
stop can no longer be reordered without a pointer. Recorded here so the next
reader does not read it as an oversight and quietly put them back. */}
{canEdit && (
)}
{orderErrors[pid] && {orderErrors[pid]}}
))}
) :
No stops yet. Add customers from a route source.
}
{/* S63-T01 STOP SCROLL END — secondary Route tools follow; primary actions never do. */}
{unlocated.length > 0 && (
Stops without map locations
These fixed anchors stay in their current positions when the located stops reorder.
)}
{/* ⭐⭐ OWNER 2026-08-31 - THE OTHER DIFFERENCE FROM THE RAIL: *"an add record button
where it provides the dropdown for the user to add more customer to the route."*
It wears the rail's own `.cg-create-new` shape, and its list is the rail's
`.cg-find-view` box over the book the panel ALREADY HOLDS: `stopLabels` is built from
`allRows` in `MapView`, so this needs no second fetch and can only offer records the
reader can already see. ⛔ The write is the SAME membership door the x uses, with
`present: true` - one door for both directions, so a stop cannot be added through a
path the removal wall does not guard. */}
{canEdit && (
{/* ⚠ `#cg-route-popover .cg-w46-stop-addmenu` in `styles/wave42/route-nav.css` is a
DESCENDANT rule, so portalling takes this node out of its reach. That is the right
outcome for every declaration in it: position, z-index, left/right and max-height
are all supplied by `AnchoredOverlay` itself, and `.cg-view-menu` already declares
`overflow-y: auto`. The one thing genuinely lost is the row's own
`overflow: hidden; text-overflow: ellipsis`, and a candidate label is a CUSTOMER
NAME of arbitrary length against a 260px menu — hence `.cg-mi-text` on the label
below, which is the app's own ellipsis backstop and what every other
`.cg-view-menu` row already wears. NO CSS FILE WAS TOUCHED FOR THIS. */}
{addStop && (
setAddStop(null)}
dataKind="route-add-stop-menu">
{/* ⛔ NO AUTO-FOCUS ATTRIBUTE AND NO ESCAPE HANDLER OF ITS OWN. The overlay
is what focuses this
input through `initialFocus`, and it takes Escape on a document capture
listener; a second owner of either would mean one key press racing two
handlers. The route search box further down keeps its own Escape, which
clears the query rather than closing anything, and is untouched. */}
setAddStopQuery(event.target.value)} />
{addableStops.length ? addableStops.map((candidate) => (
)) : (
{addStopQuery.trim()
? "No record matches that search."
: "Every record you can see is already on this Route."}
)}
)}
)}
{mapsUrl && Open Maps}
{route.mapsUrl && !mapsUrl && Maps link is unavailable.}
Google Maps
Current ordered Route stops, split into links of at most 10 stops.
))}
> : (
Add at least two located stops to open this Route in Maps.
)}
{mapCopyNotice && {mapCopyNotice}}
{mapCopyError && {mapCopyError}}
{/* ── W46-T20 / INSTRUCTION 10 / R6: the sheet the sales team is handed. ───────────
A plain print, so the person keeps their browser's own Save as PDF, its paper
size and its margins. A div, and deliberately neither a section nor an outer
complementary landmark element: this panel's structure is pinned by
verify_grid_ux, which counts the one and forbids the other outright, and the
export is a control on the Route rather than a region of it. */}
Export
A printable stop list with a Google Maps link on every stop. Choose Save as PDF
in the print dialog.
{!stopIds.length && (
Add a stop before exporting this route.
)}
{/* OWNER 2026-08-31 item 4, second half: the Maps link cap belongs to the Google Maps
block, not to Daily delivery. It is a property of the LINK, and it was sitting
under a scheduling heading where nobody looking for it would think to read. The
value still travels in the delivery request; only its place on screen moved. */}
{/* OWNER 2026-08-31 item 2 - EVERY ROUTE GETS ITS OWN COLOUR, EDITABLE HERE.
The colour was already the record's own and already painted the line and the
sidebar swatch (`MapView.tsx::overlaidRoutes`); what did not exist was any way to
CHANGE it. `route_system.py::put_route` already reads `raw.get("color", ...)`
through `_color`, so the server door needed nothing: an unrecognised value falls
back to the ordinal default rather than painting the SVG initial black. */}
Route colour
{ROUTE_SWATCHES.map((swatch) => (
{/* ⭐⭐ D-599 / W46-T22 - THE ROUTE'S ZONE. Until wave 46's hotfix no route record
carried a zone at all, so this control had nothing to write and did not exist:
Routes and Zones were two separate tables and `__zone__` was a field on a CUSTOMER
row. It saves through the same Save button as the Maps URL beside it,
because both are properties of the Route and two save buttons on one form is how
a user loses the edit they did not press.
⚠ THE UNAVAILABLE ARM IS DELIBERATE. A Route can hold a zone this reader cannot
currently see; rendering the raw id as a disabled option says so, where dropping
it would silently clear the field on the next save. */}
{!zones.length && (
Draw a Zone on the map first, then a Route
can belong to it.
)}
{deleteConfirm && (
Delete this Route and its saved stop order?
)}
) : null}
{canEdit && (
/* ⭐ OWNER 2026-08-31 item 4 - THIS IS THE "REPEAT EVERY" CONTROL, SAID ABOUT A ROUTE.
Owner: *"this whole function needs to be almost the exact same formatting as our
'Repeat every' layout under date field. its practically the same thing."* It IS the
same thing: a rule that fires on a cadence. So it borrows the date editor's own
`w46-recur-*` contract (`field-panels.css`) rather than growing a second look for
one idea, and the sentence reads left to right the way that one does.
⛔ THE CADENCE IS NOT A CHOICE YET, AND THE CONTROL SAYS SO RATHER THAN OFFERING
ONE. `route_delivery` mints a fixed daily 08:00 cron; rendering an interval box
this server would ignore is the shape of a control that lies. */
Daily delivery
Repeat every
day, at 08:00 ({deliveryTimezone})
Stop order
Frozen as it stands now, {stopIds.length.toLocaleString()} stops.
{stopIds.length < 2 && (
Add at least two stops before scheduling.
)}
{deliveryRecipientError && (
);
}
/* ── The rail itself ─────────────────────────────────────────────────────────────────────
One recursive level: folders first as `.cg-fold` disclosure groups, then the Routes filed
at that level as `.cg-view-row`s. Both kinds of row drag, and both drop ABOVE the row they
are released on, which is the gesture `ViewSidebar` teaches.
⛔ MOVE UP / MOVE DOWN ARE GONE FROM THE "..." MENU, on the owner's ruling that drag
REPLACES them. Two ways to reorder in one rail is what made the menu long enough to need
scrolling, and the length of that menu is half of why the row could not be compact. */
const dropReorder = (siblings: string[], moved: string, over: string, kind: "route" | "folder") => {
const from = siblings.indexOf(moved);
const to = siblings.indexOf(over);
if (from < 0 || to < 0 || from === to) return;
const next = [...siblings];
next.splice(to, 0, next.splice(from, 1)[0]);
finish(kind === "route" ? onRouteReorder(next) : onFolderReorder(next));
};
const renderLevel = (parent: string, depth: number): ReactElement[] => {
const out: ReactElement[] = [];
const childFolders = (foldersByParent.get(parent) || [])
.filter((folder) => !query || folderMatches.has(folder.id));
const childRoutes = (routesByFolder.get(parent) || [])
.filter((item) => !query || item.name.toLowerCase().includes(query));
const folderIds = childFolders.map((folder) => folder.id);
const routeIds = childRoutes.map((item) => item.id);
for (const folder of childFolders) {
// A live find shows every surviving folder open, whatever the stored set holds, and the
// chevron is drawn from THAT state so a click means what it looks like (W41-T34's rule).
const shut = !query && shutFolders.has(folder.id);
const empty = !(foldersByParent.get(folder.id) || []).length
&& !(routesByFolder.get(folder.id) || []).length;
out.push(
{
event.dataTransfer.setData(ROUTE_DRAG, item.id);
event.dataTransfer.effectAllowed = "move";
setRowDrag(`route:${item.id}`);
}}
onDragEnd={() => { setRowDrag(null); setRowOver(null); }}
onDragOver={(event) => {
if (!event.dataTransfer.types.includes(ROUTE_DRAG)) return;
event.preventDefault();
setRowOver(`route:${item.id}`);
}}
onDragLeave={() => setRowOver((current) => current === `route:${item.id}` ? null : current)}
onDrop={(event) => {
const moved = event.dataTransfer.getData(ROUTE_DRAG);
setRowDrag(null); setRowOver(null);
if (!moved || moved === item.id) return;
event.preventDefault();
dropReorder(routeIds, moved, item.id, "route");
}}>
{/* ⭐ W47-T07 / instruction 9: a REAL checkbox, not a pressed button.
⛔ OWNER 2026-08-31, ON SEEING IT DEPLOYED: *"remove the dots below the checkbox on
the routes rail, its ugly af, what is that even there for"*. The dot was the Route's
colour - the SAME `item.color` the drawn line uses - and it is gone as a separate
element. The colour is NOT lost: it tints the checkbox itself through `accentColor`,
so ticking a Route still shows you which line on the map is about to be yours,
without a second mark in the row. */}
{menu && menu.id === item.id && (
setMenu(null)}
dataKind="route-menu">
{folders.filter((folder) => folder.id !== item.folderId).map((folder) =>
)}
{item.folderId && }
)}
);
}
return out;
};
const levelRows = renderLevel(ROOT_LEVEL, 0);
// A failed read is not "no routes": the load error leads the list and stands in for the empty state.
const rows = routesLoadError ? [
) : null}
{/* Owner item 3 - the SAME create door the Views rail mounts (`.cg-create-new` /
`.cg-create-btn` are a shared contract, see `ViewSidebar.tsx`'s note on them), with the
two things a Routes rail can make behind it. */}
{!routesLoaded ? "Loading routes."
: query ? "No Route matches that search."
: "No routes yet. Create one from selected Zones or records."}
}
>
);
return (
{/* ⛔ An open Route REPLACES the Routes list: Back to routes is its only way out. */}
{route ? routeDetail() : inventory}
{/* ⛔ RENDERED FROM THE COMPONENT ROOT, OUTSIDE `renderLevel` AND OUTSIDE EVERY MENU
CONDITIONAL. See the note over `pendingDelete`: a dialog inside the menu subtree that
set it would never paint. `ConfirmDialog` portals to itself, so its position in
this tree governs only its LIFETIME, and that is exactly what needed fixing. */}
{
const target = pendingDelete;
if (!target || busy) return;
setBusy(true);
void (target.kind === "folder" ? onFolderDelete(target.folder) : onDelete(target.item))
.then(setError)
.finally(() => { setBusy(false); setPendingDelete(null); });
}}
onCancel={() => setPendingDelete(null)}
/>
);
}