strata-react 1.0.31 → 1.0.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/map.js CHANGED
@@ -1,9 +1,11 @@
1
- import { _ as cn, a as useColorScheme } from "./theme-BgTOESmN.js";
2
- import { a as format, t as geo } from "./geo-C0jcFp4q.js";
1
+ import { _ as cn, a as useColorScheme, h as Tooltip$1 } from "./theme-BgTOESmN.js";
2
+ import { n as useSharedCursor, r as geo, s as format } from "./cursor-DplHNzj3.js";
3
3
  import * as React from "react";
4
- import { jsx, jsxs } from "react/jsx-runtime";
4
+ import { Button } from "react-aria-components";
5
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
6
  import L from "leaflet";
6
7
  import leafletCss from "leaflet/dist/leaflet.css?inline";
8
+ import { createPortal } from "react-dom";
7
9
  // src/map/map-styles.ts
8
10
  var strata = `
9
11
  .strata-map .leaflet-container { background: var(--surface-sunken); color: var(--foreground); font: inherit; }
@@ -20,6 +22,9 @@ var strata = `
20
22
  .strata-map .leaflet-tooltip::before { display: none; }
21
23
  .strata-map[data-dark-treatment] .leaflet-tile-pane { filter: invert(1) hue-rotate(180deg) brightness(0.9) contrast(0.9); }
22
24
  .strata-map .strata-map-arrow { background: none; border: 0; }
25
+ .strata-map .strata-map-marker, .strata-map .strata-map-crosshair { background: none; border: 0; display: grid; place-items: center; }
26
+ .strata-map .strata-map-reset { display: grid; place-items: center; }
27
+ .strata-map .strata-map-picking, .strata-map .strata-map-picking .leaflet-interactive { cursor: crosshair; }
23
28
  `;
24
29
  var installed = false;
25
30
  /** Puts Leaflet's stylesheet and the token overrides in the document head, once. */
@@ -31,6 +36,232 @@ function installMapStyles() {
31
36
  el.textContent = leafletCss + strata;
32
37
  document.head.appendChild(el);
33
38
  }
39
+ // src/map/fan.ts
40
+ /** Move apart markers closer than `gap` pixels. Output is in input order. */
41
+ function fanOut(items, gap = 26) {
42
+ const parent = items.map((_, i) => i);
43
+ const find = (i) => parent[i] === i ? i : parent[i] = find(parent[i]);
44
+ const cells = /* @__PURE__ */ new Map();
45
+ const key = (cx, cy) => `${cx},${cy}`;
46
+ items.forEach((p, i) => {
47
+ const [cx, cy] = [Math.floor(p.x / gap), Math.floor(p.y / gap)];
48
+ for (let dx = -1; dx <= 1; dx++) for (let dy = -1; dy <= 1; dy++) for (const j of cells.get(key(cx + dx, cy + dy)) ?? []) if (Math.hypot(items[j].x - p.x, items[j].y - p.y) < gap) parent[find(i)] = find(j);
49
+ const own = cells.get(key(cx, cy));
50
+ if (own) own.push(i);
51
+ else cells.set(key(cx, cy), [i]);
52
+ });
53
+ const groups = /* @__PURE__ */ new Map();
54
+ items.forEach((_, i) => {
55
+ const r = find(i);
56
+ const g = groups.get(r);
57
+ if (g) g.push(i);
58
+ else groups.set(r, [i]);
59
+ });
60
+ const out = items.map((p) => ({
61
+ id: p.id,
62
+ x: p.x,
63
+ y: p.y,
64
+ fanned: false
65
+ }));
66
+ for (const members of groups.values()) {
67
+ const n = members.length;
68
+ if (n < 2) continue;
69
+ const cx = members.reduce((s, i) => s + items[i].x, 0) / n;
70
+ const cy = members.reduce((s, i) => s + items[i].y, 0) / n;
71
+ const place = (i, radius, angle) => {
72
+ out[i] = {
73
+ id: items[i].id,
74
+ x: cx + radius * Math.sin(angle),
75
+ y: cy - radius * Math.cos(angle),
76
+ fanned: true
77
+ };
78
+ };
79
+ if (n <= 6) {
80
+ const radius = gap / (2 * Math.sin(Math.PI / n));
81
+ members.forEach((i, k) => place(i, radius, 2 * Math.PI * k / n));
82
+ } else {
83
+ let k = 0;
84
+ for (let ring = 1; k < n; ring++) {
85
+ const radius = ring * gap;
86
+ const fit = Math.max(1, Math.floor(2 * Math.PI * radius / gap));
87
+ const here = Math.min(fit, n - k);
88
+ for (let m = 0; m < here; m++) place(members[k + m], radius, 2 * Math.PI * m / here);
89
+ k += here;
90
+ }
91
+ }
92
+ }
93
+ return out;
94
+ }
95
+ // src/map/markers.tsx
96
+ var alongCache = /* @__PURE__ */ new WeakMap();
97
+ /** The running distance at each point of a route, kept per route array so a long route is walked once. */
98
+ function alongOf(points) {
99
+ let a = alongCache.get(points);
100
+ if (!a) {
101
+ a = geo.cumulative(points);
102
+ alongCache.set(points, a);
103
+ }
104
+ return a;
105
+ }
106
+ /** Where a marker really is: its place, or the middle of its stretch. Null when its route is not on the map. */
107
+ function markerPlace(m, routes) {
108
+ if (Array.isArray(m.at)) return m.at;
109
+ const at = m.at;
110
+ const route = routes.find((r) => r.id === at.routeId);
111
+ return route ? geo.pointAlong(route.points, (at.from + at.to) / 2, alongOf(route.points)) : null;
112
+ }
113
+ /** The markers near the view, with the overlapping ones fanned apart for this zoom. */
114
+ function placeMarkers(map, markers, routes) {
115
+ const near = map.getBounds().pad(.25);
116
+ const zoom = map.getZoom();
117
+ const here = [];
118
+ for (const marker of markers) {
119
+ const at = markerPlace(marker, routes);
120
+ if (at && near.contains([at[0], at[1]])) here.push({
121
+ marker,
122
+ at
123
+ });
124
+ }
125
+ const fanned = fanOut(here.map((h) => ({
126
+ id: h.marker.id,
127
+ ...map.project([h.at[0], h.at[1]], zoom)
128
+ })));
129
+ return here.map((h, i) => {
130
+ const f = fanned[i];
131
+ const shown = f.fanned ? map.unproject([f.x, f.y], zoom) : null;
132
+ return {
133
+ marker: h.marker,
134
+ at: h.at,
135
+ shown: shown ? [shown.lat, shown.lng] : h.at,
136
+ fanned: f.fanned
137
+ };
138
+ });
139
+ }
140
+ var state = (m) => m.highlighted ? "highlighted" : m.selected ? "selected" : "marker";
141
+ /** One marker: a Leaflet marker holding a node that React fills with a labelled button. */
142
+ function Pin({ map, placed, active, onActivate, onMove, register, onSelect, card }) {
143
+ const { marker, shown } = placed;
144
+ const host = React.useMemo(() => {
145
+ const el = document.createElement("div");
146
+ el.className = "strata-map-pin";
147
+ return el;
148
+ }, []);
149
+ const layer = React.useRef(null);
150
+ React.useEffect(() => {
151
+ const m = L.marker([shown[0], shown[1]], {
152
+ icon: L.divIcon({
153
+ className: "strata-map-marker",
154
+ html: host,
155
+ iconSize: [28, 28],
156
+ iconAnchor: [14, 14]
157
+ }),
158
+ interactive: false,
159
+ keyboard: false
160
+ }).addTo(map);
161
+ layer.current = m;
162
+ return () => {
163
+ layer.current = null;
164
+ m.remove();
165
+ };
166
+ }, [map, host]);
167
+ React.useEffect(() => {
168
+ layer.current?.setLatLng([shown[0], shown[1]]);
169
+ }, [shown]);
170
+ React.useEffect(() => {
171
+ layer.current?.setZIndexOffset(marker.selected ? 1e3 : marker.highlighted ? 500 : 0);
172
+ }, [marker.selected, marker.highlighted]);
173
+ const kind = state(marker);
174
+ const swatch = marker.colour ?? (kind === "highlighted" ? "var(--success)" : kind === "selected" ? "var(--foreground)" : "var(--primary)");
175
+ return createPortal(/* @__PURE__ */ jsx(Tooltip$1, {
176
+ label: card ? card(marker) : marker.label,
177
+ side: "top",
178
+ children: /* @__PURE__ */ jsx(Button, {
179
+ ref: (el) => register(marker.id, el),
180
+ "aria-label": marker.label,
181
+ "aria-pressed": marker.selected ?? false,
182
+ excludeFromTabOrder: !active,
183
+ onFocus: () => onActivate(marker.id),
184
+ onPress: () => onSelect?.(marker.id),
185
+ onKeyDown: (e) => {
186
+ const to = e.key === "ArrowRight" || e.key === "ArrowDown" ? "next" : e.key === "ArrowLeft" || e.key === "ArrowUp" ? "previous" : e.key === "Home" ? "first" : e.key === "End" ? "last" : null;
187
+ if (!to) return;
188
+ e.preventDefault();
189
+ e.stopPropagation();
190
+ onMove(marker.id, to);
191
+ },
192
+ className: "pointer-events-auto grid size-7 cursor-pointer place-items-center rounded-pill outline-offset-1 focus-visible:outline-2 focus-visible:outline-ring",
193
+ children: /* @__PURE__ */ jsx(Shape, {
194
+ kind,
195
+ colour: swatch
196
+ })
197
+ })
198
+ }), host);
199
+ }
200
+ /** The drawn shape of a marker state: a circle, a ringed larger circle, a diamond. Shapes carry the meaning as colour does. */
201
+ function Shape({ kind, colour }) {
202
+ return /* @__PURE__ */ jsx("span", {
203
+ "aria-hidden": true,
204
+ className: cn("block border-2 border-background", kind === "highlighted" ? "size-3.5 rotate-45 rounded-sm" : "rounded-pill", kind === "selected" ? "size-4 ring-2 ring-foreground" : kind === "marker" ? "size-3.5" : ""),
205
+ style: { background: colour }
206
+ });
207
+ }
208
+ /** The pins for the markers near the view, as one roving group: one tab stop, arrows between them. */
209
+ function MarkerLayer({ map, placed, onSelect, card }) {
210
+ const [activeId, setActiveId] = React.useState(null);
211
+ const els = React.useRef(/* @__PURE__ */ new Map());
212
+ const ids = placed.map((p) => p.marker.id);
213
+ const active = activeId !== null && ids.includes(activeId) ? activeId : ids[0] ?? null;
214
+ const register = React.useCallback((id, el) => {
215
+ if (el) els.current.set(id, el);
216
+ else els.current.delete(id);
217
+ }, []);
218
+ const move = (id, to) => {
219
+ const i = ids.indexOf(id);
220
+ const next = to === "first" ? 0 : to === "last" ? ids.length - 1 : Math.min(ids.length - 1, Math.max(0, i + (to === "next" ? 1 : -1)));
221
+ setActiveId(ids[next]);
222
+ els.current.get(ids[next])?.focus();
223
+ };
224
+ return /* @__PURE__ */ jsx(Fragment, { children: placed.map((p) => /* @__PURE__ */ jsx(Pin, {
225
+ map,
226
+ placed: p,
227
+ active: p.marker.id === active,
228
+ onActivate: setActiveId,
229
+ onMove: move,
230
+ register,
231
+ onSelect,
232
+ card
233
+ }, p.marker.id)) });
234
+ }
235
+ /** The key to the marker states that are on the map, each with its shape and its words. */
236
+ function MarkerKey({ markers, words }) {
237
+ const kinds = [
238
+ "marker",
239
+ "selected",
240
+ "highlighted"
241
+ ].filter((k) => markers.some((m) => state(m) === k));
242
+ const text = {
243
+ marker: words?.marker ?? "Item",
244
+ selected: words?.selected ?? "Selected",
245
+ highlighted: words?.highlighted ?? "Highlighted"
246
+ };
247
+ if (!kinds.length) return null;
248
+ return /* @__PURE__ */ jsx("div", {
249
+ className: "rounded-control border border-border bg-background px-2 py-1.5 type-caption text-foreground",
250
+ children: /* @__PURE__ */ jsx("ul", {
251
+ className: "grid gap-0.5",
252
+ children: kinds.map((k) => /* @__PURE__ */ jsxs("li", {
253
+ className: "flex items-center gap-2",
254
+ children: [/* @__PURE__ */ jsx("span", {
255
+ className: "grid size-4 place-items-center",
256
+ children: /* @__PURE__ */ jsx(Shape, {
257
+ kind: k,
258
+ colour: k === "highlighted" ? "var(--success)" : k === "selected" ? "var(--foreground)" : "var(--primary)"
259
+ })
260
+ }), text[k]]
261
+ }, k))
262
+ })
263
+ });
264
+ }
34
265
  // src/map/route-map.tsx
35
266
  /** The smallest and largest value, without spreading the array (a long recording passes the engine's argument limit). */
36
267
  function extent(values) {
@@ -55,6 +286,73 @@ function useSlow(value, ms = 1e3) {
55
286
  }, [ms]);
56
287
  return slow;
57
288
  }
289
+ /** How many moves of the map the component itself is making right now (see `onViewChange`). */
290
+ var quiet = /* @__PURE__ */ new WeakMap();
291
+ /** Run a move the component makes itself, so `onViewChange` does not report it. Leaflet's events are synchronous with animation off. */
292
+ function silently(map, fn) {
293
+ quiet.set(map, (quiet.get(map) ?? 0) + 1);
294
+ try {
295
+ return fn();
296
+ } finally {
297
+ quiet.set(map, (quiet.get(map) ?? 1) - 1);
298
+ }
299
+ }
300
+ /** The route nearest a place, by distance from it to the route (not to a vertex). */
301
+ function nearestRoute(routes, at) {
302
+ let best = null;
303
+ for (const r of routes) {
304
+ const s = geo.snap(r.points, at, alongOf(r.points));
305
+ if (s && (!best || s.offset < best.distanceM)) best = {
306
+ routeId: r.id,
307
+ index: s.index,
308
+ distanceM: s.offset,
309
+ alongM: s.metres,
310
+ position: s.position
311
+ };
312
+ }
313
+ return best;
314
+ }
315
+ var RESET_ICON = "<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" aria-hidden=\"true\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.75\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M2 6V2h4M10 2h4v4M14 10v4h-4M6 14H2v-4\"/></svg>";
316
+ var CROSS_ICON = "<svg width=\"32\" height=\"32\" viewBox=\"0 0 32 32\" aria-hidden=\"true\" fill=\"none\" stroke-linecap=\"round\"><path d=\"M16 4v24M4 16h24\" stroke=\"var(--background)\" stroke-width=\"5\"/><path d=\"M16 4v24M4 16h24\" stroke=\"var(--foreground)\" stroke-width=\"2\"/></svg>";
317
+ /** Leaflet's control group gets a reset: fit the routes again. A link with a button role, as Leaflet's own zoom buttons are. */
318
+ function resetControl(onReset) {
319
+ const control = new L.Control({ position: "topleft" });
320
+ control.onAdd = () => {
321
+ const bar = L.DomUtil.create("div", "leaflet-bar leaflet-control");
322
+ const a = L.DomUtil.create("a", "strata-map-reset", bar);
323
+ a.href = "#";
324
+ a.setAttribute("role", "button");
325
+ a.setAttribute("aria-label", "Reset view");
326
+ a.title = "Reset view";
327
+ a.innerHTML = RESET_ICON;
328
+ L.DomEvent.disableClickPropagation(bar);
329
+ L.DomEvent.on(a, "click", (e) => {
330
+ L.DomEvent.preventDefault(e);
331
+ onReset();
332
+ });
333
+ L.DomEvent.on(a, "keydown", (e) => {
334
+ if (e.key === " ") {
335
+ L.DomEvent.preventDefault(e);
336
+ onReset();
337
+ }
338
+ });
339
+ return bar;
340
+ };
341
+ return control;
342
+ }
343
+ /** Put the routes in view (or, with a zoom set, centre the routes at it). */
344
+ function showRoutes(map, routes, zoom) {
345
+ const box = geo.bounds(routes.flatMap((r) => r.points));
346
+ if (!box) return false;
347
+ if (zoom !== void 0) map.setView([(box[0][0] + box[1][0]) / 2, (box[0][1] + box[1][1]) / 2], zoom, { animate: false });
348
+ else map.fitBounds([tuple(box[0]), tuple(box[1])], {
349
+ padding: [24, 24],
350
+ animate: false,
351
+ maxZoom: 17
352
+ });
353
+ return true;
354
+ }
355
+ var SINGLE = "\0position";
58
356
  var PALETTE = [
59
357
  1,
60
358
  2,
@@ -62,6 +360,26 @@ var PALETTE = [
62
360
  4,
63
361
  5
64
362
  ].map((n) => `var(--chart-${n})`);
363
+ /**
364
+ * Put `target` in the exact middle of the view at zoom `z`, with no animation and without throwing the
365
+ * loaded tiles away. A zoom change goes through `setView` (Leaflet redraws its tiles then anyway). The
366
+ * position is then set by panning to a whole-pixel top-left worked out from the target and the zoom
367
+ * alone, so where the view ends up does not depend on the path taken (Leaflet's own centred pan
368
+ * truncates each step and drifts); a `reset` would be exact too but empties the tile layer on every
369
+ * call, which flickers when the position changes every frame.
370
+ */
371
+ function centre(map, target, z) {
372
+ silently(map, () => {
373
+ if (map.getZoom() !== z) map.setView(tuple(target), z, { animate: false });
374
+ const want = map.project(tuple(target), z).subtract(map.getSize().divideBy(2)).round();
375
+ const have = map.getPixelBounds().min.round();
376
+ const move = want.subtract(have);
377
+ if (move.x || move.y) map.panBy(move, {
378
+ animate: false,
379
+ noMoveStart: true
380
+ });
381
+ });
382
+ }
65
383
  /** The colour a CSS value (a `var()`, a role) resolves to on `el`, so an SVG attribute gets a real one. Falls back to the value itself. */
66
384
  function resolveColour(el, value) {
67
385
  const probe = document.createElement("span");
@@ -88,17 +406,42 @@ function stepRuns(points, values, stepOf) {
88
406
  }
89
407
  var arrowHtml = (bearing, colour, halo) => `<svg width="26" height="26" viewBox="0 0 26 26" aria-hidden="true" style="transform: rotate(${bearing.toFixed(0)}deg)"><path d="M6 17 L13 9 L20 17" fill="none" stroke="${halo}" stroke-width="7" stroke-linecap="round" stroke-linejoin="round"/><path d="M6 17 L13 9 L20 17" fill="none" stroke="${colour}" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
90
408
  /** A map of one or more routes with a position that moves along them, on tiles the app supplies, themed from its roles. Leaflet, behind `strata-react/map`. */
91
- function RouteMap({ label, routes, tiles, position = null, positionLabel = "Current position", follow = false, selectedId = null, onSelect, colourScale, colourScaleLabel, formatValue = plain, summary, units = "metric", scrollZoom = false, topEnd, bottomStart, className }) {
409
+ function RouteMap({ label, routes, tiles, position = null, positionLabel = "Current position", positions, followId, follow = false, zoom, markers, onMarkerSelect, renderMarkerCard, markerKey, cursor: cursorProp, onViewChange, settle = 250, reportAppMoves = false, view, picking = false, onPick, onPickCancel, pickBanner, selectedId = null, onSelect, colourScale, colourScaleLabel, formatValue = plain, summary, units = "metric", scrollZoom = false, topEnd, bottomStart, className }) {
92
410
  const { scheme } = useColorScheme();
93
411
  const host = React.useRef(null);
94
412
  const root = React.useRef(null);
95
413
  const [map, setMap] = React.useState(null);
96
414
  const summaryId = React.useId();
97
- const latest = React.useRef({ onSelect });
98
- latest.current = { onSelect };
415
+ const latest = React.useRef({
416
+ onSelect,
417
+ onViewChange,
418
+ reportAppMoves,
419
+ settle,
420
+ picking,
421
+ onPick,
422
+ onPickCancel,
423
+ routes,
424
+ units,
425
+ view,
426
+ zoom
427
+ });
428
+ latest.current = {
429
+ onSelect,
430
+ onViewChange,
431
+ reportAppMoves,
432
+ settle,
433
+ picking,
434
+ onPick,
435
+ onPickCancel,
436
+ routes,
437
+ units,
438
+ view,
439
+ zoom
440
+ };
441
+ const [announced, setAnnounced] = React.useState("");
442
+ const [ready, setReady] = React.useState(false);
99
443
  const selectable = Boolean(onSelect);
100
- const marker = React.useRef(null);
101
- const markerScheme = React.useRef(null);
444
+ const posMarkers = React.useRef(/* @__PURE__ */ new Map());
102
445
  const source = (scheme === "dark" ? tiles.dark : void 0) ?? tiles.light;
103
446
  const treated = scheme === "dark" && !tiles.dark;
104
447
  const stops = React.useMemo(() => colourScale ? [...colourScale].sort((a, b) => a.at - b.at) : [], [colourScale]);
@@ -122,10 +465,10 @@ function RouteMap({ label, routes, tiles, position = null, positionLabel = "Curr
122
465
  setMap(m);
123
466
  return () => {
124
467
  ro.disconnect();
125
- marker.current = null;
126
- markerScheme.current = null;
468
+ posMarkers.current.clear();
127
469
  m.remove();
128
470
  setMap(null);
471
+ setReady(false);
129
472
  };
130
473
  }, []);
131
474
  React.useEffect(() => {
@@ -133,7 +476,20 @@ function RouteMap({ label, routes, tiles, position = null, positionLabel = "Curr
133
476
  if (scrollZoom) map.scrollWheelZoom.enable();
134
477
  else map.scrollWheelZoom.disable();
135
478
  }, [map, scrollZoom]);
136
- const spoken = useSlow(position);
479
+ const zoomed = zoom !== void 0;
480
+ React.useEffect(() => {
481
+ if (map) map.options.zoomSnap = zoomed ? 0 : .5;
482
+ }, [map, zoomed]);
483
+ const all = React.useMemo(() => [...position ? [{
484
+ id: SINGLE,
485
+ at: position,
486
+ label: positionLabel
487
+ }] : [], ...positions ?? []], [
488
+ position,
489
+ positionLabel,
490
+ positions
491
+ ]);
492
+ const spoken = useSlow(all);
137
493
  const text = React.useMemo(() => {
138
494
  if (summary) return summary;
139
495
  if (!routes.length) return "No routes to show.";
@@ -142,24 +498,25 @@ function RouteMap({ label, routes, tiles, position = null, positionLabel = "Curr
142
498
  const total = along[along.length - 1] ?? 0;
143
499
  const shape = geo.ends(r.points)?.loop ? ", a loop" : "";
144
500
  let here = "";
145
- if (spoken && r.points.length) {
146
- const i = geo.nearest(r.points, spoken);
147
- here = ` ${positionLabel}: ${format.distance(along[i] ?? 0, units)} along.`;
501
+ for (const p of spoken) {
502
+ if (!p.at || !r.points.length || p.routeId !== void 0 && p.routeId !== r.id && routes.some((o) => o.id === p.routeId)) continue;
503
+ here += ` ${p.label}: ${format.distance(along[geo.nearest(r.points, p.at)] ?? 0, units)} along.`;
148
504
  }
149
505
  let range = "";
150
506
  if (stops.length && r.values?.length) range = ` ${colourScaleLabel ?? "Value"} from ${formatValue(extent(r.values)[0])} to ${formatValue(extent(r.values)[1])}.`;
151
507
  return `${r.label}: ${format.distance(total, units)}${shape}.${range}${here}`;
152
508
  });
153
- return `Map with ${routes.length === 1 ? "one route" : `${routes.length} routes`}. ${parts.join(" ")}`;
509
+ const items = markers?.length ? ` ${markers.length === 1 ? "One marker" : `${markers.length} markers`}${markers.some((m) => m.selected) ? `, selected: ${markers.filter((m) => m.selected).map((m) => m.label).join(", ")}` : ""}.` : "";
510
+ return `Map with ${routes.length === 1 ? "one route" : `${routes.length} routes`}. ${parts.join(" ")}${items}`;
154
511
  }, [
155
512
  summary,
156
513
  routes,
157
514
  spoken,
158
- positionLabel,
159
515
  units,
160
516
  stops.length,
161
517
  colourScaleLabel,
162
- formatValue
518
+ formatValue,
519
+ markers
163
520
  ]);
164
521
  React.useEffect(() => {
165
522
  if (!map) return;
@@ -213,7 +570,7 @@ function RouteMap({ label, routes, tiles, position = null, positionLabel = "Curr
213
570
  opacity: dim ? .55 : 1,
214
571
  lineCap: "round",
215
572
  lineJoin: "round",
216
- interactive: selectable,
573
+ interactive: selectable && !picking,
217
574
  bubblingMouseEvents: false
218
575
  };
219
576
  const lines = [];
@@ -275,6 +632,7 @@ function RouteMap({ label, routes, tiles, position = null, positionLabel = "Curr
275
632
  }
276
633
  }
277
634
  });
635
+ for (const { marker } of posMarkers.current.values()) marker.bringToFront();
278
636
  return () => void group.remove();
279
637
  }, [
280
638
  map,
@@ -282,8 +640,28 @@ function RouteMap({ label, routes, tiles, position = null, positionLabel = "Curr
282
640
  scheme,
283
641
  selectedId,
284
642
  stops,
285
- selectable
643
+ selectable,
644
+ picking
645
+ ]);
646
+ const target = React.useMemo(() => {
647
+ if (!follow) return null;
648
+ const shown = all.filter((p) => p.at);
649
+ return (followId ? shown.find((p) => p.id === followId) : shown[0])?.at ?? null;
650
+ }, [
651
+ all,
652
+ follow,
653
+ followId
286
654
  ]);
655
+ const latestView = React.useRef({
656
+ target,
657
+ zoom,
658
+ centred: follow === "centre"
659
+ });
660
+ latestView.current = {
661
+ target,
662
+ zoom,
663
+ centred: follow === "centre"
664
+ };
287
665
  const routeKey = routes.map((r) => r.id).join("\n");
288
666
  const fitted = React.useRef(null);
289
667
  React.useEffect(() => {
@@ -291,52 +669,309 @@ function RouteMap({ label, routes, tiles, position = null, positionLabel = "Curr
291
669
  const fit = () => {
292
670
  const size = map.getSize();
293
671
  if (fitted.current === routeKey || size.x === 0 || size.y === 0) return;
294
- const box = geo.bounds(routes.flatMap((r) => r.points));
295
- if (!box) return;
672
+ if (!geo.bounds(routes.flatMap((r) => r.points)) && !latest.current.view) return;
296
673
  fitted.current = routeKey;
297
- map.fitBounds([tuple(box[0]), tuple(box[1])], {
298
- padding: [24, 24],
299
- animate: false,
300
- maxZoom: 17
674
+ const v = latestView.current;
675
+ setReady(true);
676
+ silently(map, () => {
677
+ if (latest.current.view) map.setView(tuple(latest.current.view.center), latest.current.view.zoom, { animate: false });
678
+ else if (v.zoom !== void 0 && v.centred && v.target) map.setView(tuple(v.target), v.zoom, { animate: false });
679
+ else showRoutes(map, latest.current.routes, v.zoom);
301
680
  });
302
681
  };
303
682
  fit();
304
683
  map.on("resize", fit);
305
684
  return () => void map.off("resize", fit);
306
685
  }, [map, routeKey]);
307
- const [lat, lng] = position ?? [null, null];
686
+ React.useEffect(() => {
687
+ if (map && zoom !== void 0 && fitted.current !== null && map.getZoom() !== zoom) silently(map, () => map.setZoom(zoom, { animate: false }));
688
+ }, [map, zoom]);
689
+ React.useEffect(() => {
690
+ if (!map) return;
691
+ const el = map.getContainer();
692
+ const live = posMarkers.current;
693
+ const seen = /* @__PURE__ */ new Set();
694
+ for (const p of all) {
695
+ if (!p.at) continue;
696
+ seen.add(p.id);
697
+ let entry = live.get(p.id);
698
+ if (!entry) {
699
+ entry = {
700
+ marker: L.circleMarker(tuple(p.at), {
701
+ radius: 8,
702
+ weight: 3,
703
+ fillOpacity: 1,
704
+ interactive: false
705
+ }).addTo(map),
706
+ style: ""
707
+ };
708
+ live.set(p.id, entry);
709
+ } else entry.marker.setLatLng(tuple(p.at));
710
+ const index = routes.findIndex((r) => r.id === p.routeId);
711
+ const spec = p.colour ?? (index >= 0 ? routes[index].colour ?? PALETTE[index % PALETTE.length] : "var(--primary)");
712
+ const style = `${scheme}|${spec}`;
713
+ if (entry.style !== style) {
714
+ entry.style = style;
715
+ entry.marker.setStyle({
716
+ color: resolveColour(el, "var(--background)"),
717
+ fillColor: resolveColour(el, spec)
718
+ });
719
+ }
720
+ }
721
+ for (const [id, entry] of live) {
722
+ if (seen.has(id)) continue;
723
+ entry.marker.remove();
724
+ live.delete(id);
725
+ }
726
+ if (!target) return;
727
+ if (follow === "centre") {
728
+ const z = zoom ?? (fitted.current === null ? void 0 : map.getZoom());
729
+ if (z !== void 0) centre(map, target, z);
730
+ } else if (!map.getBounds().pad(-.2).contains(tuple(target))) silently(map, () => map.panTo(tuple(target), { animate: false }));
731
+ }, [
732
+ map,
733
+ all,
734
+ routes,
735
+ scheme,
736
+ follow,
737
+ target,
738
+ zoom
739
+ ]);
740
+ React.useEffect(() => {
741
+ if (!map) return;
742
+ const control = resetControl(() => {
743
+ const view = latest.current.view;
744
+ if (view) map.setView(tuple(view.center), view.zoom, { animate: false });
745
+ else showRoutes(map, latest.current.routes, latest.current.zoom);
746
+ });
747
+ control.addTo(map);
748
+ return () => void control.remove();
749
+ }, [map]);
308
750
  React.useEffect(() => {
309
751
  if (!map) return;
310
- if (lat === null || lng === null) {
311
- marker.current?.remove();
312
- marker.current = null;
752
+ let timer;
753
+ const send = () => {
754
+ timer = void 0;
755
+ const b = map.getBounds();
756
+ const c = map.getCenter();
757
+ latest.current.onViewChange?.({
758
+ bounds: [[b.getSouth(), b.getWest()], [b.getNorth(), b.getEast()]],
759
+ zoom: map.getZoom(),
760
+ center: [c.lat, c.lng]
761
+ });
762
+ };
763
+ const moved = () => {
764
+ if (!latest.current.onViewChange) return;
765
+ if (!latest.current.reportAppMoves && (quiet.get(map) ?? 0) > 0) return;
766
+ window.clearTimeout(timer);
767
+ timer = window.setTimeout(send, latest.current.settle);
768
+ };
769
+ map.on("moveend zoomend", moved);
770
+ if (fitted.current !== null && latest.current.reportAppMoves) moved();
771
+ return () => {
772
+ map.off("moveend zoomend", moved);
773
+ window.clearTimeout(timer);
774
+ };
775
+ }, [map]);
776
+ const [viewLat, viewLng, viewZoom] = view ? [
777
+ view.center[0],
778
+ view.center[1],
779
+ view.zoom
780
+ ] : [
781
+ null,
782
+ null,
783
+ null
784
+ ];
785
+ React.useEffect(() => {
786
+ if (!map || viewLat === null || viewLng === null || viewZoom === null || fitted.current === null) return;
787
+ const c = map.getCenter();
788
+ if (map.getZoom() === viewZoom && Math.abs(c.lat - viewLat) < 1e-7 && Math.abs(c.lng - viewLng) < 1e-7) return;
789
+ silently(map, () => map.setView([viewLat, viewLng], viewZoom, { animate: false }));
790
+ }, [
791
+ map,
792
+ viewLat,
793
+ viewLng,
794
+ viewZoom
795
+ ]);
796
+ const shared = useSharedCursor();
797
+ const cursorOn = Boolean(cursorProp) && shared !== null;
798
+ const cursorRouteId = typeof cursorProp === "object" && cursorProp.routeId ? cursorProp.routeId : routes[0]?.id;
799
+ const cursorRoute = routes.find((r) => r.id === cursorRouteId) ?? null;
800
+ const setPointer = shared?.setPointer;
801
+ React.useEffect(() => {
802
+ if (!map || !cursorOn || !cursorRoute || !setPointer) return;
803
+ const along = alongOf(cursorRoute.points);
804
+ const onMove = (e) => {
805
+ if (latest.current.picking) return;
806
+ const snap = geo.snap(cursorRoute.points, [e.latlng.lat, e.latlng.lng], along);
807
+ if (!snap) return;
808
+ const apart = map.latLngToContainerPoint(e.latlng).distanceTo(map.latLngToContainerPoint(tuple(snap.position)));
809
+ setPointer(apart <= 24 ? snap.metres : null);
810
+ };
811
+ const onOut = () => setPointer(null);
812
+ map.on("mousemove", onMove);
813
+ map.on("mouseout", onOut);
814
+ return () => {
815
+ map.off("mousemove", onMove);
816
+ map.off("mouseout", onOut);
817
+ setPointer(null);
818
+ };
819
+ }, [
820
+ map,
821
+ cursorOn,
822
+ cursorRoute,
823
+ setPointer
824
+ ]);
825
+ const otherAlong = cursorOn ? shared?.other ?? null : null;
826
+ const ring = React.useRef(null);
827
+ React.useEffect(() => {
828
+ if (!map) return;
829
+ const at = otherAlong !== null && cursorRoute ? geo.pointAlong(cursorRoute.points, otherAlong, alongOf(cursorRoute.points)) : null;
830
+ if (!at) {
831
+ ring.current?.remove();
832
+ ring.current = null;
313
833
  return;
314
834
  }
315
- const el = map.getContainer();
316
- if (!marker.current) {
317
- marker.current = L.circleMarker([lat, lng], {
318
- radius: 8,
835
+ if (!ring.current) {
836
+ const el = map.getContainer();
837
+ ring.current = L.circleMarker(tuple(at), {
838
+ radius: 9,
319
839
  weight: 3,
320
- fillOpacity: 1,
321
- interactive: false
840
+ fillOpacity: 0,
841
+ interactive: false,
842
+ color: resolveColour(el, "var(--foreground)")
322
843
  }).addTo(map);
323
- markerScheme.current = null;
324
- } else marker.current.setLatLng([lat, lng]);
325
- if (markerScheme.current !== scheme) {
326
- markerScheme.current = scheme;
327
- marker.current.setStyle({
328
- color: resolveColour(el, "var(--background)"),
329
- fillColor: resolveColour(el, "var(--primary)")
330
- });
844
+ } else ring.current.setLatLng(tuple(at));
845
+ }, [
846
+ map,
847
+ otherAlong,
848
+ cursorRoute
849
+ ]);
850
+ React.useEffect(() => () => void (ring.current = null), [map]);
851
+ const [tick, setTick] = React.useState(0);
852
+ React.useEffect(() => {
853
+ if (!map || !markers?.length) return;
854
+ const again = () => setTick((t) => t + 1);
855
+ map.on("moveend zoomend resize", again);
856
+ return () => void map.off("moveend zoomend resize", again);
857
+ }, [map, markers?.length]);
858
+ const placed = React.useMemo(() => map && ready && markers?.length ? placeMarkers(map, markers, routes) : [], [
859
+ map,
860
+ ready,
861
+ markers,
862
+ routes,
863
+ tick
864
+ ]);
865
+ React.useEffect(() => {
866
+ if (!map || !markers?.length) return;
867
+ const group = L.featureGroup().addTo(map);
868
+ const el = map.getContainer();
869
+ for (const m of markers) {
870
+ if (Array.isArray(m.at)) continue;
871
+ const at = m.at;
872
+ const index = routes.findIndex((r) => r.id === at.routeId);
873
+ if (index < 0) continue;
874
+ const route = routes[index];
875
+ const part = geo.slice(route.points, at.from, at.to, alongOf(route.points));
876
+ if (part.length < 2) continue;
877
+ const colour = m.colour ?? (m.highlighted ? "var(--success)" : m.selected ? "var(--foreground)" : route.colour ?? PALETTE[index % PALETTE.length]);
878
+ L.polyline(part.map(tuple), {
879
+ color: resolveColour(el, colour),
880
+ weight: (route.weight ?? 4) + (m.selected ? 5 : 3),
881
+ opacity: m.selected ? 1 : .8,
882
+ lineCap: "round",
883
+ interactive: false
884
+ }).addTo(group);
331
885
  }
332
- if (follow && !map.getBounds().pad(-.2).contains([lat, lng])) map.panTo([lat, lng], { animate: false });
886
+ for (const p of placed) if (p.fanned) L.polyline([tuple(p.at), tuple(p.shown)], {
887
+ color: resolveColour(el, "var(--muted-foreground)"),
888
+ weight: 1,
889
+ dashArray: "2 3",
890
+ interactive: false
891
+ }).addTo(group);
892
+ for (const { marker } of posMarkers.current.values()) marker.bringToFront();
893
+ return () => void group.remove();
333
894
  }, [
334
895
  map,
335
- lat,
336
- lng,
337
- follow,
896
+ markers,
897
+ routes,
898
+ placed,
338
899
  scheme
339
900
  ]);
901
+ React.useEffect(() => {
902
+ if (!map || !picking) return;
903
+ const el = map.getContainer();
904
+ el.classList.add("strata-map-picking");
905
+ map.keyboard.disable();
906
+ setAnnounced("Choose a place on the map. Arrow keys move the crosshair, Shift for bigger steps, Enter chooses, Escape cancels.");
907
+ let cross = null;
908
+ const showCross = (at) => {
909
+ if (!cross) cross = L.marker(at, {
910
+ interactive: false,
911
+ keyboard: false,
912
+ icon: L.divIcon({
913
+ className: "strata-map-crosshair",
914
+ html: CROSS_ICON,
915
+ iconSize: [32, 32],
916
+ iconAnchor: [16, 16]
917
+ })
918
+ }).addTo(map);
919
+ else cross.setLatLng(at);
920
+ };
921
+ const choose = (ll) => {
922
+ const at = [ll.lat, ll.lng];
923
+ const nearest = nearestRoute(latest.current.routes, at);
924
+ const route = nearest ? latest.current.routes.find((r) => r.id === nearest.routeId) : void 0;
925
+ setAnnounced(`Picked ${at[0].toFixed(5)}, ${at[1].toFixed(5)}.${nearest && route ? ` Nearest: ${route.label}, ${format.distance(nearest.alongM, latest.current.units)} along, ${format.distance(nearest.distanceM, latest.current.units)} from the route.` : ""}`);
926
+ latest.current.onPick?.(at, { nearest });
927
+ };
928
+ const onClick = (e) => {
929
+ cross?.remove();
930
+ cross = null;
931
+ choose(e.latlng);
932
+ };
933
+ const onKey = (e) => {
934
+ if (e.key === "Escape") {
935
+ e.preventDefault();
936
+ e.stopPropagation();
937
+ latest.current.onPickCancel?.();
938
+ return;
939
+ }
940
+ if (e.key === "Enter") {
941
+ e.preventDefault();
942
+ e.stopPropagation();
943
+ choose(cross ? cross.getLatLng() : map.getCenter());
944
+ return;
945
+ }
946
+ const step = e.shiftKey ? 50 : 10;
947
+ const d = {
948
+ ArrowLeft: [-step, 0],
949
+ ArrowRight: [step, 0],
950
+ ArrowUp: [0, -step],
951
+ ArrowDown: [0, step]
952
+ }[e.key];
953
+ if (!d) return;
954
+ e.preventDefault();
955
+ e.stopPropagation();
956
+ let to = map.latLngToContainerPoint(cross ? cross.getLatLng() : map.getCenter()).add(d);
957
+ const size = map.getSize();
958
+ const inside = L.point(Math.min(Math.max(to.x, 16), size.x - 16), Math.min(Math.max(to.y, 16), size.y - 16));
959
+ if (!inside.equals(to)) {
960
+ map.panBy(to.subtract(inside), { animate: false });
961
+ to = inside;
962
+ }
963
+ showCross(map.containerPointToLatLng(to));
964
+ };
965
+ map.on("click", onClick);
966
+ el.addEventListener("keydown", onKey);
967
+ return () => {
968
+ map.off("click", onClick);
969
+ el.removeEventListener("keydown", onKey);
970
+ cross?.remove();
971
+ el.classList.remove("strata-map-picking");
972
+ map.keyboard.enable();
973
+ };
974
+ }, [map, picking]);
340
975
  return /* @__PURE__ */ jsxs("div", {
341
976
  ref: root,
342
977
  "data-dark-treatment": treated ? "" : void 0,
@@ -351,17 +986,40 @@ function RouteMap({ label, routes, tiles, position = null, positionLabel = "Curr
351
986
  className: "sr-only",
352
987
  children: text
353
988
  }),
989
+ /* @__PURE__ */ jsx("p", {
990
+ role: "status",
991
+ "aria-live": "polite",
992
+ className: "sr-only",
993
+ children: announced
994
+ }),
995
+ map && placed.length > 0 && /* @__PURE__ */ jsx(MarkerLayer, {
996
+ map,
997
+ placed,
998
+ onSelect: onMarkerSelect,
999
+ card: renderMarkerCard
1000
+ }),
354
1001
  topEnd && /* @__PURE__ */ jsx("div", {
355
1002
  className: "absolute top-2 right-2 z-1000",
356
1003
  children: topEnd
357
1004
  }),
358
- (stops.length > 0 || bottomStart) && /* @__PURE__ */ jsxs("div", {
1005
+ picking && pickBanner && /* @__PURE__ */ jsx("div", {
1006
+ className: "absolute top-2 left-1/2 z-1000 max-w-[60%] -translate-x-1/2",
1007
+ children: pickBanner
1008
+ }),
1009
+ (stops.length > 0 || bottomStart || markers?.length && markerKey !== false) && /* @__PURE__ */ jsxs("div", {
359
1010
  className: "absolute bottom-6 left-2 z-1000 grid max-w-[60%] gap-2",
360
- children: [stops.length > 0 && /* @__PURE__ */ jsx(ColourKey, {
361
- stops,
362
- label: colourScaleLabel,
363
- formatValue
364
- }), bottomStart]
1011
+ children: [
1012
+ stops.length > 0 && /* @__PURE__ */ jsx(ColourKey, {
1013
+ stops,
1014
+ label: colourScaleLabel,
1015
+ formatValue
1016
+ }),
1017
+ markers && markers.length > 0 && markerKey !== false && /* @__PURE__ */ jsx(MarkerKey, {
1018
+ markers,
1019
+ words: markerKey
1020
+ }),
1021
+ bottomStart
1022
+ ]
365
1023
  })
366
1024
  ]
367
1025
  });
@@ -395,6 +1053,6 @@ function ColourKey({ stops, label, formatValue }) {
395
1053
  })]
396
1054
  });
397
1055
  }
398
- export { RouteMap };
1056
+ export { RouteMap, fanOut };
399
1057
 
400
1058
  //# sourceMappingURL=map.js.map