@loadmap/react 0.7.0 → 0.9.0

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.
@@ -0,0 +1,3715 @@
1
+ import { compare, headroom, reach } from "@loadmap/core";
2
+ import { compact, fmt, monthOf, multiple, multiples, pct, secs } from "@loadmap/core/format";
3
+ import { anchor, labelsAt, layout, legPath, localElk, pointAt, structureKey } from "@loadmap/layout";
4
+ import { memo, useCallback, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
5
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
6
+ import { morph, shapesOf } from "@loadmap/layout/internal";
7
+ import { createSim } from "@loadmap/sim";
8
+ // src/camera.ts
9
+ /**
10
+ * The shots of a story played, in seconds: the whole diagram first, then for each step a flight in to what it changes,
11
+ * a moment close, the change held close, a flight out, and the whole diagram for the step's own seconds. `back` is the
12
+ * flight out when the reader pauses.
13
+ */
14
+ const SHOTS = {
15
+ establish: 1.2,
16
+ in: 1,
17
+ close: .5,
18
+ out: 1,
19
+ back: .4
20
+ };
21
+ /** The change is held close until the structure has moved and settled. */
22
+ const changeSeconds = (transition) => Math.max(1.6, transition + .7);
23
+ /** A step played, from the flight in to the end of its hold on the whole diagram. */
24
+ const stepSeconds = (st, transition) => SHOTS.in + SHOTS.close + changeSeconds(transition) + SHOTS.out + st.seconds;
25
+ /** The whole story played, from the first shot of the whole diagram. */
26
+ const storySeconds = (story, transition) => story.reduce((t, st) => t + stepSeconds(st, transition), SHOTS.establish);
27
+ const whole = (s) => ({
28
+ x: 0,
29
+ y: 0,
30
+ w: s.width,
31
+ h: s.height
32
+ });
33
+ /** The component a box stands for: its stages' component, or its own. */
34
+ function boxComponent(ev, n) {
35
+ return n.stages.map((s) => ev.stages[s]?.component).find(Boolean) ?? n.component ?? void 0;
36
+ }
37
+ /**
38
+ * The boxes a step's change is about, from the values before (`a`) to the step's (`b`): the box it points at and any box
39
+ * the change reshapes; else the boxes it reshapes or an edge that comes or goes ends at; else those whose component
40
+ * changes state; else the first limit after it.
41
+ */
42
+ function targets(scene, a, b, shapes, focus) {
43
+ const ids = new Set(scene.nodes.map((n) => n.id));
44
+ const reshaped = /* @__PURE__ */ new Set();
45
+ for (const id of ids) if (shapes.a.nodes[id] !== shapes.b.nodes[id]) reshaped.add(id);
46
+ const edgesA = new Set(shapes.a.edges.map((e) => e.id));
47
+ const edgesB = new Set(shapes.b.edges.map((e) => e.id));
48
+ for (const e of [...shapes.a.edges, ...shapes.b.edges]) if (edgesA.has(e.id) !== edgesB.has(e.id)) {
49
+ for (const end of [e.from, e.to]) if (ids.has(end)) reshaped.add(end);
50
+ }
51
+ const of = (c) => scene.nodes.filter((n) => c && boxComponent(b, n) === c).map((n) => n.id);
52
+ const order = (s) => scene.nodes.filter((n) => s.has(n.id)).map((n) => n.id);
53
+ if (focus) return order(/* @__PURE__ */ new Set([...of(focus), ...reshaped]));
54
+ if (reshaped.size) return order(reshaped);
55
+ const turned = scene.nodes.filter((n) => {
56
+ const c = boxComponent(b, n);
57
+ return c && a.components[c]?.state !== b.components[c]?.state;
58
+ });
59
+ if (turned.length) return turned.map((n) => n.id);
60
+ return of(b.firstLimit?.id);
61
+ }
62
+ /** The closest the camera comes: the boxes framed never fill more than this share of the board's width. */
63
+ const MAX_ZOOM = 2.5;
64
+ /** Boxes that take more than this share of the board's width are shown on the whole diagram. */
65
+ const WIDE = .8;
66
+ /**
67
+ * The part of the scene that shows these boxes with room around them, at the scene's own shape (the board's), at most
68
+ * 2.5× closer, inside the scene. The whole scene when there is nothing to frame or it would hardly be closer; with
69
+ * `hold`, as wide as it takes instead (a framing that follows boxes as they grow never jumps out).
70
+ */
71
+ function framing(scene, ids, o = {}) {
72
+ const all = whole(scene);
73
+ const ns = scene.nodes.filter((n) => ids.includes(n.id));
74
+ if (!ns.length || !(scene.width > 0 && scene.height > 0)) return all;
75
+ const x0 = Math.min(...ns.map((n) => n.x));
76
+ const y0 = Math.min(...ns.map((n) => n.y));
77
+ const x1 = Math.max(...ns.map((n) => n.x + n.w));
78
+ const y1 = Math.max(...ns.map((n) => n.y + n.h));
79
+ const aspect = scene.width / scene.height;
80
+ let w = Math.max(x1 - x0 + 60, (y1 - y0 + 60) * aspect, scene.width / MAX_ZOOM);
81
+ if (w > WIDE * scene.width && !o.hold) return all;
82
+ w = Math.min(w, scene.width);
83
+ const h = w / aspect;
84
+ const clamp = (v, hi) => Math.max(0, Math.min(hi, v));
85
+ return {
86
+ x: clamp((x0 + x1 - w) / 2, scene.width - w),
87
+ y: clamp((y0 + y1 - h) / 2, scene.height - h),
88
+ w,
89
+ h
90
+ };
91
+ }
92
+ /** Cubic in and out. */
93
+ const ease = (t) => t < .5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2;
94
+ /**
95
+ * The camera `t` of the way from `a` to `b` (eased): the centre moves evenly, the size changes by the same factor
96
+ * each moment, so a zoom feels even whatever its depth.
97
+ */
98
+ function between(a, b, t) {
99
+ const k = ease(Math.max(0, Math.min(1, t)));
100
+ const w = a.w * (b.w / a.w) ** k;
101
+ const h = a.h * (b.h / a.h) ** k;
102
+ const cx = a.x + a.w / 2 + (b.x + b.w / 2 - a.x - a.w / 2) * k;
103
+ const cy = a.y + a.h / 2 + (b.y + b.h / 2 - a.y - a.h / 2) * k;
104
+ return {
105
+ x: cx - w / 2,
106
+ y: cy - h / 2,
107
+ w,
108
+ h
109
+ };
110
+ }
111
+ /** A label's first words: "Users, × today" says "Users". */
112
+ const short = (label) => label.split(",")[0].trim();
113
+ /** At most this many changed values in a title; the rest are counted. */
114
+ const TITLE_VALUES = 2;
115
+ /**
116
+ * The few words the diagram shows for a step: its own title, or what it changes ("Proposed: Gateway instances 1 → 2,
117
+ * Worker pods 3 → 6"), numbered.
118
+ */
119
+ function stepTitle(model, from, st, i) {
120
+ if (st.title) return `${i + 1} · ${st.title}`;
121
+ const say = (k, v) => {
122
+ if (k === "load") return `${fmt(v)}×`;
123
+ const def = model.params.find((x) => x.id === k)?.def;
124
+ if (typeof v === "boolean") return v ? "on" : "off";
125
+ if (def && def.kind !== "load" && "format" in def && def.format) return def.format(v);
126
+ return typeof v === "number" ? fmt(v) : String(v);
127
+ };
128
+ const changed = Object.keys(st.values).filter((k) => from[k] !== st.values[k]);
129
+ const parts = changed.slice(0, TITLE_VALUES).map((k) => {
130
+ const label = k === "load" ? model.load.label : model.params.find((x) => x.id === k)?.def.label ?? k;
131
+ const to = st.values[k];
132
+ const was = from[k];
133
+ return typeof to === "boolean" ? `${short(label)} ${say(k, to)}` : `${short(label)} ${say(k, was)} → ${say(k, to)}`;
134
+ });
135
+ if (changed.length > TITLE_VALUES) parts.push(`${changed.length - TITLE_VALUES} more`);
136
+ const what = parts.join(", ") || "Nothing changes";
137
+ return `${i + 1} · ${st.scenario && changed.length ? `${st.scenario}: ${what}` : what}`;
138
+ }
139
+ /** What the framed components show: their utilization now, or before and after the change. */
140
+ function stepDetail(a, b, components) {
141
+ return components.slice(0, 2).map((c) => {
142
+ const was = a.components[c];
143
+ const now = b?.components[c];
144
+ if (!was) return "";
145
+ const u = (x) => x == null ? "off" : pct(x);
146
+ return now ? `${was.name} ${u(was.util)} → ${u(now.util)}` : `${was.name} ${u(was.util)}`;
147
+ }).filter(Boolean).join(" · ");
148
+ }
149
+ // src/scenarios.tsx
150
+ /** Scenario identity colours, in declaration order; a fifth and later scenario is drawn muted. */
151
+ const SERIES = [
152
+ "var(--lm-s1)",
153
+ "var(--lm-s2)",
154
+ "var(--lm-s3)",
155
+ "var(--lm-s4)"
156
+ ];
157
+ /** The colour of a scenario by label; values of the reader's own are drawn in the text colour. */
158
+ function scenarioColor(model, label) {
159
+ if (label == null) return "var(--lm-fg)";
160
+ const i = model.scenarios.findIndex((s) => s.label === label);
161
+ return SERIES[i] ?? "var(--lm-muted)";
162
+ }
163
+ const lineName = (l) => l.label ?? "These values";
164
+ /** A month for a table cell or an axis: "Mar 2031"; "now" for a crossing already reached. */
165
+ function when(model, x) {
166
+ const d = model.dateAt(x);
167
+ return d ? monthOf(d, true) : x != null && x <= 1 && model.growth ? "now" : "";
168
+ }
169
+ /** The months of both edges: "Sep 2029–Feb 2030", or one month when they agree. */
170
+ function whenRange(model, r) {
171
+ if (!r) return "";
172
+ const [lo, hi] = [when(model, r.low), when(model, r.high)];
173
+ return !hi || lo === hi ? lo : `${lo}–${hi}`;
174
+ }
175
+ /** The comparison at the shown load: crossings do not depend on it, the verdicts do. */
176
+ function useComparison(lm) {
177
+ return useMemo(() => compare(lm.model, lm.values.load), [lm.model, lm.values.load]);
178
+ }
179
+ /** One button per scenario: a reader switches designs without touching the controls. The load stays. */
180
+ function Scenarios({ lm }) {
181
+ const { model } = lm;
182
+ if (!model.scenarios.length) return null;
183
+ return /* @__PURE__ */ jsxs("fieldset", {
184
+ className: "lm-scenarios",
185
+ children: [
186
+ /* @__PURE__ */ jsx("legend", { children: "Scenario" }),
187
+ model.scenarios.map((s) => /* @__PURE__ */ jsxs("button", {
188
+ type: "button",
189
+ "aria-pressed": lm.scenario?.label === s.label,
190
+ onClick: () => lm.setScenario(s.label),
191
+ children: [/* @__PURE__ */ jsx("i", { style: { background: scenarioColor(model, s.label) } }), s.label]
192
+ }, s.label)),
193
+ !lm.scenario && /* @__PURE__ */ jsx("span", {
194
+ className: "lm-own",
195
+ children: "your own values"
196
+ })
197
+ ]
198
+ });
199
+ }
200
+ /** "+107 %" against the baseline; "same" within a rounding; nothing where either never runs out. */
201
+ function change(x) {
202
+ if (x == null || !Number.isFinite(x) || x === 0) return "";
203
+ if (Math.abs(x - 1) < .005) return "same";
204
+ return `${x > 1 ? "+" : "−"}${pct(Math.abs(x - 1))}`;
205
+ }
206
+ /** The scenarios side by side: which buys more headroom, where each first runs out, and per component. */
207
+ function Compare({ lm, title = "Scenarios compared" }) {
208
+ const { model } = lm;
209
+ const c = useComparison(lm);
210
+ if (c.rows.length < 2) return null;
211
+ const target = `${pct(model.thresholds.target)} target`;
212
+ const at = (r) => /* @__PURE__ */ jsxs(Fragment, { children: [r ? multiples(r, model.searchMax, true) : multiple(null), whenRange(model, r) && /* @__PURE__ */ jsx("small", { children: whenRange(model, r) })] });
213
+ return /* @__PURE__ */ jsxs("div", {
214
+ className: "lm-card lm-compare",
215
+ children: [
216
+ /* @__PURE__ */ jsx("h3", { children: title }),
217
+ /* @__PURE__ */ jsx("p", {
218
+ className: "lm-compare-text",
219
+ children: c.text
220
+ }),
221
+ /* @__PURE__ */ jsx("div", {
222
+ className: "lm-table-wrap",
223
+ children: /* @__PURE__ */ jsxs("table", {
224
+ className: "lm-table",
225
+ children: [/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [
226
+ /* @__PURE__ */ jsx("th", {
227
+ scope: "col",
228
+ children: "Scenario"
229
+ }),
230
+ /* @__PURE__ */ jsx("th", {
231
+ scope: "col",
232
+ children: "First limit"
233
+ }),
234
+ /* @__PURE__ */ jsx("th", {
235
+ scope: "col",
236
+ children: target
237
+ }),
238
+ /* @__PURE__ */ jsx("th", {
239
+ scope: "col",
240
+ children: "Runs out"
241
+ })
242
+ ] }) }), /* @__PURE__ */ jsx("tbody", { children: c.rows.map((r) => /* @__PURE__ */ jsxs("tr", {
243
+ "data-scenario": r.label,
244
+ "aria-current": lm.scenario?.label === r.label || void 0,
245
+ children: [
246
+ /* @__PURE__ */ jsxs("th", {
247
+ scope: "row",
248
+ children: [/* @__PURE__ */ jsx("i", { style: { background: scenarioColor(model, r.label) } }), r.label]
249
+ }),
250
+ /* @__PURE__ */ jsx("td", {
251
+ className: "lm-text",
252
+ children: r.firstLimit?.name ?? "—"
253
+ }),
254
+ /* @__PURE__ */ jsx("td", {
255
+ "data-multiple": r.target ?? "",
256
+ "data-high": r.targetRange?.high ?? "",
257
+ children: at(r.targetRange)
258
+ }),
259
+ /* @__PURE__ */ jsx("td", {
260
+ "data-multiple": r.full ?? "",
261
+ "data-high": r.fullRange?.high ?? "",
262
+ children: at(r.fullRange)
263
+ })
264
+ ]
265
+ }, r.label)) })]
266
+ })
267
+ }),
268
+ /* @__PURE__ */ jsxs("h3", { children: [target, ", by component"] }),
269
+ /* @__PURE__ */ jsx("div", {
270
+ className: "lm-table-wrap",
271
+ children: /* @__PURE__ */ jsxs("table", {
272
+ className: "lm-table",
273
+ children: [/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [/* @__PURE__ */ jsx("th", {
274
+ scope: "col",
275
+ children: "Component"
276
+ }), c.rows.map((r) => /* @__PURE__ */ jsx("th", {
277
+ scope: "col",
278
+ children: r.label
279
+ }, r.label))] }) }), /* @__PURE__ */ jsx("tbody", { children: model.componentIds.map((id, k) => /* @__PURE__ */ jsxs("tr", {
280
+ "data-component": id,
281
+ children: [/* @__PURE__ */ jsx("th", {
282
+ scope: "row",
283
+ children: c.rows[0].components[k].name
284
+ }), c.rows.map((r, i) => {
285
+ const x = r.components[k];
286
+ return /* @__PURE__ */ jsxs("td", {
287
+ "data-multiple": x.target ?? "",
288
+ children: [x.targetRange == null ? "off" : multiples(x.targetRange, model.searchMax, true), i > 0 && change(x.change) && /* @__PURE__ */ jsx("small", { children: change(x.change) })]
289
+ }, r.label);
290
+ })]
291
+ }, id)) })]
292
+ })
293
+ })
294
+ ]
295
+ });
296
+ }
297
+ /** The size of an element in CSS pixels, kept current: a chart draws at its own size so text stays legible. */
298
+ function useSize(fallback) {
299
+ const ref = useRef(null);
300
+ const [size, setSize] = useState({
301
+ width: fallback,
302
+ height: 0
303
+ });
304
+ useEffect(() => {
305
+ const el = ref.current;
306
+ if (!el) return;
307
+ const ro = new ResizeObserver(([e]) => {
308
+ const width = Math.round(e?.contentRect.width ?? el.clientWidth);
309
+ const height = Math.round(e?.contentRect.height ?? el.clientHeight);
310
+ if (width > 0) setSize((s) => s.width === width && s.height === height ? s : {
311
+ width,
312
+ height
313
+ });
314
+ });
315
+ ro.observe(el);
316
+ return () => ro.disconnect();
317
+ }, []);
318
+ return [ref, size];
319
+ }
320
+ /** Every scenario's line over the load: it depends on every value but the load, which is only the marker. */
321
+ function useHeadroom(lm) {
322
+ const { model, values } = lm;
323
+ const rest = JSON.stringify({
324
+ ...values,
325
+ load: null
326
+ });
327
+ return useMemo(() => headroom(model, {
328
+ ...values,
329
+ load: model.load.default
330
+ }), [model, rest]);
331
+ }
332
+ /**
333
+ * The width of a label in the chart's 11 px monospace (`--lm-mono`), measured once the chart is on the page, so its
334
+ * labels are kept inside it whatever the theme's font.
335
+ */
336
+ function useAxisMeasure(el) {
337
+ const [measure, setMeasure] = useState(() => (text, _weight) => text.length * 6.7);
338
+ useLayoutEffect(() => {
339
+ const ctx = el.current && document.createElement("canvas").getContext("2d");
340
+ if (!ctx) return;
341
+ const font = getComputedStyle(el.current).getPropertyValue("--lm-mono").trim() || "monospace";
342
+ setMeasure(() => (text, weight = 400) => {
343
+ ctx.font = `${weight} 11px ${font}`;
344
+ return ctx.measureText(text).width;
345
+ });
346
+ }, [el]);
347
+ return measure;
348
+ }
349
+ /** 1, 2, 5, 10, 20, 50, … inside [from, to]; decades only when there is little room. */
350
+ function ticks(from, to, roomy) {
351
+ const out = [];
352
+ for (let d = Math.floor(Math.log10(from)); d <= Math.ceil(Math.log10(to)); d++) for (const k of roomy ? [
353
+ 1,
354
+ 2,
355
+ 5
356
+ ] : [1]) {
357
+ const v = k * 10 ** d;
358
+ if (v >= from * .999 && v <= to * 1.001) out.push(Number(v.toPrecision(6)));
359
+ }
360
+ return out;
361
+ }
362
+ /**
363
+ * Utilization over the load multiple. Each scenario's line is its highest utilization, so it crosses the target and
364
+ * 100 % exactly where its first limit does; the dots are those crossings, taken from the limits, not from the line.
365
+ * With a ± on a capacity, a band shows the line at every capacity's low and high bound, and a bracket on the target
366
+ * and 100 % lines spans where the band crosses them. The shown scenario's components are the thin lines under it.
367
+ * Hover or arrow keys read every line at one load.
368
+ */
369
+ function HeadroomChart({ lm, title = "Headroom" }) {
370
+ const { model, values } = lm;
371
+ const h = useHeadroom(lm);
372
+ const [wrap, { width }] = useSize(640);
373
+ const [hover, setHover] = useState(null);
374
+ const clip = useId().replace(/:/g, "");
375
+ const measure = useAxisMeasure(wrap);
376
+ const tip = useRef(null);
377
+ useLayoutEffect(() => {
378
+ const el = tip.current;
379
+ if (el && hover != null) el.style.left = `${Math.max(0, Math.min(lx(xs[hover]) + 10, W - el.offsetWidth))}px`;
380
+ });
381
+ const dated = !!model.growth;
382
+ const m = {
383
+ l: 44,
384
+ r: 14,
385
+ t: 14,
386
+ b: dated ? 40 : 26
387
+ };
388
+ const W = width;
389
+ const H = Math.round(Math.min(300, Math.max(200, W * .45)));
390
+ const pw = W - m.l - m.r;
391
+ const ph = H - m.t - m.b;
392
+ const top = Math.max(1.5, model.thresholds.full * 1.5);
393
+ const lx = (x) => m.l + pw * Math.log(x / h.from) / Math.log(h.to / h.from);
394
+ const ly = (u) => m.t + ph * (1 - Math.min(u, top * 1.2) / top);
395
+ const path = (s) => {
396
+ let d = "";
397
+ let pen = false;
398
+ for (const [x, u] of s) {
399
+ if (u == null) {
400
+ pen = false;
401
+ continue;
402
+ }
403
+ d += `${pen ? "L" : "M"}${lx(x).toFixed(1)} ${ly(u).toFixed(1)}`;
404
+ pen = true;
405
+ }
406
+ return d;
407
+ };
408
+ const xs = h.lines[0]?.envelope.map(([x]) => x) ?? [];
409
+ const selected = h.lines.find((l) => l.selected);
410
+ const roomy = W >= 480;
411
+ const tickList = ticks(h.from, h.to, roomy);
412
+ const labelled = (x) => roomy || Number.isInteger(Math.log10(x));
413
+ const near = (px) => {
414
+ let best = 0;
415
+ for (let i = 1; i < xs.length; i++) if (Math.abs(lx(xs[i]) - px) < Math.abs(lx(xs[best]) - px)) best = i;
416
+ return best;
417
+ };
418
+ const onMove = (e) => {
419
+ const r = e.currentTarget.ownerSVGElement.getBoundingClientRect();
420
+ setHover(near(e.clientX - r.left));
421
+ };
422
+ const onKey = (e) => {
423
+ const i = hover ?? near(lx(Math.min(h.to, Math.max(h.from, values.load))));
424
+ if (e.key === "ArrowRight" || e.key === "ArrowLeft") {
425
+ e.preventDefault();
426
+ setHover(Math.max(0, Math.min(xs.length - 1, i + (e.key === "ArrowRight" ? 1 : -1))));
427
+ } else if (e.key === "Escape") setHover(null);
428
+ };
429
+ const area = (b) => {
430
+ const both = b.upper.flatMap(([x, u], i) => {
431
+ const v = b.lower[i][1];
432
+ return u == null || v == null ? [] : [[
433
+ x,
434
+ u,
435
+ v
436
+ ]];
437
+ });
438
+ if (both.length < 2) return "";
439
+ const up = both.map(([x, u]) => `${lx(x).toFixed(1)} ${ly(u).toFixed(1)}`);
440
+ const down = both.map(([x, , v]) => `${lx(x).toFixed(1)} ${ly(v).toFixed(1)}`).reverse();
441
+ return `M${up.join("L")}L${down.join("L")}Z`;
442
+ };
443
+ const reaches = (r, x) => r && l0(r) ? multiples(r, model.searchMax) : multiple(x, model.searchMax);
444
+ const l0 = (r) => multiple(r.low, model.searchMax) !== multiple(r.high, model.searchMax);
445
+ const summary = h.lines.map((l) => `${lineName(l)} reaches the ${pct(model.thresholds.target)} target at ${reaches(l.targetRange, l.target)} and ${pct(model.thresholds.full)} at ${reaches(l.fullRange, l.full)}`).join("; ");
446
+ const loadX = lx(Math.min(h.to, Math.max(h.from, values.load)));
447
+ const hx = hover == null ? null : xs[hover];
448
+ const fromLeft = {
449
+ x: 0,
450
+ textAnchor: "start"
451
+ };
452
+ const fromRight = {
453
+ x: W,
454
+ textAnchor: "end"
455
+ };
456
+ /** A label beside a line at x: on the side it prefers if it fits, else the other, else against the nearer edge. */
457
+ const beside = (x, w, prefer, gap = 4) => {
458
+ const right = {
459
+ x: x + gap,
460
+ textAnchor: "start"
461
+ };
462
+ const left = {
463
+ x: x - gap,
464
+ textAnchor: "end"
465
+ };
466
+ const fitsRight = x + gap + w <= W;
467
+ const fitsLeft = x - gap - w >= 0;
468
+ if (prefer === "right" ? fitsRight : !fitsLeft && fitsRight) return right;
469
+ if (fitsLeft) return left;
470
+ return x < W / 2 ? fromLeft : fromRight;
471
+ };
472
+ /** A label centred on x, unless that passes an edge. */
473
+ const centred = (x, w) => x - w / 2 < 0 ? fromLeft : x + w / 2 > W ? fromRight : {
474
+ x,
475
+ textAnchor: "middle"
476
+ };
477
+ const shown = `shown: ${fmt(values.load)}×`;
478
+ /** A crossing's multiple, left of its dot where it fits. */
479
+ const mark = (t, x, y) => /* @__PURE__ */ jsx("text", {
480
+ ...beside(x, measure(t, 600), "left", 6),
481
+ y,
482
+ className: "lm-mark",
483
+ children: t
484
+ });
485
+ return /* @__PURE__ */ jsxs("div", {
486
+ className: "lm-card lm-headroom",
487
+ children: [
488
+ /* @__PURE__ */ jsx("h3", { children: title }),
489
+ h.lines.length > 1 && /* @__PURE__ */ jsxs("div", {
490
+ className: "lm-legend",
491
+ children: [h.lines.map((l) => /* @__PURE__ */ jsxs("span", { children: [/* @__PURE__ */ jsx("b", {
492
+ className: "lm-key",
493
+ style: { background: scenarioColor(model, l.label) }
494
+ }), lineName(l)] }, lineName(l))), selected && /* @__PURE__ */ jsxs("span", { children: ["thin lines: each component of ", lineName(selected)] })]
495
+ }),
496
+ /* @__PURE__ */ jsxs("div", {
497
+ className: "lm-chart",
498
+ ref: wrap,
499
+ role: "slider",
500
+ "aria-label": `Utilization over the load multiple. ${summary}.`,
501
+ "aria-valuemin": h.from,
502
+ "aria-valuemax": h.to,
503
+ "aria-valuenow": hx ?? values.load,
504
+ "aria-valuetext": hx == null ? `${fmt(values.load)}×` : `${fmt(hx)}×: ${h.lines.map((l) => `${lineName(l)} ${l.envelope[hover][1] == null ? "off" : pct(l.envelope[hover][1])}`).join(", ")}`,
505
+ tabIndex: 0,
506
+ onKeyDown: onKey,
507
+ onBlur: () => setHover(null),
508
+ children: [/* @__PURE__ */ jsxs("svg", {
509
+ width: W,
510
+ height: H,
511
+ viewBox: `0 0 ${W} ${H}`,
512
+ "aria-hidden": "true",
513
+ children: [
514
+ /* @__PURE__ */ jsx("defs", { children: /* @__PURE__ */ jsx("clipPath", {
515
+ id: clip,
516
+ children: /* @__PURE__ */ jsx("rect", {
517
+ x: m.l,
518
+ y: m.t,
519
+ width: pw,
520
+ height: ph + 2
521
+ })
522
+ }) }),
523
+ [
524
+ 0,
525
+ model.thresholds.target,
526
+ model.thresholds.full
527
+ ].map((u) => /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("line", {
528
+ x1: m.l,
529
+ x2: W - m.r,
530
+ y1: ly(u),
531
+ y2: ly(u),
532
+ stroke: "var(--lm-line)"
533
+ }), /* @__PURE__ */ jsx("text", {
534
+ x: m.l - 6,
535
+ y: ly(u) + 4,
536
+ textAnchor: "end",
537
+ className: "lm-axis",
538
+ children: pct(u)
539
+ })] }, u)),
540
+ /* @__PURE__ */ jsx("text", {
541
+ x: W - m.r,
542
+ y: ly(model.thresholds.target) - 5,
543
+ textAnchor: "end",
544
+ className: "lm-axis",
545
+ children: "target"
546
+ }),
547
+ tickList.map((x) => {
548
+ const label = `${fmt(x)}×`;
549
+ const date = dated && x > 1 ? when(model, x) : "";
550
+ return /* @__PURE__ */ jsxs("g", {
551
+ className: "lm-axis",
552
+ children: [/* @__PURE__ */ jsx("line", {
553
+ x1: lx(x),
554
+ x2: lx(x),
555
+ y1: m.t + ph,
556
+ y2: m.t + ph + 4,
557
+ stroke: "var(--lm-line)"
558
+ }), labelled(x) && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("text", {
559
+ ...centred(lx(x), measure(label)),
560
+ y: m.t + ph + 16,
561
+ children: label
562
+ }), date && /* @__PURE__ */ jsx("text", {
563
+ ...centred(lx(x), measure(date)),
564
+ y: m.t + ph + 30,
565
+ children: date
566
+ })] })]
567
+ }, x);
568
+ }),
569
+ /* @__PURE__ */ jsxs("g", {
570
+ clipPath: `url(#${clip})`,
571
+ children: [
572
+ [...h.lines].sort((a, b) => Number(a.selected) - Number(b.selected)).map((l) => l.band ? /* @__PURE__ */ jsx("path", {
573
+ "data-band": lineName(l),
574
+ d: area(l.band),
575
+ fill: scenarioColor(model, l.label),
576
+ fillOpacity: l.selected ? .2 : .08
577
+ }, lineName(l)) : null),
578
+ selected?.components.map((c) => /* @__PURE__ */ jsx("path", {
579
+ d: path(c.points),
580
+ fill: "none",
581
+ stroke: "var(--lm-muted)",
582
+ strokeOpacity: ".55",
583
+ strokeWidth: "1"
584
+ }, c.id)),
585
+ [...h.lines].sort((a, b) => Number(a.selected) - Number(b.selected)).map((l) => /* @__PURE__ */ jsx("path", {
586
+ "data-line": lineName(l),
587
+ d: path(l.envelope),
588
+ fill: "none",
589
+ stroke: scenarioColor(model, l.label),
590
+ strokeWidth: "2",
591
+ strokeLinejoin: "round",
592
+ strokeLinecap: "round"
593
+ }, lineName(l)))
594
+ ]
595
+ }),
596
+ /* @__PURE__ */ jsx("line", {
597
+ x1: loadX,
598
+ x2: loadX,
599
+ y1: m.t,
600
+ y2: m.t + ph,
601
+ stroke: "var(--lm-fg)",
602
+ strokeOpacity: ".45"
603
+ }),
604
+ /* @__PURE__ */ jsx("text", {
605
+ ...beside(loadX, measure(shown), "right"),
606
+ y: m.t + 10,
607
+ className: "lm-axis",
608
+ children: shown
609
+ }),
610
+ h.lines.flatMap((l) => [[
611
+ "target",
612
+ l.targetRange,
613
+ model.thresholds.target
614
+ ], [
615
+ "full",
616
+ l.fullRange,
617
+ model.thresholds.full
618
+ ]].map(([kind, r, u]) => {
619
+ if (!l.band || !r || !Number.isFinite(r.low) || r.low > h.to) return null;
620
+ const [x1, x2] = [lx(Math.max(h.from, r.low)), lx(Math.min(h.to, r.high))];
621
+ const y = ly(u);
622
+ return /* @__PURE__ */ jsxs("g", {
623
+ "data-range": kind,
624
+ "data-scenario": lineName(l),
625
+ "data-low": r.low,
626
+ "data-high": r.high,
627
+ stroke: scenarioColor(model, l.label),
628
+ strokeWidth: l.selected ? 3 : 2,
629
+ strokeOpacity: l.selected ? 1 : .6,
630
+ children: [
631
+ /* @__PURE__ */ jsx("line", {
632
+ x1,
633
+ x2,
634
+ y1: y,
635
+ y2: y
636
+ }),
637
+ /* @__PURE__ */ jsx("line", {
638
+ x1,
639
+ x2: x1,
640
+ y1: y - 5,
641
+ y2: y + 5
642
+ }),
643
+ Number.isFinite(r.high) && r.high <= h.to && /* @__PURE__ */ jsx("line", {
644
+ x1: x2,
645
+ x2,
646
+ y1: y - 5,
647
+ y2: y + 5
648
+ })
649
+ ]
650
+ }, `${lineName(l)}/${kind}/range`);
651
+ })),
652
+ h.lines.flatMap((l) => [[
653
+ "target",
654
+ l.target,
655
+ l.targetRange,
656
+ model.thresholds.target
657
+ ], [
658
+ "full",
659
+ l.full,
660
+ l.fullRange,
661
+ model.thresholds.full
662
+ ]].map(([kind, x, r, u]) => x != null && Number.isFinite(x) && x >= h.from && x <= h.to ? /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("circle", {
663
+ "data-crossing": kind,
664
+ "data-scenario": lineName(l),
665
+ "data-multiple": x,
666
+ cx: lx(x),
667
+ cy: ly(u),
668
+ r: "4",
669
+ fill: scenarioColor(model, l.label),
670
+ stroke: "var(--lm-surface)",
671
+ strokeWidth: "2"
672
+ }), l.selected && mark(r && l0(r) ? multiples(r, model.searchMax, true) : multiple(x, model.searchMax), lx(r && l0(r) ? Math.max(h.from, r.low) : x), ly(u) - 8)] }, `${lineName(l)}/${kind}`) : null)),
673
+ hx != null && /* @__PURE__ */ jsx("line", {
674
+ x1: lx(hx),
675
+ x2: lx(hx),
676
+ y1: m.t,
677
+ y2: m.t + ph,
678
+ stroke: "var(--lm-fg)",
679
+ strokeOpacity: ".8"
680
+ }),
681
+ /* @__PURE__ */ jsx("rect", {
682
+ x: m.l,
683
+ y: m.t,
684
+ width: pw,
685
+ height: ph,
686
+ fill: "transparent",
687
+ onPointerMove: onMove,
688
+ onPointerDown: onMove,
689
+ onPointerLeave: () => setHover(null)
690
+ })
691
+ ]
692
+ }), hover != null && hx != null && /* @__PURE__ */ jsxs("div", {
693
+ className: "lm-tip",
694
+ role: "status",
695
+ ref: tip,
696
+ style: {
697
+ left: lx(hx) + 10,
698
+ top: m.t
699
+ },
700
+ children: [
701
+ /* @__PURE__ */ jsxs("b", { children: [
702
+ fmt(hx),
703
+ "×",
704
+ when(model, hx) && ` · ${when(model, hx)}`
705
+ ] }),
706
+ h.lines.map((l) => /* @__PURE__ */ jsxs("span", { children: [
707
+ /* @__PURE__ */ jsx("b", {
708
+ className: "lm-key",
709
+ style: { background: scenarioColor(model, l.label) }
710
+ }),
711
+ /* @__PURE__ */ jsx("strong", { children: l.envelope[hover][1] == null ? "off" : pct(l.envelope[hover][1]) }),
712
+ " ",
713
+ lineName(l)
714
+ ] }, lineName(l))),
715
+ selected?.components.map((c) => /* @__PURE__ */ jsxs("span", {
716
+ className: "lm-sub",
717
+ children: [
718
+ /* @__PURE__ */ jsx("strong", { children: c.points[hover][1] == null ? "off" : pct(c.points[hover][1]) }),
719
+ " ",
720
+ c.name
721
+ ]
722
+ }, c.id))
723
+ ]
724
+ })]
725
+ })
726
+ ]
727
+ });
728
+ }
729
+ // src/Diagram.tsx
730
+ const STATE_STROKE = {
731
+ off: "var(--lm-line)",
732
+ ok: "var(--lm-ok)",
733
+ warn: "var(--lm-warn)",
734
+ over: "var(--lm-drop)"
735
+ };
736
+ const tokenColor = (c) => [
737
+ "accent",
738
+ "alt",
739
+ "ok",
740
+ "warn",
741
+ "drop",
742
+ "muted"
743
+ ].includes(c) ? `var(--lm-${c})` : c;
744
+ function Diagram({ lm, legend = true, onNodeClick, selected = null }) {
745
+ const { scene, engine, reducedMotion } = lm;
746
+ const click = useRef(onNodeClick);
747
+ click.current = onNodeClick;
748
+ const [onClick] = useState(() => (id) => click.current?.(id));
749
+ const svgRef = useRef(null);
750
+ const canvasRef = useRef(null);
751
+ const wrapRef = useRef(null);
752
+ const barRef = useRef(null);
753
+ const boardRef = useRef(null);
754
+ const buttonRef = useRef(null);
755
+ const titleRef = useRef(null);
756
+ const full = lm.fullScreen;
757
+ const [tip, setTip] = useState(null);
758
+ const detailId = useId();
759
+ useLayoutEffect(() => {
760
+ if (scene) engine.setScene(scene, { cut: reducedMotion });
761
+ }, [
762
+ engine,
763
+ scene,
764
+ reducedMotion
765
+ ]);
766
+ const frameId = useSyncExternalStore(engine.subscribe, () => engine.frameId);
767
+ const frame = engine.frame;
768
+ useEffect(() => {
769
+ engine.bind(svgRef.current, canvasRef.current);
770
+ }, [
771
+ engine,
772
+ frame,
773
+ reducedMotion
774
+ ]);
775
+ useLayoutEffect(() => engine.applyCamera());
776
+ useEffect(() => {
777
+ if (lm.root) engine.readColors(lm.root);
778
+ }, [
779
+ engine,
780
+ scene,
781
+ lm.root
782
+ ]);
783
+ useEffect(() => {
784
+ engine.drawnValues = JSON.stringify(lm.values);
785
+ engine.drawnFocus = lm.focus;
786
+ engine.drawnFrame = frameId;
787
+ });
788
+ useEffect(() => {
789
+ const board = boardRef.current;
790
+ if (!board) return;
791
+ const ro = new ResizeObserver(() => engine.resize());
792
+ ro.observe(board);
793
+ return () => ro.disconnect();
794
+ }, [engine]);
795
+ const follow = () => {
796
+ const wrap = wrapRef.current;
797
+ const board = boardRef.current;
798
+ const c = engine.camera;
799
+ const title = titleRef.current;
800
+ if (!c && !engine.cue) return;
801
+ if (!wrap || !board || !engine.frame || wrap.scrollHeight <= wrap.clientHeight) {
802
+ title?.style.removeProperty("top");
803
+ title?.style.removeProperty("bottom");
804
+ return;
805
+ }
806
+ const k = board.clientHeight / engine.frame.height;
807
+ if (c) wrap.scrollTop = board.offsetTop + (c.y + c.h / 2) * k - wrap.clientHeight / 2;
808
+ if (title) {
809
+ title.style.top = `${Math.max(0, wrap.scrollTop - board.offsetTop + (barRef.current?.offsetHeight ?? 0))}px`;
810
+ title.style.bottom = "auto";
811
+ }
812
+ };
813
+ useEffect(() => {
814
+ let raf = 0;
815
+ let last = 0;
816
+ const frame = (ts) => {
817
+ const dt = last ? Math.min(.05, (ts - last) / 1e3) : 0;
818
+ last = ts;
819
+ if (!engine.paused && engine.scene) {
820
+ engine.step(dt, { particles: !reducedMotion });
821
+ engine.draw({ particles: !reducedMotion });
822
+ follow();
823
+ }
824
+ raf = requestAnimationFrame(frame);
825
+ };
826
+ raf = requestAnimationFrame(frame);
827
+ return () => cancelAnimationFrame(raf);
828
+ }, [engine, reducedMotion]);
829
+ const was = useRef(false);
830
+ useEffect(() => {
831
+ if (was.current && !full) buttonRef.current?.focus();
832
+ was.current = full;
833
+ }, [full]);
834
+ useEffect(() => {
835
+ const wrap = wrapRef.current;
836
+ const bar = barRef.current;
837
+ const root = lm.root;
838
+ if (!full || !scene || !wrap || !bar || !root) return;
839
+ const px = (x) => Number.parseFloat(x) || 0;
840
+ const fit = () => {
841
+ const rs = getComputedStyle(root);
842
+ let around = px(rs.paddingTop) + px(rs.paddingBottom);
843
+ const add = (el) => {
844
+ const cs = getComputedStyle(el);
845
+ if (cs.display === "none" || cs.position === "absolute" || cs.position === "fixed") return;
846
+ around += px(rs.rowGap) + (px(cs.flexGrow) > 0 ? px(cs.minHeight) : el.offsetHeight);
847
+ };
848
+ for (const el of root.children) if (el !== wrap) add(el);
849
+ if (getComputedStyle(root, "::after").content !== "none") around += px(rs.rowGap);
850
+ const h = root.clientHeight - around - bar.offsetHeight - px(getComputedStyle(wrap).rowGap);
851
+ const w = Math.min(wrap.clientWidth, h * scene.width / scene.height);
852
+ wrap.style.setProperty("--lm-fit", `${Math.max(0, Math.floor(w))}px`);
853
+ };
854
+ const ro = new ResizeObserver(fit);
855
+ const watch = () => {
856
+ ro.disconnect();
857
+ ro.observe(bar);
858
+ ro.observe(root);
859
+ for (const el of root.children) ro.observe(el);
860
+ };
861
+ watch();
862
+ const mo = new MutationObserver(() => {
863
+ watch();
864
+ fit();
865
+ });
866
+ mo.observe(root, {
867
+ childList: true,
868
+ attributeFilter: ["data-mode"]
869
+ });
870
+ return () => {
871
+ ro.disconnect();
872
+ mo.disconnect();
873
+ wrap.style.removeProperty("--lm-fit");
874
+ };
875
+ }, [
876
+ full,
877
+ scene,
878
+ lm.root
879
+ ]);
880
+ const { setFullScreenMode, fullScreenMode } = lm;
881
+ const modesRef = useRef(null);
882
+ useEffect(() => {
883
+ const root = lm.root;
884
+ if (!full || !root) return;
885
+ const f = (e) => {
886
+ if (e.key !== "f" && e.key !== "F" || e.ctrlKey || e.metaKey || e.altKey) return;
887
+ if (typing(e.composedPath()[0] ?? null) || root.querySelector(":scope > [data-drawer]")) return;
888
+ e.preventDefault();
889
+ if (e.repeat) return;
890
+ const next = fullScreenMode === "focus" ? "panels" : "focus";
891
+ if (document.activeElement?.closest(".lm-dock, .lm-line")) modesRef.current?.querySelector(`[data-mode="${next}"]`)?.focus();
892
+ setFullScreenMode(next);
893
+ };
894
+ document.addEventListener("keydown", f);
895
+ return () => document.removeEventListener("keydown", f);
896
+ }, [
897
+ full,
898
+ fullScreenMode,
899
+ setFullScreenMode,
900
+ lm.root
901
+ ]);
902
+ return /* @__PURE__ */ jsxs("div", {
903
+ className: "lm-wrap",
904
+ ref: wrapRef,
905
+ children: [
906
+ /* @__PURE__ */ jsxs("div", {
907
+ className: "lm-bar",
908
+ ref: barRef,
909
+ children: [legend ? /* @__PURE__ */ jsx(Legend, { lm }) : /* @__PURE__ */ jsx("span", {}), /* @__PURE__ */ jsxs("span", {
910
+ className: "lm-tools",
911
+ children: [full && /* @__PURE__ */ jsx("fieldset", {
912
+ className: "lm-modes",
913
+ "aria-label": "Full screen shows (F)",
914
+ ref: modesRef,
915
+ children: ["panels", "focus"].map((m) => /* @__PURE__ */ jsx("button", {
916
+ type: "button",
917
+ "data-mode": m,
918
+ "aria-pressed": fullScreenMode === m,
919
+ "aria-keyshortcuts": "F",
920
+ onClick: () => setFullScreenMode(m),
921
+ children: m === "panels" ? "Panels" : "Focus"
922
+ }, m))
923
+ }), /* @__PURE__ */ jsx("button", {
924
+ type: "button",
925
+ className: "lm-btn",
926
+ onClick: lm.toggleFullScreen,
927
+ "aria-pressed": full,
928
+ ref: buttonRef,
929
+ children: full ? "✕ Close" : "⤢ Full screen"
930
+ })]
931
+ })]
932
+ }),
933
+ /* @__PURE__ */ jsxs("div", {
934
+ className: "lm-board",
935
+ ref: boardRef,
936
+ style: frame ? { aspectRatio: `${frame.width} / ${frame.height}` } : { minHeight: 240 },
937
+ children: [
938
+ frame && /* @__PURE__ */ jsx(Structure, {
939
+ lm,
940
+ scene: frame,
941
+ svgRef,
942
+ rates: reducedMotion,
943
+ setTip,
944
+ onClick: onNodeClick ? onClick : void 0,
945
+ selected
946
+ }),
947
+ /* @__PURE__ */ jsx("canvas", {
948
+ ref: canvasRef,
949
+ hidden: reducedMotion
950
+ }),
951
+ lm.cue && /* @__PURE__ */ jsxs("div", {
952
+ className: "lm-title",
953
+ "data-top": lm.cue.top || void 0,
954
+ "aria-hidden": "true",
955
+ ref: titleRef,
956
+ children: [/* @__PURE__ */ jsx("b", { children: lm.cue.title }), lm.cue.detail && /* @__PURE__ */ jsx("span", { children: lm.cue.detail })]
957
+ })
958
+ ]
959
+ }),
960
+ frame && tip && !lm.storyPlaying && /* @__PURE__ */ jsx(Detail, {
961
+ lm,
962
+ scene: frame,
963
+ id: tip.id,
964
+ board: boardRef.current,
965
+ detailId
966
+ })
967
+ ]
968
+ });
969
+ }
970
+ /** The keyboard is in a field that takes letters: the first target of the key, inside a web component too. */
971
+ function typing(t) {
972
+ if (!(t instanceof HTMLElement)) return false;
973
+ if (t.isContentEditable || t instanceof HTMLTextAreaElement || t instanceof HTMLSelectElement) return true;
974
+ return t instanceof HTMLInputElement && ![
975
+ "range",
976
+ "checkbox",
977
+ "radio",
978
+ "button",
979
+ "submit",
980
+ "reset",
981
+ "image",
982
+ "file",
983
+ "color"
984
+ ].includes(t.type);
985
+ }
986
+ function Legend({ lm }) {
987
+ const flows = lm.view.def.flows;
988
+ const grey = Object.values(lm.ev.overload).some((o) => o.merge) || Object.values(lm.ev.stages).some((s) => s.kind === "fanout");
989
+ return /* @__PURE__ */ jsxs("div", {
990
+ className: "lm-legend",
991
+ children: [
992
+ Object.entries(flows).map(([f, v]) => /* @__PURE__ */ jsxs("span", { children: [/* @__PURE__ */ jsx("i", { style: { background: tokenColor(v.color) } }), v.label ?? f] }, f)),
993
+ /* @__PURE__ */ jsxs("span", { children: [/* @__PURE__ */ jsx("i", { style: { background: "var(--lm-ok)" } }), "done"] }),
994
+ /* @__PURE__ */ jsxs("span", { children: [/* @__PURE__ */ jsx("i", { style: { background: "var(--lm-drop)" } }), "dropped or rejected"] }),
995
+ grey && /* @__PURE__ */ jsxs("span", { children: [/* @__PURE__ */ jsx("i", { style: { background: "var(--lm-muted)" } }), "superseded or unread"] }),
996
+ /* @__PURE__ */ jsx("span", { children: lm.reducedMotion ? "line width: rate" : `one dot ≈ ${lm.engine.sim.dotScale.toLocaleString("en-US")} a second · ${lm.engine.sim.speed}× speed` })
997
+ ]
998
+ });
999
+ }
1000
+ const componentOf = (lm, n) => boxComponent(lm.ev, n);
1001
+ /** The SVG. It does not read the detail's state, so a hover re-renders the detail, not every box and edge. */
1002
+ const Structure = memo(function Structure({ lm, scene, svgRef, rates, setTip, onClick, selected }) {
1003
+ const marker = useId().replace(/:/g, "");
1004
+ const { labels, ev } = lm;
1005
+ const stateOf = (n) => {
1006
+ const c = componentOf(lm, n);
1007
+ return c ? ev.components[c]?.state ?? null : null;
1008
+ };
1009
+ const handlers = (n) => {
1010
+ const cid = componentOf(lm, n);
1011
+ const c = cid ? ev.components[cid] : void 0;
1012
+ const title = labels.nodes[n.id]?.title;
1013
+ if (!c) {
1014
+ if (!onClick) return {};
1015
+ return {
1016
+ tabIndex: 0,
1017
+ role: "button",
1018
+ className: "lm-node",
1019
+ "aria-label": title ?? n.id,
1020
+ "aria-pressed": selected === n.id,
1021
+ onClick: () => onClick(n.id),
1022
+ onKeyDown: (e) => {
1023
+ if (e.key === "Enter" || e.key === " ") {
1024
+ e.preventDefault();
1025
+ onClick(n.id);
1026
+ }
1027
+ }
1028
+ };
1029
+ }
1030
+ const press = () => {
1031
+ setTip((t) => t?.pinned && t.id === n.id ? null : {
1032
+ id: n.id,
1033
+ pinned: true
1034
+ });
1035
+ onClick?.(n.id);
1036
+ };
1037
+ return {
1038
+ tabIndex: 0,
1039
+ role: "button",
1040
+ className: "lm-node",
1041
+ "aria-label": `${title && title !== c.name ? `${title}, ` : ""}${c.name}: ${c.util == null ? "switched off" : pct(c.util)}`,
1042
+ ...onClick ? { "aria-pressed": selected === n.id } : {},
1043
+ onPointerEnter: (e) => e.pointerType === "mouse" && setTip((t) => t?.pinned ? t : {
1044
+ id: n.id,
1045
+ pinned: false
1046
+ }),
1047
+ onPointerLeave: (e) => e.pointerType === "mouse" && setTip((t) => t?.pinned ? t : null),
1048
+ onFocus: () => setTip((t) => t?.pinned ? t : {
1049
+ id: n.id,
1050
+ pinned: false
1051
+ }),
1052
+ onBlur: () => setTip((t) => t?.pinned ? t : null),
1053
+ onClick: press,
1054
+ onKeyDown: (e) => {
1055
+ if (e.key === "Escape") setTip(null);
1056
+ if (e.key === "Enter" || e.key === " ") {
1057
+ e.preventDefault();
1058
+ press();
1059
+ }
1060
+ }
1061
+ };
1062
+ };
1063
+ const summary = scene.nodes.map((n) => labels.nodes[n.id]?.title).join(", ");
1064
+ const first = ev.firstLimit;
1065
+ return /* @__PURE__ */ jsxs("svg", {
1066
+ ref: svgRef,
1067
+ viewBox: `0 0 ${scene.width} ${scene.height}`,
1068
+ role: "group",
1069
+ "aria-label": `Diagram: ${summary}`,
1070
+ children: [
1071
+ /* @__PURE__ */ jsx("defs", { children: /* @__PURE__ */ jsx("marker", {
1072
+ id: marker,
1073
+ viewBox: "0 0 10 10",
1074
+ refX: "9",
1075
+ refY: "5",
1076
+ markerWidth: "7",
1077
+ markerHeight: "7",
1078
+ orient: "auto-start-reverse",
1079
+ children: /* @__PURE__ */ jsx("path", {
1080
+ d: "M0 0 L10 5 L0 10 z",
1081
+ fill: "var(--lm-muted)"
1082
+ })
1083
+ }) }),
1084
+ rates && /* @__PURE__ */ jsx(RateStrokes, {
1085
+ lm,
1086
+ scene
1087
+ }),
1088
+ scene.edges.map((e) => /* @__PURE__ */ jsx(Edge, {
1089
+ e,
1090
+ text: labels.edges[e.id],
1091
+ marker
1092
+ }, e.id)),
1093
+ scene.nodes.map((n) => /* @__PURE__ */ jsx(Node, {
1094
+ n,
1095
+ state: stateOf(n),
1096
+ title: labels.nodes[n.id]?.title,
1097
+ sub: labels.nodes[n.id]?.sub,
1098
+ lm,
1099
+ focused: !!lm.focus && componentOf(lm, n) === lm.focus,
1100
+ selected: selected === n.id,
1101
+ handlers: handlers(n)
1102
+ }, n.id)),
1103
+ first && scene.nodes.filter((n) => componentOf(lm, n) === first.id).map((n) => /* @__PURE__ */ jsx(Halo, { n }, n.id))
1104
+ ]
1105
+ });
1106
+ });
1107
+ const pathOf = (pts) => pts.map(([x, y], i) => `${i ? "L" : "M"}${x} ${y}`).join(" ");
1108
+ function Edge({ e, text, marker }) {
1109
+ const drawing = e.draw != null && e.draw < 1;
1110
+ return /* @__PURE__ */ jsxs("g", {
1111
+ opacity: e.fade,
1112
+ children: [/* @__PURE__ */ jsx("path", {
1113
+ d: pathOf(e.points),
1114
+ fill: "none",
1115
+ stroke: "var(--lm-muted)",
1116
+ strokeOpacity: ".7",
1117
+ markerEnd: drawing ? void 0 : `url(#${marker})`,
1118
+ ...drawing ? {
1119
+ pathLength: 1,
1120
+ strokeDasharray: 1,
1121
+ strokeDashoffset: 1 - e.draw
1122
+ } : {}
1123
+ }), e.label && text && /* @__PURE__ */ jsx("text", {
1124
+ x: e.label.x + e.label.w / 2,
1125
+ y: e.label.y + e.label.h / 2 + 4,
1126
+ textAnchor: "middle",
1127
+ fontSize: "11",
1128
+ fill: "var(--lm-muted)",
1129
+ children: text
1130
+ })]
1131
+ });
1132
+ }
1133
+ /** With reduced motion, each flow is a static stroke along its edges, its width scaled by its rate. */
1134
+ function RateStrokes({ lm, scene }) {
1135
+ const { ev } = lm;
1136
+ const flows = lm.view.def.flows;
1137
+ const max = Math.max(1e-9, ...Object.values(ev.flows));
1138
+ const out = [];
1139
+ for (const f of Object.keys(flows)) {
1140
+ const seq = [scene.flowFrom[f], ...(ev.routes[f] ?? []).map((s) => scene.stageNode[s])].filter((n, i, a) => n && n !== a[i - 1]);
1141
+ const rate = ev.flows[f] ?? 0;
1142
+ const legs = seq.slice(1).map((to, i) => [
1143
+ seq[i],
1144
+ to,
1145
+ rate
1146
+ ]);
1147
+ const last = (ev.routes[f] ?? []).at(-1);
1148
+ const st = last ? ev.stages[last] : void 0;
1149
+ if (st?.kind === "fanout") for (const b of st.to[f] ?? []) legs.push([
1150
+ scene.stageNode[last],
1151
+ scene.stageNode[b.stage],
1152
+ rate * b.share
1153
+ ]);
1154
+ for (const [from, to, r] of legs) {
1155
+ const e = scene.edges.find((x) => x.from === from && x.to === to);
1156
+ if (e) out.push(/* @__PURE__ */ jsx("path", {
1157
+ d: pathOf(e.points),
1158
+ fill: "none",
1159
+ stroke: tokenColor(flows[f].color),
1160
+ strokeOpacity: ".45",
1161
+ strokeWidth: 1.5 + 6 * Math.min(r, max) / max
1162
+ }, `${f}:${e.id}`));
1163
+ }
1164
+ }
1165
+ return /* @__PURE__ */ jsx("g", { children: out });
1166
+ }
1167
+ function Txt({ s, children, anchor = "middle", fill = "currentColor", opacity }) {
1168
+ return /* @__PURE__ */ jsx("text", {
1169
+ x: s.x,
1170
+ y: s.y,
1171
+ fontSize: s.size,
1172
+ fontWeight: s.weight,
1173
+ textAnchor: anchor,
1174
+ fill,
1175
+ opacity,
1176
+ children
1177
+ });
1178
+ }
1179
+ function Node({ n, state, title, sub, lm, focused, selected, handlers }) {
1180
+ const stroke = state ? STATE_STROKE[state] : "var(--lm-line)";
1181
+ const flows = lm.view.def.flows;
1182
+ const st = n.kind === "pool" ? lm.ev.stages[n.stages[0] ?? ""] : void 0;
1183
+ const running = st?.kind === "workers" ? st.running : n.members.length;
1184
+ const idle = (i) => i >= running && i < (st?.kind === "workers" ? st.pods : n.members.length);
1185
+ const e = 6;
1186
+ const grow = n.fade == null ? void 0 : `translate(${n.x + n.w / 2} ${n.y + n.h / 2}) scale(${.92 + .08 * n.fade}) translate(${-n.x - n.w / 2} ${-n.y - n.h / 2})`;
1187
+ return /* @__PURE__ */ jsxs("g", {
1188
+ style: { color: "var(--lm-fg)" },
1189
+ opacity: n.fade,
1190
+ transform: grow,
1191
+ "data-node": n.id,
1192
+ "data-focus": focused || void 0,
1193
+ "data-selected": selected || void 0,
1194
+ ...handlers,
1195
+ children: [
1196
+ n.shape === "cylinder" ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("path", {
1197
+ d: `M${n.x} ${n.y + e} A${n.w / 2} ${e} 0 0 1 ${n.x + n.w} ${n.y + e} V${n.y + n.h - e} A${n.w / 2} ${e} 0 0 1 ${n.x} ${n.y + n.h - e} Z`,
1198
+ fill: "var(--lm-surface)",
1199
+ stroke,
1200
+ strokeWidth: "1.5"
1201
+ }), /* @__PURE__ */ jsx("path", {
1202
+ d: `M${n.x} ${n.y + e} A${n.w / 2} ${e} 0 0 0 ${n.x + n.w} ${n.y + e}`,
1203
+ fill: "none",
1204
+ stroke,
1205
+ strokeWidth: "1.5"
1206
+ })] }) : /* @__PURE__ */ jsx("rect", {
1207
+ x: n.x,
1208
+ y: n.y,
1209
+ width: n.w,
1210
+ height: n.h,
1211
+ rx: "6",
1212
+ fill: "var(--lm-surface)",
1213
+ stroke,
1214
+ strokeWidth: "1.5"
1215
+ }),
1216
+ /* @__PURE__ */ jsx(Txt, {
1217
+ s: n.title,
1218
+ children: title
1219
+ }),
1220
+ n.sub && sub && /* @__PURE__ */ jsx(Txt, {
1221
+ s: n.sub,
1222
+ fill: "var(--lm-muted)",
1223
+ children: sub
1224
+ }),
1225
+ n.members.map((m, i) => /* @__PURE__ */ jsxs("g", {
1226
+ "data-idle": idle(i) || void 0,
1227
+ opacity: idle(i) ? .45 * (m.fade ?? 1) : m.fade,
1228
+ children: [/* @__PURE__ */ jsx("rect", {
1229
+ x: m.x,
1230
+ y: m.y,
1231
+ width: m.w,
1232
+ height: m.h,
1233
+ rx: "4",
1234
+ fill: "none",
1235
+ stroke: "var(--lm-line)",
1236
+ strokeDasharray: idle(i) ? "3 3" : void 0
1237
+ }), /* @__PURE__ */ jsx(Txt, {
1238
+ s: m.spot,
1239
+ anchor: "start",
1240
+ fill: "var(--lm-muted)",
1241
+ children: m.label
1242
+ })]
1243
+ }, m.label)),
1244
+ n.groups.map((g, i) => /* @__PURE__ */ jsx(Txt, {
1245
+ s: g.spot,
1246
+ anchor: "start",
1247
+ fill: tokenColor(flows[g.flow]?.color ?? "muted"),
1248
+ opacity: g.fade,
1249
+ children: g.text
1250
+ }, `${g.flow}#${i}`)),
1251
+ n.cells.map((c) => /* @__PURE__ */ jsx("rect", {
1252
+ x: c.x,
1253
+ y: c.y,
1254
+ width: c.w,
1255
+ height: c.h,
1256
+ rx: "1.5",
1257
+ opacity: c.fade,
1258
+ fill: "var(--lm-lane)",
1259
+ stroke: tokenColor(flows[c.flow]?.color ?? "muted"),
1260
+ strokeOpacity: ".6"
1261
+ }, `${c.stage}/${c.flow}/${c.index}`)),
1262
+ n.slots.map((s) => /* @__PURE__ */ jsxs("g", {
1263
+ opacity: s.fade,
1264
+ children: [/* @__PURE__ */ jsx("rect", {
1265
+ x: s.x,
1266
+ y: s.y,
1267
+ width: s.w,
1268
+ height: s.h,
1269
+ rx: "2",
1270
+ fill: "var(--lm-surface)",
1271
+ stroke: "currentColor",
1272
+ strokeOpacity: ".45"
1273
+ }), /* @__PURE__ */ jsx("rect", {
1274
+ "data-slot": s.index,
1275
+ "data-stage": n.stages[0],
1276
+ "data-y": s.y,
1277
+ "data-s": s.w,
1278
+ x: s.x + 1,
1279
+ y: s.y + s.h - 1,
1280
+ width: s.w - 2,
1281
+ height: 0,
1282
+ rx: "1",
1283
+ fill: "var(--lm-accent)"
1284
+ })]
1285
+ }, s.index)),
1286
+ selected && /* @__PURE__ */ jsx("rect", {
1287
+ className: "lm-selected",
1288
+ x: n.x - 3,
1289
+ y: n.y - 3,
1290
+ width: n.w + 6,
1291
+ height: n.h + 6,
1292
+ rx: "8",
1293
+ fill: "none",
1294
+ stroke: "var(--lm-accent)",
1295
+ strokeWidth: "2.5"
1296
+ }),
1297
+ focused && /* @__PURE__ */ jsx("rect", {
1298
+ className: "lm-focus",
1299
+ x: n.x - 5,
1300
+ y: n.y - 5,
1301
+ width: n.w + 10,
1302
+ height: n.h + 10,
1303
+ rx: "9",
1304
+ fill: "none",
1305
+ stroke: "var(--lm-accent)",
1306
+ strokeWidth: "2",
1307
+ strokeDasharray: "5 4"
1308
+ })
1309
+ ]
1310
+ });
1311
+ }
1312
+ /** The width of the first limit's tag, in scene units. */
1313
+ const TAG_W = 72;
1314
+ /**
1315
+ * A ring around the first limit's box with a soft glow and a "first limit" tag on its top edge. The engine scales it
1316
+ * and its glow on its own clock; it is a layer of its own, so it moves nothing else. It fades with its box.
1317
+ */
1318
+ function Halo({ n }) {
1319
+ const d = 7;
1320
+ const box = {
1321
+ x: n.x - d,
1322
+ y: n.y - d,
1323
+ width: n.w + 14,
1324
+ height: n.h + 14,
1325
+ rx: 10
1326
+ };
1327
+ const tx = n.x + n.w + d - TAG_W - 8;
1328
+ return /* @__PURE__ */ jsxs("g", {
1329
+ className: "lm-halo",
1330
+ "data-halo": "",
1331
+ "data-cx": n.x + n.w / 2,
1332
+ "data-cy": n.y + n.h / 2,
1333
+ opacity: n.fade,
1334
+ pointerEvents: "none",
1335
+ children: [
1336
+ /* @__PURE__ */ jsx("rect", {
1337
+ ...box,
1338
+ "data-glow": "",
1339
+ fill: "none",
1340
+ stroke: "var(--lm-drop)",
1341
+ strokeWidth: "10",
1342
+ strokeOpacity: ".22"
1343
+ }),
1344
+ /* @__PURE__ */ jsx("rect", {
1345
+ ...box,
1346
+ fill: "none",
1347
+ stroke: "var(--lm-drop)",
1348
+ strokeWidth: "2.5"
1349
+ }),
1350
+ /* @__PURE__ */ jsx("rect", {
1351
+ x: tx,
1352
+ y: box.y - 7.5,
1353
+ width: TAG_W,
1354
+ height: "15",
1355
+ rx: "3",
1356
+ fill: "var(--lm-drop)"
1357
+ }),
1358
+ /* @__PURE__ */ jsx("text", {
1359
+ x: tx + TAG_W / 2,
1360
+ y: box.y + 3.5,
1361
+ textAnchor: "middle",
1362
+ fontSize: "9.5",
1363
+ fontWeight: "600",
1364
+ letterSpacing: ".06em",
1365
+ fill: "var(--lm-surface)",
1366
+ children: "FIRST LIMIT"
1367
+ })
1368
+ ]
1369
+ });
1370
+ }
1371
+ /**
1372
+ * A box's component in words, over the board: utilization, demand against capacity and where it came from, where it
1373
+ * reaches the target and 100 % (with dates, given growth), and its target in each scenario. HTML, so exports leave it out.
1374
+ */
1375
+ function Detail({ lm, scene, id, board, detailId }) {
1376
+ const { model, ev } = lm;
1377
+ const n = scene.nodes.find((x) => x.id === id);
1378
+ const cid = n && componentOf(lm, n);
1379
+ const comparison = useComparison(lm);
1380
+ const rows = model.scenarios.length > 1 ? comparison.rows : [];
1381
+ useEffect(() => {
1382
+ const el = board?.querySelector(`[data-node="${CSS.escape(id)}"]`);
1383
+ el?.setAttribute("aria-describedby", detailId);
1384
+ return () => el?.removeAttribute("aria-describedby");
1385
+ }, [
1386
+ board,
1387
+ id,
1388
+ detailId
1389
+ ]);
1390
+ const c = cid ? ev.components[cid] : void 0;
1391
+ const tip = useRef(null);
1392
+ const box = n && `${n.x} ${n.y} ${n.w} ${n.h}`;
1393
+ useLayoutEffect(() => {
1394
+ const el = tip.current;
1395
+ const wrap = el?.offsetParent;
1396
+ if (!el || !n || !board || !(wrap instanceof HTMLElement)) return;
1397
+ const place = () => {
1398
+ const k = board.clientWidth / scene.width;
1399
+ const w = wrap.getBoundingClientRect();
1400
+ const y = (v) => v - w.top - wrap.clientTop + wrap.scrollTop;
1401
+ let lo = 0;
1402
+ let hi = innerHeight;
1403
+ for (let a = wrap; a; a = a.parentElement) {
1404
+ if (getComputedStyle(a).overflowY === "visible") continue;
1405
+ const r = a.getBoundingClientRect();
1406
+ lo = Math.max(lo, r.top);
1407
+ hi = Math.min(hi, r.bottom);
1408
+ }
1409
+ const [top, bottom] = [y(lo) + 4, y(hi) - 4];
1410
+ const h = el.offsetHeight;
1411
+ const boxTop = board.offsetTop + n.y * k;
1412
+ const boxBottom = board.offsetTop + (n.y + n.h) * k;
1413
+ const below = boxBottom + 6;
1414
+ const above = boxTop - 6 - h;
1415
+ const fits = (n.y + n.h / 2 < scene.height / 2 ? [below, above] : [above, below]).find((t) => t >= top && t + h <= bottom);
1416
+ const roomier = bottom - boxBottom >= boxTop - top ? below : above;
1417
+ el.style.top = `${Math.max(top, Math.min(fits ?? roomier, bottom - h))}px`;
1418
+ el.style.left = `${Math.max(0, Math.min(board.offsetLeft + n.x * k, wrap.clientWidth - el.offsetWidth))}px`;
1419
+ };
1420
+ place();
1421
+ const ro = new ResizeObserver(place);
1422
+ ro.observe(el);
1423
+ ro.observe(board);
1424
+ document.addEventListener("scroll", place, {
1425
+ capture: true,
1426
+ passive: true
1427
+ });
1428
+ addEventListener("resize", place);
1429
+ return () => {
1430
+ ro.disconnect();
1431
+ document.removeEventListener("scroll", place, { capture: true });
1432
+ removeEventListener("resize", place);
1433
+ };
1434
+ }, [
1435
+ box,
1436
+ board,
1437
+ scene
1438
+ ]);
1439
+ if (!n || !c || !board) return null;
1440
+ const at = (r, x) => r ? reach(r, model.searchMax, model.dateAt) : multiple(x, model.searchMax);
1441
+ const num = (x) => Math.abs(x) >= 1e3 ? compact(x) : fmt(x);
1442
+ const cap = c.capacity;
1443
+ return /* @__PURE__ */ jsxs("div", {
1444
+ id: detailId,
1445
+ className: "lm-tip lm-detail",
1446
+ role: "tooltip",
1447
+ ref: tip,
1448
+ children: [
1449
+ /* @__PURE__ */ jsxs("b", { children: [c.name, c === ev.firstLimit && /* @__PURE__ */ jsx("span", {
1450
+ className: "lm-tag",
1451
+ "data-kind": "first",
1452
+ children: "first limit"
1453
+ })] }),
1454
+ c.util == null || !cap ? /* @__PURE__ */ jsx("span", { children: "switched off" }) : /* @__PURE__ */ jsxs(Fragment, { children: [
1455
+ /* @__PURE__ */ jsxs("span", { children: [
1456
+ /* @__PURE__ */ jsx("strong", { children: pct(c.util) }),
1457
+ " · ",
1458
+ num(c.demand ?? 0),
1459
+ " of ",
1460
+ fmt(cap.value),
1461
+ " ",
1462
+ cap.unit,
1463
+ cap.within ? ` ±${pct(cap.within)}` : ""
1464
+ ] }),
1465
+ /* @__PURE__ */ jsxs("span", {
1466
+ className: "lm-sub",
1467
+ children: [
1468
+ "capacity",
1469
+ " ",
1470
+ /* @__PURE__ */ jsx("span", {
1471
+ className: "lm-prov",
1472
+ "data-kind": cap.provenance,
1473
+ children: cap.provenance
1474
+ }),
1475
+ cap.source ? `, ${cap.source}` : ""
1476
+ ]
1477
+ }),
1478
+ /* @__PURE__ */ jsxs("span", { children: [
1479
+ pct(model.thresholds.target),
1480
+ " at ",
1481
+ at(c.targetRange, c.target)
1482
+ ] }),
1483
+ /* @__PURE__ */ jsxs("span", { children: [
1484
+ pct(model.thresholds.full),
1485
+ " at ",
1486
+ at(c.fullRange, c.full)
1487
+ ] }),
1488
+ blocks(lm, n).map((line) => /* @__PURE__ */ jsx("span", { children: line }, line)),
1489
+ c.over && /* @__PURE__ */ jsxs("span", {
1490
+ className: "lm-sub",
1491
+ children: [
1492
+ "Past ",
1493
+ pct(model.thresholds.full),
1494
+ ": ",
1495
+ c.over,
1496
+ "."
1497
+ ]
1498
+ })
1499
+ ] }),
1500
+ rows.length > 0 && /* @__PURE__ */ jsxs("span", {
1501
+ className: "lm-sub",
1502
+ children: [
1503
+ pct(model.thresholds.target),
1504
+ " by scenario:",
1505
+ " ",
1506
+ rows.map((r, i) => {
1507
+ const x = r.components.find((y) => y.id === cid);
1508
+ return /* @__PURE__ */ jsxs("span", {
1509
+ className: "lm-nowrap",
1510
+ children: [
1511
+ i > 0 && " · ",
1512
+ /* @__PURE__ */ jsx("b", {
1513
+ className: "lm-key",
1514
+ style: { background: scenarioColor(model, r.label) }
1515
+ }),
1516
+ r.label,
1517
+ " ",
1518
+ x?.targetRange == null ? "off" : multiples(x.targetRange, model.searchMax, true)
1519
+ ]
1520
+ }, r.label);
1521
+ })
1522
+ ]
1523
+ })
1524
+ ]
1525
+ });
1526
+ }
1527
+ /** What a box's building blocks do at these values: pods running, cache answers, what a stage turns away. */
1528
+ function blocks(lm, n) {
1529
+ const out = [];
1530
+ for (const id of n.stages) {
1531
+ const s = lm.ev.stages[id];
1532
+ if (s?.kind === "workers" && s.autoscale) out.push(`${s.running} of ${s.pods} pods running, each held near ${pct(s.autoscale.target)}`);
1533
+ if (s?.kind === "cache") out.push(`${pct(s.hit)} answered here`);
1534
+ if ((s?.kind === "pass" || s?.kind === "limit" || s?.kind === "cache") && s.shed > 0) out.push(`${pct(s.shed)} of what reaches it turned away`);
1535
+ }
1536
+ return out;
1537
+ }
1538
+ // src/elk.ts
1539
+ let shared = null;
1540
+ /**
1541
+ * One ELK worker for every loadmap on the page, started on the first layout. When the worker cannot start or load
1542
+ * (no Worker, a CSP without worker-src, a dev server that pre-bundled this package away from the worker file), every
1543
+ * layout runs on the main thread instead: slower to start, the same result.
1544
+ */
1545
+ function pageElk() {
1546
+ shared ??= workerElk(() => new Worker(new URL("./elk.worker.js", import.meta.url), {
1547
+ type: "module",
1548
+ name: "loadmap-elk"
1549
+ }));
1550
+ return shared;
1551
+ }
1552
+ /**
1553
+ * ELK in the worker `make` starts, falling back to the main thread: `<Loadmap elk={workerElk(…)}>` for a page whose
1554
+ * bundler inlines the worker (`@loadmap/react/elk.worker.js`), or that serves it from another place. Make it once,
1555
+ * outside a component: each engine starts its own worker.
1556
+ */
1557
+ function workerElk(make) {
1558
+ let worker = null;
1559
+ let broken = typeof Worker === "undefined";
1560
+ let told = false;
1561
+ let next = 0;
1562
+ const pending = /* @__PURE__ */ new Map();
1563
+ const tell = (why) => {
1564
+ if (told || typeof Worker === "undefined") return;
1565
+ told = true;
1566
+ console.info(`loadmap: the layout runs on the main thread, slower to start: the ELK worker did not start (${why}). A page can hand one in, <Loadmap elk={workerElk(() => new Worker(…))}>; a Content-Security-Policy must allow it (worker-src).`);
1567
+ };
1568
+ const fallBack = (why) => {
1569
+ tell(why);
1570
+ broken = true;
1571
+ worker?.terminate();
1572
+ worker = null;
1573
+ for (const [id, p] of pending) {
1574
+ pending.delete(id);
1575
+ localElk().then((elk) => elk.layout(p.graph)).then(p.resolve, p.reject);
1576
+ }
1577
+ };
1578
+ const start = () => {
1579
+ if (worker || broken) return worker;
1580
+ try {
1581
+ worker = make();
1582
+ } catch (err) {
1583
+ fallBack(err instanceof Error ? err.message : String(err));
1584
+ return null;
1585
+ }
1586
+ worker.onmessage = ({ data }) => {
1587
+ const p = pending.get(data.id);
1588
+ if (!p) return;
1589
+ pending.delete(data.id);
1590
+ if (data.error != null) p.reject(new Error(data.error));
1591
+ else p.resolve(data.graph);
1592
+ };
1593
+ worker.onerror = (e) => {
1594
+ e.preventDefault();
1595
+ fallBack(e.message || "it failed to load or to run");
1596
+ };
1597
+ return worker;
1598
+ };
1599
+ return { layout(graph) {
1600
+ const w = start();
1601
+ if (!w) {
1602
+ tell("no Worker here");
1603
+ return localElk().then((elk) => elk.layout(graph));
1604
+ }
1605
+ return new Promise((resolve, reject) => {
1606
+ const id = next++;
1607
+ pending.set(id, {
1608
+ graph,
1609
+ resolve,
1610
+ reject
1611
+ });
1612
+ w.postMessage({
1613
+ id,
1614
+ graph
1615
+ });
1616
+ });
1617
+ } };
1618
+ }
1619
+ // src/panels.tsx
1620
+ /** The model's one-sentence answer for the current values, and which capacity to measure when it is unsure. */
1621
+ function Verdict({ lm }) {
1622
+ const { measure } = lm.ev;
1623
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("p", {
1624
+ className: "lm-verdict",
1625
+ "data-tier": lm.ev.verdict.tier,
1626
+ "aria-live": "polite",
1627
+ children: lm.ev.verdict.text
1628
+ }), measure && /* @__PURE__ */ jsx("p", {
1629
+ className: "lm-measure",
1630
+ "data-component": measure.component,
1631
+ children: measure.text
1632
+ })] });
1633
+ }
1634
+ /** "±30 %" for a capacity with a range. */
1635
+ const plusMinus = (c) => c?.within ? `±${pct(c.within)}` : "";
1636
+ /** Each component's utilization in the order they reach the target, with where they cross it and 100 %. */
1637
+ function Limits({ lm, title = "Where it runs out, in order" }) {
1638
+ const { ev, model } = lm;
1639
+ const top = Math.max(1.5, model.thresholds.full * 1.5);
1640
+ const at = (u) => `${u / top * 100}%`;
1641
+ const span = (r, x) => r ? multiples(r, model.searchMax, true) : multiple(x, model.searchMax);
1642
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1643
+ /* @__PURE__ */ jsx("h3", { children: title }),
1644
+ /* @__PURE__ */ jsxs("div", {
1645
+ className: "lm-scale",
1646
+ "aria-hidden": "true",
1647
+ children: [
1648
+ /* @__PURE__ */ jsx("span", {}),
1649
+ /* @__PURE__ */ jsxs("div", { children: [
1650
+ /* @__PURE__ */ jsx("span", {
1651
+ style: {
1652
+ left: 0,
1653
+ transform: "none"
1654
+ },
1655
+ children: "0"
1656
+ }),
1657
+ /* @__PURE__ */ jsxs("span", {
1658
+ style: { left: at(model.thresholds.target) },
1659
+ children: [pct(model.thresholds.target), " target"]
1660
+ }),
1661
+ /* @__PURE__ */ jsx("span", {
1662
+ style: { left: at(model.thresholds.full) },
1663
+ children: pct(model.thresholds.full)
1664
+ }),
1665
+ /* @__PURE__ */ jsx("span", {
1666
+ style: {
1667
+ left: "100%",
1668
+ transform: "translateX(-100%)"
1669
+ },
1670
+ children: pct(top)
1671
+ })
1672
+ ] }),
1673
+ /* @__PURE__ */ jsx("span", {})
1674
+ ]
1675
+ }),
1676
+ /* @__PURE__ */ jsx("div", {
1677
+ className: "lm-limits",
1678
+ children: ev.ranked.map((c) => /* @__PURE__ */ jsxs("div", {
1679
+ className: "lm-lim",
1680
+ "data-component": c.id,
1681
+ children: [
1682
+ /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsxs("b", { children: [
1683
+ c.name,
1684
+ c === ev.firstLimit && /* @__PURE__ */ jsx("span", {
1685
+ className: "lm-tag",
1686
+ "data-kind": "first",
1687
+ children: "first limit"
1688
+ }),
1689
+ c.capacity?.provenance === "estimated" ? /* @__PURE__ */ jsxs("span", {
1690
+ className: "lm-tag",
1691
+ "data-kind": "estimated",
1692
+ children: ["estimate", c.capacity.within ? ` ${plusMinus(c.capacity)}` : ""]
1693
+ }) : !!c.capacity?.within && /* @__PURE__ */ jsx("span", {
1694
+ className: "lm-tag",
1695
+ "data-kind": "range",
1696
+ children: plusMinus(c.capacity)
1697
+ })
1698
+ ] }), /* @__PURE__ */ jsx("span", {
1699
+ className: "lm-sub",
1700
+ children: c.describe ?? (c.capacity ? `${fmt(c.capacity.value)} ${c.capacity.unit}` : "switched off")
1701
+ })] }),
1702
+ /* @__PURE__ */ jsxs("div", {
1703
+ className: "lm-track",
1704
+ role: "img",
1705
+ "aria-label": `${c.name} at ${c.util == null ? "off" : pct(c.util)}`,
1706
+ children: [
1707
+ /* @__PURE__ */ jsx("div", {
1708
+ className: "lm-fill",
1709
+ "data-state": c.state,
1710
+ style: { width: `${Math.min(100, (c.util ?? 0) / top * 100)}%` }
1711
+ }),
1712
+ /* @__PURE__ */ jsx("div", {
1713
+ className: "lm-tick",
1714
+ style: { left: at(model.thresholds.target) }
1715
+ }),
1716
+ /* @__PURE__ */ jsx("div", {
1717
+ className: "lm-tick",
1718
+ style: { left: at(model.thresholds.full) }
1719
+ })
1720
+ ]
1721
+ }),
1722
+ /* @__PURE__ */ jsxs("div", {
1723
+ className: "lm-val",
1724
+ children: [c.util == null ? "—" : `${pct(c.util)} · ${num(c.demand ?? 0)} ${c.capacity?.unit ?? ""}`, /* @__PURE__ */ jsx("small", { children: c.util == null ? "switched off" : `${pct(model.thresholds.target)} at ${span(c.targetRange, c.target)} · full at ${span(c.fullRange, c.full)}` })]
1725
+ })
1726
+ ]
1727
+ }, c.id))
1728
+ })
1729
+ ] });
1730
+ }
1731
+ /**
1732
+ * Live numbers: from the sim, lag and drops per queue, busy workers, rejected requests; from the model, pods running,
1733
+ * cache answers and retries.
1734
+ */
1735
+ function Meters({ lm }) {
1736
+ const [, tick] = useState(0);
1737
+ useEffect(() => {
1738
+ const t = setInterval(() => tick((x) => x + 1), 250);
1739
+ return () => clearInterval(t);
1740
+ }, []);
1741
+ const { ev, engine, model } = lm;
1742
+ const sim = engine.sim;
1743
+ const flowLabel = (f) => model.def.flows[f]?.label ?? f;
1744
+ const items = [];
1745
+ for (const s of Object.values(ev.stages)) {
1746
+ if (s.kind === "queue") for (const f of model.flowIds.filter((x) => ev.routes[x]?.includes(s.id))) {
1747
+ const q = sim.queue(s.id, f);
1748
+ const rules = ev.overload[f] ?? {};
1749
+ items.push({
1750
+ key: `${s.id}/${f}/lag`,
1751
+ value: secs(q.lag),
1752
+ label: `${flowLabel(f)} lag in ${s.label}`,
1753
+ state: q.lag > 60 ? "over" : q.lag > 5 ? "warn" : "ok"
1754
+ });
1755
+ if (rules.merge) items.push({
1756
+ key: `${s.id}/${f}/merge`,
1757
+ value: compact(q.merged),
1758
+ label: `${flowLabel(f)} superseded /s (${rules.merge.reason ?? "newest kept"})`,
1759
+ state: q.merged > .5 ? "warn" : "ok"
1760
+ });
1761
+ if (rules.drop) items.push({
1762
+ key: `${s.id}/${f}/drop`,
1763
+ value: compact(q.dropped),
1764
+ label: `${flowLabel(f)} dropped /s (${rules.drop.reason ?? "too old"})`,
1765
+ state: q.dropped > .5 ? "over" : "ok"
1766
+ });
1767
+ }
1768
+ if (s.kind === "workers") {
1769
+ const b = sim.busy(s.id);
1770
+ items.push({
1771
+ key: `${s.id}/busy`,
1772
+ value: pct(b),
1773
+ label: `${s.label} busy`,
1774
+ state: b > .95 ? "over" : b > .5 ? "warn" : "ok"
1775
+ });
1776
+ if (s.autoscale) items.push({
1777
+ key: `${s.id}/pods`,
1778
+ value: `${s.running} of ${s.pods}`,
1779
+ label: `${s.label} pods running`,
1780
+ state: s.running < s.pods ? "ok" : (ev.components[s.component]?.util ?? 0) > model.thresholds.full ? "over" : "warn"
1781
+ });
1782
+ }
1783
+ if (s.kind === "cache") items.push({
1784
+ key: `${s.id}/hits`,
1785
+ value: compact(sim.arriving(s.id) * (1 - sim.shed(s.id)) * s.hit),
1786
+ label: `answered at ${s.label} /s (${pct(s.hit)} hits)`,
1787
+ state: "ok"
1788
+ });
1789
+ if ((s.kind === "pass" || s.kind === "limit" || s.kind === "cache") && sim.shed(s.id) > 0) items.push({
1790
+ key: `${s.id}/shed`,
1791
+ value: pct(sim.shed(s.id)),
1792
+ label: `rejected at ${s.label}`,
1793
+ state: "over"
1794
+ });
1795
+ }
1796
+ for (const f of model.flowIds) {
1797
+ const r = ev.retry[f];
1798
+ if (!r || !(r.rate > 0)) continue;
1799
+ const per = r.attempts / r.rate;
1800
+ items.push({
1801
+ key: `${f}/attempts`,
1802
+ value: `${fmt(per)}×`,
1803
+ label: `${flowLabel(f)} attempts per ${model.def.flows[f]?.unit ?? "unit"}`,
1804
+ state: per > 1.05 ? "warn" : "ok"
1805
+ });
1806
+ items.push({
1807
+ key: `${f}/failed`,
1808
+ value: pct(r.failed),
1809
+ label: `${flowLabel(f)} failing after ${r.times} ${r.times === 1 ? "retry" : "retries"}`,
1810
+ state: r.failed > .005 ? "over" : "ok"
1811
+ });
1812
+ }
1813
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("h3", { children: "Live" }), /* @__PURE__ */ jsx("div", {
1814
+ className: "lm-meters",
1815
+ children: items.map((m) => /* @__PURE__ */ jsxs("div", {
1816
+ className: "lm-meter",
1817
+ "data-state": m.state,
1818
+ children: [/* @__PURE__ */ jsx("b", { children: m.value }), /* @__PURE__ */ jsx("span", {
1819
+ title: m.label,
1820
+ children: m.label
1821
+ })]
1822
+ }, m.key))
1823
+ })] });
1824
+ }
1825
+ /** The load slider with its label and value. */
1826
+ function LoadRange({ lm }) {
1827
+ const load = lm.model.load;
1828
+ const x = lm.values.load;
1829
+ return /* @__PURE__ */ jsxs("label", {
1830
+ className: "lm-range",
1831
+ children: [/* @__PURE__ */ jsxs("span", { children: [
1832
+ load.label,
1833
+ " ",
1834
+ /* @__PURE__ */ jsxs("output", { children: [fmt(x), "×"] })
1835
+ ] }), /* @__PURE__ */ jsx("input", {
1836
+ type: "range",
1837
+ min: load.min,
1838
+ max: load.max,
1839
+ step: load.step,
1840
+ value: x,
1841
+ onChange: (e) => lm.setValues({ load: Number(e.target.value) })
1842
+ })]
1843
+ });
1844
+ }
1845
+ /** The load slider, the presets and every parameter, greyed out where it does not apply. */
1846
+ function Controls({ lm }) {
1847
+ const { model, values, setValues, ev } = lm;
1848
+ const v = values;
1849
+ return /* @__PURE__ */ jsxs("div", {
1850
+ className: "lm-card lm-controls",
1851
+ children: [
1852
+ /* @__PURE__ */ jsx("h3", { children: "Load" }),
1853
+ /* @__PURE__ */ jsx(LoadRange, { lm }),
1854
+ /* @__PURE__ */ jsx("div", {
1855
+ className: "lm-presets",
1856
+ children: ev.presets.map((p) => {
1857
+ const on = Object.entries(p.values).every(([k, x]) => v[k] === x);
1858
+ return /* @__PURE__ */ jsx("button", {
1859
+ type: "button",
1860
+ "aria-pressed": on,
1861
+ onClick: () => setValues(p.values),
1862
+ children: p.label
1863
+ }, p.label);
1864
+ })
1865
+ }),
1866
+ model.params.length > 1 && /* @__PURE__ */ jsx("h3", { children: "Design" }),
1867
+ model.params.map(({ id, def }) => {
1868
+ if (def.kind === "load") return null;
1869
+ const enabled = model.isEnabled(id, v);
1870
+ const tag = def.tag && /* @__PURE__ */ jsx("span", {
1871
+ className: "lm-tag",
1872
+ "data-kind": "estimated",
1873
+ children: def.tag
1874
+ });
1875
+ if (def.kind === "switch") return /* @__PURE__ */ jsxs("label", {
1876
+ className: `lm-switch${enabled ? "" : " lm-off"}`,
1877
+ children: [
1878
+ /* @__PURE__ */ jsx("input", {
1879
+ type: "checkbox",
1880
+ checked: Boolean(v[id]),
1881
+ disabled: !enabled,
1882
+ onChange: (e) => setValues({ [id]: e.target.checked })
1883
+ }),
1884
+ /* @__PURE__ */ jsxs("span", { children: [def.label, tag] }),
1885
+ def.hint && /* @__PURE__ */ jsx("small", { children: def.hint })
1886
+ ]
1887
+ }, id);
1888
+ if (def.kind === "select") return /* @__PURE__ */ jsxs("label", {
1889
+ className: `lm-select${enabled ? "" : " lm-off"}`,
1890
+ children: [
1891
+ /* @__PURE__ */ jsxs("span", { children: [def.label, tag] }),
1892
+ /* @__PURE__ */ jsx("select", {
1893
+ value: String(v[id]),
1894
+ disabled: !enabled,
1895
+ onChange: (e) => {
1896
+ const opt = def.options.find((o) => String(o) === e.target.value);
1897
+ setValues({ [id]: opt });
1898
+ },
1899
+ children: def.options.map((o) => /* @__PURE__ */ jsx("option", {
1900
+ value: String(o),
1901
+ children: def.format ? def.format(o) : String(o)
1902
+ }, String(o)))
1903
+ }),
1904
+ def.hint && /* @__PURE__ */ jsx("small", { children: def.hint })
1905
+ ]
1906
+ }, id);
1907
+ return /* @__PURE__ */ jsxs("label", {
1908
+ className: `lm-range${enabled ? "" : " lm-off"}`,
1909
+ children: [
1910
+ /* @__PURE__ */ jsxs("span", { children: [
1911
+ def.label,
1912
+ tag,
1913
+ " ",
1914
+ /* @__PURE__ */ jsx("output", { children: def.format ? def.format(v[id]) : fmt(v[id]) })
1915
+ ] }),
1916
+ /* @__PURE__ */ jsx("input", {
1917
+ type: "range",
1918
+ min: def.min,
1919
+ max: def.max,
1920
+ step: def.step,
1921
+ value: v[id],
1922
+ disabled: !enabled,
1923
+ onChange: (e) => setValues({ [id]: Number(e.target.value) })
1924
+ }),
1925
+ def.hint && /* @__PURE__ */ jsx("small", { children: def.hint })
1926
+ ]
1927
+ }, id);
1928
+ })
1929
+ ]
1930
+ });
1931
+ }
1932
+ /** What the model assumes: every capacity with its provenance, every fit, and anything the page adds. */
1933
+ function Assumptions({ lm, extra = [] }) {
1934
+ return /* @__PURE__ */ jsxs("div", {
1935
+ className: "lm-card",
1936
+ children: [/* @__PURE__ */ jsx("h3", { children: "What this assumes" }), /* @__PURE__ */ jsxs("ul", {
1937
+ className: "lm-facts",
1938
+ children: [extra.map((x, i) => /* @__PURE__ */ jsx("li", { children: x }, i)), lm.ev.assumptions.map((a) => /* @__PURE__ */ jsx("li", { children: describe(a) }, a.kind === "capacity" ? `c:${a.component}` : `f:${a.name}`))]
1939
+ })]
1940
+ });
1941
+ }
1942
+ function describe(a) {
1943
+ if (a.kind === "capacity") {
1944
+ const c = a.capacity;
1945
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1946
+ /* @__PURE__ */ jsxs("b", { children: [a.name, ":"] }),
1947
+ " ",
1948
+ fmt(c.value),
1949
+ " ",
1950
+ c.unit,
1951
+ c.within ? ` ${plusMinus(c)}` : "",
1952
+ ",",
1953
+ " ",
1954
+ /* @__PURE__ */ jsx("span", {
1955
+ className: "lm-prov",
1956
+ "data-kind": c.provenance,
1957
+ children: c.provenance
1958
+ }),
1959
+ c.source ? ` (${c.source})` : "",
1960
+ "."
1961
+ ] });
1962
+ }
1963
+ const f = a.fit;
1964
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1965
+ /* @__PURE__ */ jsxs("b", { children: [a.name, ":"] }),
1966
+ " ",
1967
+ f.y,
1968
+ " = ",
1969
+ sig(f.a),
1970
+ " + ",
1971
+ sig(f.b),
1972
+ " × ",
1973
+ f.x,
1974
+ ", r² ",
1975
+ f.r2.toFixed(3),
1976
+ " over ",
1977
+ f.n,
1978
+ " points,",
1979
+ " ",
1980
+ /* @__PURE__ */ jsx("span", {
1981
+ className: "lm-prov",
1982
+ "data-kind": "measured",
1983
+ children: "measured"
1984
+ }),
1985
+ f.source ? ` (${f.source})` : "",
1986
+ "."
1987
+ ] });
1988
+ }
1989
+ /** Exact below 1,000 (3.9 cores), compact above (12k req/s). */
1990
+ const num = (x) => Math.abs(x) >= 1e3 ? compact(x) : fmt(x);
1991
+ const sig = (x) => Number(x.toPrecision(3)).toString();
1992
+ // src/compact.tsx
1993
+ /** The names a reader sees for the panels, on the tabs and the buttons that open them. */
1994
+ const NAMES = {
1995
+ verdict: "Verdict",
1996
+ live: "Live",
1997
+ limits: "Limits",
1998
+ controls: "Load",
1999
+ headroom: "Headroom",
2000
+ compare: "Compare",
2001
+ assumptions: "Assumptions"
2002
+ };
2003
+ /**
2004
+ * The verdict in one line, from the same evaluation as the sentence: the load, how far the target holds, the first
2005
+ * limit and how sure its capacity is, what is past capacity. The sentence is its tooltip and opens under "Why".
2006
+ */
2007
+ function VerdictLine({ lm, verdict = true, extra = 0, open, assumptions }) {
2008
+ const { ev, model, values } = lm;
2009
+ const first = ev.firstLimit;
2010
+ const range = ev.target;
2011
+ const target = `${pct(model.thresholds.target)} target`;
2012
+ const c = first?.capacity;
2013
+ const sure = !c ? "" : c.provenance === "estimated" ? `est${c.within ? ` ${plusMinus(c)}` : ""}` : plusMinus(c);
2014
+ const over = ev.ranked.filter((x) => (x.util ?? 0) > model.thresholds.full);
2015
+ const when = range ? whenRange(model, range) : "";
2016
+ const estimated = ev.assumptions.filter((a) => a.kind === "capacity" && a.capacity.provenance === "estimated").length;
2017
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
2018
+ verdict && /* @__PURE__ */ jsx("p", {
2019
+ className: "lm-headline",
2020
+ title: ev.verdict.text,
2021
+ "aria-live": "polite",
2022
+ children: !first || !range ? ev.verdict.text : /* @__PURE__ */ jsxs(Fragment, { children: [
2023
+ /* @__PURE__ */ jsxs("b", {
2024
+ className: "lm-num",
2025
+ children: [fmt(values.load), "×"]
2026
+ }),
2027
+ " ·",
2028
+ " ",
2029
+ values.load < range.low ? /* @__PURE__ */ jsxs(Fragment, { children: [
2030
+ "the ",
2031
+ target,
2032
+ " holds to ",
2033
+ /* @__PURE__ */ jsx("b", {
2034
+ className: "lm-num",
2035
+ children: multiples(range, model.searchMax, true)
2036
+ }),
2037
+ when && ` (${when})`
2038
+ ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
2039
+ "past the ",
2040
+ target,
2041
+ " from ",
2042
+ /* @__PURE__ */ jsx("b", {
2043
+ className: "lm-num",
2044
+ children: multiple(range.low, model.searchMax)
2045
+ })
2046
+ ] }),
2047
+ " ",
2048
+ "· first limit ",
2049
+ /* @__PURE__ */ jsx("b", { children: first.name }),
2050
+ sure && /* @__PURE__ */ jsx("span", {
2051
+ className: "lm-tag",
2052
+ "data-kind": c?.provenance === "estimated" ? "estimated" : "range",
2053
+ children: sure
2054
+ }),
2055
+ over.length > 0 && /* @__PURE__ */ jsxs(Fragment, { children: [
2056
+ " ",
2057
+ "· ",
2058
+ /* @__PURE__ */ jsx("b", { children: over.map((x) => x.name).join(", ") }),
2059
+ " past capacity"
2060
+ ] })
2061
+ ] })
2062
+ }),
2063
+ open && verdict && /* @__PURE__ */ jsx("button", {
2064
+ type: "button",
2065
+ className: "lm-link",
2066
+ onClick: (e) => open("verdict", e.currentTarget),
2067
+ children: "Why ›"
2068
+ }),
2069
+ open && assumptions && /* @__PURE__ */ jsxs("button", {
2070
+ type: "button",
2071
+ className: "lm-link",
2072
+ onClick: (e) => open("assumptions", e.currentTarget),
2073
+ children: [
2074
+ "What this assumes · ",
2075
+ ev.assumptions.length + extra,
2076
+ estimated > 0 && ` (${estimated} estimated)`,
2077
+ " ›"
2078
+ ]
2079
+ })
2080
+ ] });
2081
+ }
2082
+ /** The order of the cards in the dock: what the reader changes first, what it changes next to it. */
2083
+ const DOCK = [
2084
+ "controls",
2085
+ "live",
2086
+ "limits",
2087
+ "headroom",
2088
+ "compare"
2089
+ ];
2090
+ /**
2091
+ * Full screen's panels, compact, side by side in a box the screen sizes: what does not fit is left out whole, and
2092
+ * each card opens its panel whole. A phone shows one at a time, under tabs.
2093
+ */
2094
+ function Dock({ lm, panels, open }) {
2095
+ const shown = DOCK.filter((p) => panels.includes(p));
2096
+ const [tab, setTab] = useState(null);
2097
+ if (!shown.length) return null;
2098
+ const active = tab && shown.includes(tab) ? tab : shown[0];
2099
+ return /* @__PURE__ */ jsxs("div", {
2100
+ className: "lm-dock",
2101
+ children: [/* @__PURE__ */ jsx("fieldset", {
2102
+ className: "lm-tabs",
2103
+ "aria-label": "Panels",
2104
+ children: shown.map((p) => /* @__PURE__ */ jsx("button", {
2105
+ type: "button",
2106
+ "aria-pressed": p === active,
2107
+ onClick: () => setTab(p),
2108
+ children: NAMES[p]
2109
+ }, p))
2110
+ }), shown.map((p) => /* @__PURE__ */ jsx(Card, {
2111
+ lm,
2112
+ panel: p,
2113
+ open,
2114
+ active: p === active
2115
+ }, p))]
2116
+ });
2117
+ }
2118
+ function Card({ lm, panel, open, active }) {
2119
+ const box = useRef(null);
2120
+ const more = useRef(null);
2121
+ useClip(box, more);
2122
+ return /* @__PURE__ */ jsxs("div", {
2123
+ className: "lm-mini",
2124
+ "data-mini": panel,
2125
+ "data-active": active || void 0,
2126
+ ref: box,
2127
+ children: [panel === "controls" ? /* @__PURE__ */ jsx(Controls, { lm }) : panel === "compare" ? /* @__PURE__ */ jsx(Compare, { lm }) : /* @__PURE__ */ jsx("div", {
2128
+ className: "lm-card",
2129
+ children: panel === "live" ? /* @__PURE__ */ jsx(Meters, { lm }) : panel === "limits" ? /* @__PURE__ */ jsx(MiniLimits, { lm }) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("h3", { children: "Headroom" }), /* @__PURE__ */ jsx(Sparkline, { lm })] })
2130
+ }), /* @__PURE__ */ jsx("button", {
2131
+ type: "button",
2132
+ className: "lm-more",
2133
+ ref: more,
2134
+ "aria-label": `${NAMES[panel]}, all of it`,
2135
+ onClick: (e) => open(panel, e.currentTarget),
2136
+ children: "›"
2137
+ })]
2138
+ });
2139
+ }
2140
+ /** The rows a card leaves out whole when they do not fit. */
2141
+ const ROWS = ".lm-meter, .lm-mini-lim, .lm-controls > *, .lm-table tbody tr";
2142
+ /**
2143
+ * Hides the rows that cross the bottom of the card, and counts them on its button. Runs again when the card's size
2144
+ * or its rows change: the meters come and go with the load, and the order of the limits with it.
2145
+ */
2146
+ function useClip(box, more) {
2147
+ useEffect(() => {
2148
+ const card = box.current?.querySelector(".lm-card");
2149
+ if (!card) return;
2150
+ const clip = () => {
2151
+ const r = card.getBoundingClientRect();
2152
+ const bottom = r.bottom - Number.parseFloat(getComputedStyle(card).paddingBottom || "0");
2153
+ let n = 0;
2154
+ for (const row of card.querySelectorAll(ROWS)) {
2155
+ const out = r.height > 0 && row.getBoundingClientRect().bottom > bottom + .5;
2156
+ row.toggleAttribute("data-clip", out);
2157
+ if (out && !row.matches("h3")) n++;
2158
+ }
2159
+ if (more.current) more.current.dataset.more = n ? `+${n}` : "";
2160
+ };
2161
+ const ro = new ResizeObserver(clip);
2162
+ ro.observe(card);
2163
+ const mo = new MutationObserver(clip);
2164
+ mo.observe(card, {
2165
+ childList: true,
2166
+ subtree: true
2167
+ });
2168
+ clip();
2169
+ return () => {
2170
+ ro.disconnect();
2171
+ mo.disconnect();
2172
+ };
2173
+ }, [box, more]);
2174
+ }
2175
+ /**
2176
+ * The limits in their order, a line each: the name and how sure its capacity is, the bar, the utilization, where it
2177
+ * is full. The first is the first limit: the verdict line names it.
2178
+ */
2179
+ function MiniLimits({ lm }) {
2180
+ const { ev, model } = lm;
2181
+ const top = Math.max(1.5, model.thresholds.full * 1.5);
2182
+ const at = (u) => `${u / top * 100}%`;
2183
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("h3", { children: "Where it runs out" }), /* @__PURE__ */ jsx("div", {
2184
+ className: "lm-mini-limits",
2185
+ children: ev.ranked.map((c) => /* @__PURE__ */ jsxs("div", {
2186
+ className: "lm-mini-lim",
2187
+ "data-component": c.id,
2188
+ children: [
2189
+ /* @__PURE__ */ jsxs("span", {
2190
+ className: "lm-name",
2191
+ title: c.name,
2192
+ children: [c.name, c.capacity?.provenance === "estimated" ? /* @__PURE__ */ jsx("span", {
2193
+ className: "lm-tag",
2194
+ "data-kind": "estimated",
2195
+ children: "est"
2196
+ }) : !!c.capacity?.within && /* @__PURE__ */ jsx("span", {
2197
+ className: "lm-tag",
2198
+ "data-kind": "range",
2199
+ children: "±"
2200
+ })]
2201
+ }),
2202
+ /* @__PURE__ */ jsxs("span", {
2203
+ className: "lm-track",
2204
+ role: "img",
2205
+ "aria-label": `${c.name} at ${c.util == null ? "off" : pct(c.util)}`,
2206
+ children: [
2207
+ /* @__PURE__ */ jsx("span", {
2208
+ className: "lm-fill",
2209
+ "data-state": c.state,
2210
+ style: { width: `${Math.min(100, (c.util ?? 0) / top * 100)}%` }
2211
+ }),
2212
+ /* @__PURE__ */ jsx("span", {
2213
+ className: "lm-tick",
2214
+ style: { left: at(model.thresholds.target) }
2215
+ }),
2216
+ /* @__PURE__ */ jsx("span", {
2217
+ className: "lm-tick",
2218
+ style: { left: at(model.thresholds.full) }
2219
+ })
2220
+ ]
2221
+ }),
2222
+ /* @__PURE__ */ jsx("span", {
2223
+ className: "lm-val",
2224
+ children: c.util == null ? "—" : pct(c.util)
2225
+ }),
2226
+ /* @__PURE__ */ jsx("span", {
2227
+ className: "lm-val lm-sub",
2228
+ children: c.util == null ? "off" : c.full != null && !Number.isFinite(c.full) ? `full > ${fmt(model.searchMax)}×` : `full ${c.fullRange ? multiples(c.fullRange, model.searchMax, true) : multiple(c.full, model.searchMax)}`
2229
+ })
2230
+ ]
2231
+ }, c.id))
2232
+ })] });
2233
+ }
2234
+ /** The headroom chart as a sparkline: each scenario's line, the target, the load; where the shown one crosses it. */
2235
+ function Sparkline({ lm }) {
2236
+ const { model, values } = lm;
2237
+ const h = useHeadroom(lm);
2238
+ const [box, { width: W, height: H }] = useSize(240);
2239
+ const top = Math.max(1.5, model.thresholds.full * 1.5);
2240
+ const lx = (x) => W * Math.log(x / h.from) / Math.log(h.to / h.from);
2241
+ const ly = (u) => 8 + (H - 10) * (1 - Math.min(u, top * 1.2) / top);
2242
+ const path = (s) => {
2243
+ let d = "";
2244
+ let pen = false;
2245
+ for (const [x, u] of s) {
2246
+ if (u == null) {
2247
+ pen = false;
2248
+ continue;
2249
+ }
2250
+ d += `${pen ? "L" : "M"}${lx(x).toFixed(1)} ${ly(u).toFixed(1)}`;
2251
+ pen = true;
2252
+ }
2253
+ return d;
2254
+ };
2255
+ const line = h.lines.find((l) => l.selected) ?? h.lines[0];
2256
+ const target = pct(model.thresholds.target);
2257
+ const reaches = line ? `${line.targetRange ? multiples(line.targetRange, model.searchMax, true) : multiple(line.target, model.searchMax)}` : "";
2258
+ const when = line ? whenRange(model, line.targetRange) : "";
2259
+ const loadX = lx(Math.min(h.to, Math.max(h.from, values.load)));
2260
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("div", {
2261
+ className: "lm-spark",
2262
+ ref: box,
2263
+ children: H > 0 && /* @__PURE__ */ jsxs("svg", {
2264
+ width: W,
2265
+ height: H,
2266
+ "aria-hidden": "true",
2267
+ children: [
2268
+ /* @__PURE__ */ jsx("line", {
2269
+ className: "lm-spark-th",
2270
+ x1: 0,
2271
+ x2: W,
2272
+ y1: ly(model.thresholds.target),
2273
+ y2: ly(model.thresholds.target)
2274
+ }),
2275
+ h.lines.map((l) => /* @__PURE__ */ jsx("path", {
2276
+ d: path(l.envelope),
2277
+ fill: "none",
2278
+ stroke: scenarioColor(model, l.label),
2279
+ strokeWidth: l.selected ? 2 : 1.25
2280
+ }, l.label ?? "")),
2281
+ /* @__PURE__ */ jsx("line", {
2282
+ className: "lm-spark-load",
2283
+ x1: loadX,
2284
+ x2: loadX,
2285
+ y1: 0,
2286
+ y2: H
2287
+ })
2288
+ ]
2289
+ })
2290
+ }), line && /* @__PURE__ */ jsxs("p", {
2291
+ className: "lm-spark-text",
2292
+ title: `${line.label ?? "It"} reaches the ${target} target at ${reaches}`,
2293
+ children: [
2294
+ line.label ?? "It",
2295
+ " reaches the ",
2296
+ target,
2297
+ " target at ",
2298
+ reaches,
2299
+ when && ` (${when})`,
2300
+ "."
2301
+ ]
2302
+ })] });
2303
+ }
2304
+ // src/story.tsx
2305
+ /**
2306
+ * The model's story, a step at a time: the step's text, where it is, play, back and next. ← and → move through it
2307
+ * while the bar has the keyboard focus (the sliders keep their own arrows). The text keeps the room of the longest
2308
+ * step, so stepping through it never moves what is below. While it plays, the bar shows the step played from the
2309
+ * moment the camera heads for it, before its values change.
2310
+ */
2311
+ function Story({ lm }) {
2312
+ const bar = useRef(null);
2313
+ const { story } = lm.model;
2314
+ if (!story.length) return null;
2315
+ const i = lm.cue?.step ?? lm.step;
2316
+ const last = story.length - 1;
2317
+ const go = (to) => {
2318
+ const next = Math.max(0, Math.min(last, to));
2319
+ if (next !== i || lm.storyPlaying) lm.setStep(next);
2320
+ };
2321
+ const keys = (e) => {
2322
+ if (e.key === "ArrowRight") go(i == null ? 0 : i + 1);
2323
+ else if (e.key === "ArrowLeft" && i != null) go(i - 1);
2324
+ else return;
2325
+ e.preventDefault();
2326
+ };
2327
+ const playing = lm.storyPlaying;
2328
+ return /* @__PURE__ */ jsxs("fieldset", {
2329
+ className: "lm-story",
2330
+ onKeyDown: keys,
2331
+ ref: bar,
2332
+ tabIndex: -1,
2333
+ "data-playing": playing || void 0,
2334
+ children: [
2335
+ /* @__PURE__ */ jsx("legend", { children: "Story" }),
2336
+ /* @__PURE__ */ jsx("span", {
2337
+ className: "lm-sr",
2338
+ "aria-live": "polite",
2339
+ children: i == null ? `A walk through this model in ${story.length} steps.` : `${i + 1} of ${story.length}. ${story[i].text}${lm.stepChanged ? " You changed the values since." : ""}`
2340
+ }),
2341
+ /* @__PURE__ */ jsxs("p", {
2342
+ "aria-hidden": "true",
2343
+ children: [/* @__PURE__ */ jsxs("span", {
2344
+ "data-shown": i == null || void 0,
2345
+ children: [
2346
+ "A walk through this model in ",
2347
+ story.length,
2348
+ " steps."
2349
+ ]
2350
+ }), story.map((st, k) => /* @__PURE__ */ jsxs("span", {
2351
+ "data-shown": k === i || void 0,
2352
+ children: [
2353
+ /* @__PURE__ */ jsxs("b", { children: [
2354
+ k + 1,
2355
+ " of ",
2356
+ story.length
2357
+ ] }),
2358
+ " ",
2359
+ st.text,
2360
+ /* @__PURE__ */ jsx("em", {
2361
+ "data-shown": k === i && lm.stepChanged || void 0,
2362
+ children: " You changed the values since."
2363
+ })
2364
+ ]
2365
+ }, k))]
2366
+ }),
2367
+ i != null && /* @__PURE__ */ jsx("span", {
2368
+ className: "lm-story-progress",
2369
+ "aria-hidden": "true",
2370
+ children: story.map((st, k) => /* @__PURE__ */ jsx("i", {
2371
+ "data-state": k < i ? "done" : k === i ? "now" : void 0,
2372
+ style: k === i ? { "--lm-step": `${stepSeconds(st, lm.engine.transition)}s` } : void 0
2373
+ }, k === i ? `${k}-${playing}` : k))
2374
+ }),
2375
+ /* @__PURE__ */ jsxs("span", {
2376
+ className: "lm-story-nav",
2377
+ children: [
2378
+ /* @__PURE__ */ jsx("button", {
2379
+ type: "button",
2380
+ onClick: () => lm.setStoryPlaying(!playing),
2381
+ "aria-pressed": playing,
2382
+ children: playing ? "❚❚ Pause" : "▶ Play"
2383
+ }),
2384
+ i != null && /* @__PURE__ */ jsx("button", {
2385
+ type: "button",
2386
+ onClick: () => go(i - 1),
2387
+ "aria-disabled": i === 0,
2388
+ children: "Back"
2389
+ }),
2390
+ /* @__PURE__ */ jsx("button", {
2391
+ type: "button",
2392
+ onClick: () => go(i == null ? 0 : i + 1),
2393
+ "aria-disabled": i === last,
2394
+ children: i == null ? "Start" : "Next"
2395
+ }),
2396
+ i != null && lm.stepChanged && /* @__PURE__ */ jsx("button", {
2397
+ type: "button",
2398
+ onClick: () => {
2399
+ lm.setStep(i);
2400
+ bar.current?.focus();
2401
+ },
2402
+ children: "Show again"
2403
+ }),
2404
+ i != null && /* @__PURE__ */ jsx("button", {
2405
+ type: "button",
2406
+ onClick: () => lm.setStep(null),
2407
+ "aria-label": "Leave the story",
2408
+ children: "Done"
2409
+ })
2410
+ ]
2411
+ })
2412
+ ]
2413
+ });
2414
+ }
2415
+ // src/styles.ts
2416
+ const LIGHT = `
2417
+ --lm-bg: #eef2f5; --lm-surface: #ffffff; --lm-fg: #17212b; --lm-muted: #5d6d7c; --lm-line: #c6d0da;
2418
+ --lm-accent: #0b6b8f; --lm-accent-soft: #d6e9f0; --lm-alt: #7a4f9a; --lm-alt-soft: #efe5f6;
2419
+ --lm-ok: #2a7f5a; --lm-warn: #b86e00; --lm-drop: #b7392e; --lm-lane: #e3e9ee;
2420
+ --lm-s1: #2a78d6; --lm-s2: #eb6834; --lm-s3: #6250d6; --lm-s4: #eda100; color-scheme: light;`;
2421
+ const DARK = `
2422
+ --lm-bg: #0d141b; --lm-surface: #151e27; --lm-fg: #e4ebf1; --lm-muted: #93a3b3; --lm-line: #2a3744;
2423
+ --lm-accent: #5fb7d6; --lm-accent-soft: #163442; --lm-alt: #c39be0; --lm-alt-soft: #2b2236;
2424
+ --lm-ok: #5fc08f; --lm-warn: #e2a24a; --lm-drop: #e26a5c; --lm-lane: #1b2631;
2425
+ --lm-s1: #3987e5; --lm-s2: #d95926; --lm-s3: #9085e9; --lm-s4: #c98500; color-scheme: dark;`;
2426
+ /**
2427
+ * Theme tokens and the layout of every piece. Scoped to `.lm`; override any `--lm-*` token to restyle. Two are for the
2428
+ * page around it: `--lm-pad` (the root's padding, 16px) and `--lm-root-bg` (its background, `--lm-bg`), for a card
2429
+ * that has its own, set on the root (`.card > .lm`) so they resolve there and reach no nested board; full screen
2430
+ * keeps both.
2431
+ */
2432
+ const LOADMAP_CSS = `
2433
+ .lm { ${LIGHT}
2434
+ --lm-font: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
2435
+ --lm-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
2436
+ font: 14px/1.45 var(--lm-font); color: var(--lm-fg); background: var(--lm-root-bg, var(--lm-bg));
2437
+ display: grid; gap: 14px; padding: var(--lm-pad, 16px); min-width: 0; box-sizing: border-box; }
2438
+ @media (prefers-color-scheme: dark) { .lm:not([data-theme="light"]) { ${DARK} } }
2439
+ .lm[data-theme="dark"] { ${DARK} }
2440
+ .lm *, .lm *::before, .lm *::after { box-sizing: border-box; }
2441
+ .lm h2 { font-size: 1.3rem; font-weight: 600; margin: 0; text-wrap: balance; }
2442
+ .lm h3 { font: 600 .74rem var(--lm-font); text-transform: uppercase; letter-spacing: .08em; color: var(--lm-muted); margin: 0; }
2443
+ .lm button:focus-visible, .lm input:focus-visible, .lm select:focus-visible { outline: 2px solid var(--lm-accent); outline-offset: 2px; }
2444
+ .lm-problems { margin: 0; padding: 10px 12px; font: .8rem/1.5 var(--lm-mono); white-space: pre-wrap; overflow-x: auto; color: var(--lm-fg); background: var(--lm-surface); border: 1px solid var(--lm-line); border-left: 3px solid var(--lm-drop); border-radius: 6px; }
2445
+ .lm-note { margin: 0; font-size: .8rem; color: var(--lm-muted); }
2446
+ .lm-card { background: var(--lm-surface); border: 1px solid var(--lm-line); border-radius: 8px; padding: 14px 16px; display: grid; gap: 12px; align-content: start; min-width: 0; }
2447
+
2448
+ .lm-wrap { display: grid; gap: 8px; min-width: 0; position: relative; }
2449
+ .lm-bar { display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap; }
2450
+ .lm-btn { font: 500 .8rem var(--lm-font); color: var(--lm-fg); background: var(--lm-surface); border: 1px solid var(--lm-line); border-radius: 6px; padding: 6px 12px; cursor: pointer; white-space: nowrap; }
2451
+ .lm-board { position: relative; background: var(--lm-surface); border: 1px solid var(--lm-line); border-radius: 8px; overflow: hidden; margin: 0 auto; width: 100%; }
2452
+ .lm-board svg { display: block; width: 100%; height: auto; font-family: var(--lm-font); }
2453
+ .lm-board canvas { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; }
2454
+ /* the story's title over the board while it plays: a lower third, at the top when what is framed is low; a strip
2455
+ across the top of a narrow board */
2456
+ .lm-title { position: absolute; left: 12px; bottom: 12px; z-index: 1; display: grid; gap: 1px; max-width: min(34rem, calc(100% - 24px)); padding: 7px 12px 8px; border-left: 4px solid var(--lm-accent); border-radius: 0 6px 6px 0; background: color-mix(in srgb, var(--lm-surface) 92%, transparent); box-shadow: 0 4px 16px rgb(0 0 0 / .12); pointer-events: none; overflow-wrap: anywhere; }
2457
+ .lm-title[data-top] { top: 12px; bottom: auto; }
2458
+ .lm-title b { font-size: .95rem; font-weight: 600; }
2459
+ .lm-title span { font: 500 .8rem var(--lm-mono); color: var(--lm-muted); }
2460
+ @container (max-width: 520px) {
2461
+ .lm-title, .lm-title[data-top] { top: 0; right: 0; bottom: auto; left: 0; max-width: none; padding: 4px 8px; border-radius: 0; box-shadow: none; }
2462
+ .lm-title b { font-size: .8rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
2463
+ .lm-title span { display: none; }
2464
+ }
2465
+ .lm-legend { display: flex; flex-wrap: wrap; gap: 6px 16px; font-size: .78rem; color: var(--lm-muted); }
2466
+ .lm-legend i { display: inline-block; width: 10px; height: 10px; border-radius: 50%; vertical-align: -1px; margin-right: 5px; }
2467
+
2468
+ /* full screen (the browser's, or a fixed overlay): a column that never scrolls. The diagram as wide as the screen on
2469
+ top; under it the verdict in a line and the panels, compact, in a dock the screen sizes. The load changes what is
2470
+ in them, never their size, so it never moves the board. Focus: the diagram, the story, the verdict and the load */
2471
+ .lm-side, .lm-card > .lm-panel { display: contents; }
2472
+ .lm-panel { display: grid; gap: 14px; min-width: 0; }
2473
+ .lm[data-full] { height: 100vh; height: 100dvh; padding: 16px; background: var(--lm-bg); overflow: hidden; overscroll-behavior: contain; display: flex; flex-direction: column; gap: 10px; position: relative; }
2474
+ .lm[data-full="overlay"] { position: fixed; inset: 0; z-index: 2147483000; width: auto; max-width: none; max-height: none; margin: 0; border: 0; }
2475
+ .lm[data-full] > * { flex: none; }
2476
+ /* a page of its own keeps the rest outside full screen, as <Loadmap> does */
2477
+ .lm[data-full] > :not(.lm-head, h2, .lm-scenarios, .lm-story, .lm-wrap, .lm-line, .lm-dock, .lm-side) { display: none; }
2478
+ .lm-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 20px; min-width: 0; }
2479
+ .lm-head h2 { font-size: 1.1rem; }
2480
+ .lm[data-full] .lm-wrap { gap: 6px; }
2481
+ /* the board as large as fits (--lm-fit, from Diagram), left under the bar, so the legend starts where the board does */
2482
+ .lm[data-full] .lm-board { width: var(--lm-fit, 100%); margin: 0; align-self: start; justify-self: start; }
2483
+ .lm-tools { display: flex; align-items: center; gap: 8px; margin-left: auto; }
2484
+ .lm-modes { display: inline-flex; margin: 0; padding: 0; min-width: 0; border: 1px solid var(--lm-line); border-radius: 6px; overflow: hidden; }
2485
+ .lm-modes button { font: 500 .8rem var(--lm-font); color: var(--lm-fg); background: var(--lm-surface); border: 0; padding: 6px 12px; cursor: pointer; }
2486
+ .lm-modes button[aria-pressed="true"] { background: var(--lm-fg); color: var(--lm-surface); }
2487
+ .lm[data-full] .lm-story { padding: 6px 12px; }
2488
+ .lm[data-full] [data-out] { display: none; }
2489
+
2490
+ .lm-line { display: flex; align-items: center; gap: 6px 14px; min-width: 0; padding: 6px 12px; border-left: 4px solid var(--lm-ok); background: var(--lm-accent-soft); border-radius: 0 6px 6px 0; }
2491
+ .lm-line[data-tier="warn"] { border-color: var(--lm-warn); }
2492
+ .lm-line[data-tier="over"] { border-color: var(--lm-drop); }
2493
+ .lm-headline { flex: 1 1 auto; min-width: 0; margin: 0; font-size: .9rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
2494
+ .lm-num { font: 600 .95em var(--lm-mono); font-variant-numeric: tabular-nums; }
2495
+ .lm-link { font: 500 .8rem var(--lm-font); color: var(--lm-accent); background: none; border: 0; padding: 2px 4px; cursor: pointer; white-space: nowrap; }
2496
+ .lm-line .lm-range { flex: 0 1 380px; display: grid; grid-template-columns: auto minmax(100px, 1fr); align-items: center; gap: 10px; font-size: .84rem; }
2497
+ .lm-line output { font-family: var(--lm-mono); font-variant-numeric: tabular-nums; }
2498
+ .lm-line input[type=range] { width: 100%; accent-color: var(--lm-accent); }
2499
+
2500
+ .lm-dock { display: flex; gap: 10px; min-width: 0; }
2501
+ .lm[data-full] > .lm-dock { flex: 1 1 0; min-height: clamp(200px, 26dvh, 340px); }
2502
+ .lm-tabs { display: none; margin: 0; padding: 0; border: 0; min-width: 0; }
2503
+ .lm-mini { position: relative; flex: 1 1 0; min-width: 0; min-height: 0; display: grid; container-type: inline-size; }
2504
+ .lm-mini[data-mini="controls"] { flex-grow: 1.25; }
2505
+ .lm-mini[data-mini="limits"] { flex-grow: 1.45; }
2506
+ .lm-mini[data-mini="live"] { flex-grow: .8; }
2507
+ .lm-mini[data-mini="headroom"] { flex-grow: .9; }
2508
+ .lm-mini[data-mini="compare"] { flex-grow: 1.3; }
2509
+ .lm-mini > .lm-card { min-height: 0; overflow: hidden; padding: 10px 12px; gap: 6px; align-content: start; }
2510
+ .lm-mini [data-clip] { visibility: hidden; }
2511
+ .lm-more { position: absolute; top: 6px; right: 6px; font: 500 .8rem var(--lm-font); color: var(--lm-accent); background: var(--lm-surface); border: 0; border-radius: 4px; padding: 2px 6px; cursor: pointer; }
2512
+ .lm-more[data-more]:not([data-more=""])::before { content: attr(data-more) " "; }
2513
+ .lm-mini .lm-meters { grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 4px; }
2514
+ .lm-mini .lm-meter { display: flex; align-items: baseline; gap: 8px; padding: 3px 8px; }
2515
+ .lm-mini .lm-meter b { flex: none; font-size: .9rem; }
2516
+ .lm-mini .lm-meter span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
2517
+ /* one grid for every row, so the bars line up whatever the names */
2518
+ .lm-mini-limits { display: grid; grid-template-columns: minmax(0, max-content) minmax(48px, 1fr) auto auto; gap: 6px 10px; }
2519
+ .lm-mini-lim { display: grid; grid-column: 1 / -1; grid-template-columns: subgrid; align-items: center; font-size: .8rem; }
2520
+ .lm-mini-lim .lm-name { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
2521
+ .lm-mini-lim .lm-tag { margin-left: 5px; }
2522
+ .lm-mini-lim .lm-track { height: 9px; }
2523
+ .lm-mini-lim .lm-val { white-space: nowrap; }
2524
+ .lm-mini-lim .lm-sub { font: 400 .74rem var(--lm-mono); color: var(--lm-muted); }
2525
+ .lm-mini .lm-controls { gap: 6px; column-gap: 16px; }
2526
+ .lm-mini .lm-controls small, .lm-mini .lm-controls > h3:not(:first-child) { display: none; }
2527
+ .lm-mini .lm-controls label.lm-range { grid-template-columns: minmax(0, 1fr) minmax(90px, 1.2fr); align-items: center; gap: 10px; font-size: .8rem; }
2528
+ .lm-mini .lm-select { grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 10px; font-size: .8rem; }
2529
+ .lm-mini .lm-select select { width: auto; padding: 1px 6px; font-size: .78rem; }
2530
+ .lm-mini .lm-switch { font-size: .8rem; }
2531
+ .lm-mini .lm-switch input { margin-top: 2px; }
2532
+ .lm-mini .lm-presets { gap: 4px; }
2533
+ .lm-mini .lm-presets button { padding: 2px 8px; font-size: .72rem; }
2534
+ @container (min-width: 420px) {
2535
+ .lm-mini .lm-controls { grid-template-columns: repeat(2, minmax(0, 1fr)); }
2536
+ .lm-mini .lm-controls > :is(h3, .lm-presets), .lm-mini .lm-controls > h3 + .lm-range { grid-column: 1 / -1; }
2537
+ }
2538
+ .lm-mini .lm-compare > :not(h3:first-child, .lm-table-wrap:nth-child(3)) { display: none; }
2539
+ .lm-mini .lm-table { font-size: .76rem; }
2540
+ .lm-mini .lm-table th, .lm-mini .lm-table td { padding: 3px 8px 3px 0; }
2541
+ .lm-mini .lm-table small { display: none; }
2542
+ .lm-mini .lm-table thead th { white-space: nowrap; font-size: .6rem; }
2543
+ .lm-mini > .lm-card:has(> .lm-spark) { grid-template-rows: auto minmax(0, 1fr) auto; align-content: stretch; }
2544
+ .lm-spark { position: relative; min-height: 0; }
2545
+ .lm-spark svg { position: absolute; inset: 0; display: block; overflow: hidden; }
2546
+ .lm-spark-th { stroke: var(--lm-muted); stroke-dasharray: 4 3; }
2547
+ .lm-spark-load { stroke: var(--lm-fg); opacity: .45; }
2548
+ .lm-spark-text { margin: 0; font-size: .76rem; color: var(--lm-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
2549
+
2550
+ /* the drawer: the page's own panel, alone, over the right of the board */
2551
+ .lm[data-full] > .lm-drawer:not([data-drawer]) { display: none; }
2552
+ .lm[data-full] > .lm-drawer[data-drawer] { display: grid; gap: 14px; align-content: start; position: absolute; top: 16px; right: 16px; bottom: 16px; z-index: 4; width: min(640px, calc(100% - 32px)); overflow: auto; overscroll-behavior: contain; padding: 14px; background: var(--lm-bg); border: 1px solid var(--lm-line); border-radius: 10px; box-shadow: -8px 0 30px rgb(0 0 0 / .2); container-type: inline-size; }
2553
+ .lm-side[data-drawer] :is(.lm-panel, .lm-strip, .lm-charts, .lm-card):not([data-drawn]):not(.lm-panel *) { display: none; }
2554
+ .lm-side[data-drawer] .lm-strip { grid-template-columns: minmax(0, 1fr); }
2555
+ .lm-drawer-bar { display: flex; justify-content: flex-end; }
2556
+
2557
+ /* a page of its own: its .lm-side is a box under the board that scrolls on its own, the board as large as leaves it a
2558
+ third of the screen */
2559
+ .lm[data-full] > .lm-side:not(.lm-drawer) { display: grid; gap: 14px; align-content: start; flex: 1 1 0; min-height: 33dvh; overflow: auto; overscroll-behavior: contain; container-type: inline-size; }
2560
+
2561
+ /* focus: the board and what runs on it in the middle of the screen */
2562
+ .lm[data-mode="focus"] .lm-scenarios, .lm[data-mode="focus"] > .lm-side:not(.lm-drawer) { display: none; }
2563
+ .lm[data-mode="focus"] > .lm-wrap { margin-top: auto; }
2564
+ .lm[data-mode="focus"] > :is(.lm-story, .lm-line) { order: 1; }
2565
+ .lm[data-mode="focus"]::after { content: ""; order: 2; margin-top: auto; }
2566
+ .lm[data-mode="focus"] > .lm-story { border-left-width: 4px; padding: 10px 14px; }
2567
+ .lm[data-mode="focus"] > .lm-story p { font-size: 1.1rem; }
2568
+
2569
+ @media (max-width: 760px) {
2570
+ .lm[data-full] { padding: 10px; gap: 8px; }
2571
+ /* the page has the title, and the legend: here they would leave the diagram no room */
2572
+ .lm[data-full] > h2, .lm[data-full] :is(.lm-head h2, .lm-legend, .lm-story legend) { display: none; }
2573
+ /* the one exception: here the diagram runs top to bottom, and shrunk to the screen it is too small to read, so it
2574
+ pans in a box of its own with the bar on top. The page never scrolls */
2575
+ .lm[data-full] .lm-board { width: 100%; }
2576
+ .lm[data-full] > .lm-wrap { height: 40dvh; overflow: auto; row-gap: 0; overscroll-behavior: contain; }
2577
+ .lm[data-mode="focus"] > .lm-wrap { height: auto; flex: 1 1 0; min-height: 0; margin-top: 0; }
2578
+ .lm[data-full] .lm-bar { position: sticky; top: 0; z-index: 1; padding-bottom: 8px; background: var(--lm-bg); }
2579
+ .lm[data-full] .lm-line { flex-wrap: wrap; }
2580
+ .lm[data-full] > .lm-story { padding: 6px 10px; gap: 6px 10px; }
2581
+ .lm[data-full] > .lm-story p { font-size: .84rem; }
2582
+ .lm[data-full] .lm-story button { padding: 4px 10px; }
2583
+ .lm[data-full] .lm-headline { flex-basis: 100%; }
2584
+ .lm-dock { flex-direction: column; min-height: 0; gap: 6px; }
2585
+ .lm-tabs { display: flex; flex: none; gap: 2px; border-bottom: 1px solid var(--lm-line); overflow: hidden; }
2586
+ .lm-tabs button { font: 500 .78rem var(--lm-font); color: var(--lm-muted); background: none; border: 0; border-bottom: 2px solid transparent; padding: 6px 8px; cursor: pointer; white-space: nowrap; }
2587
+ .lm-tabs button[aria-pressed="true"] { color: var(--lm-fg); border-color: var(--lm-fg); }
2588
+ .lm-mini:not([data-active]) { display: none; }
2589
+ .lm[data-full] > .lm-side[data-drawer] { inset: 8px; width: auto; }
2590
+ }
2591
+
2592
+ .lm-verdict { margin: 0; padding: 10px 14px; border-left: 4px solid var(--lm-ok); background: var(--lm-accent-soft); border-radius: 0 6px 6px 0; }
2593
+ .lm-verdict[data-tier="warn"] { border-color: var(--lm-warn); }
2594
+ .lm-verdict[data-tier="over"] { border-color: var(--lm-drop); }
2595
+ .lm-measure { margin: 6px 0 0; padding: 0 14px; font-size: .86rem; color: var(--lm-muted); }
2596
+
2597
+ .lm-strip { display: grid; grid-template-columns: minmax(0, 3fr) minmax(280px, 2fr); gap: 14px; align-items: start; }
2598
+ @container (max-width: 860px) { .lm-strip { grid-template-columns: minmax(0, 1fr); } }
2599
+ .lm { container-type: inline-size; }
2600
+
2601
+ .lm-meters { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 8px; }
2602
+ .lm-meter { padding: 8px 10px; border-radius: 6px; background: var(--lm-bg); min-width: 0; }
2603
+ .lm-meter b { display: block; font: 500 1.15rem var(--lm-mono); font-variant-numeric: tabular-nums; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
2604
+ .lm-meter span { font-size: .74rem; color: var(--lm-muted); }
2605
+ .lm-meter[data-state="warn"] b { color: var(--lm-warn); } .lm-meter[data-state="over"] b { color: var(--lm-drop); }
2606
+
2607
+ .lm-limits { display: grid; gap: 10px; }
2608
+ .lm-lim, .lm-scale { display: grid; grid-template-columns: minmax(0, 14rem) minmax(0, 1fr) 10rem; gap: 4px 14px; align-items: center; }
2609
+ @container (max-width: 640px) { .lm-lim, .lm-scale { grid-template-columns: minmax(0, 1fr); } .lm-scale > :first-child, .lm-scale > :last-child { display: none; } }
2610
+ .lm-lim b { display: block; font-weight: 600; font-size: .88rem; }
2611
+ .lm-lim .lm-sub { display: block; font-size: .74rem; color: var(--lm-muted); }
2612
+ .lm-tag { font: 600 .64rem var(--lm-font); text-transform: uppercase; letter-spacing: .06em; border-radius: 3px; padding: 1px 5px; margin-left: 6px; vertical-align: 1px; }
2613
+ .lm-tag[data-kind="first"] { color: var(--lm-surface); background: var(--lm-drop); }
2614
+ .lm-tag[data-kind="estimated"] { color: var(--lm-warn); border: 1px solid currentColor; }
2615
+ .lm-tag[data-kind="range"] { color: var(--lm-muted); border: 1px solid currentColor; }
2616
+ .lm-track { position: relative; height: 16px; background: var(--lm-bg); border-radius: 3px; overflow: hidden; }
2617
+ .lm-fill { position: absolute; inset: 0 auto 0 0; background: var(--lm-ok); transition: width .25s ease; }
2618
+ .lm-fill[data-state="warn"] { background: var(--lm-warn); } .lm-fill[data-state="over"] { background: var(--lm-drop); }
2619
+ .lm-tick { position: absolute; top: 0; bottom: 0; width: 1px; background: var(--lm-fg); opacity: .55; }
2620
+ .lm-val { font: 500 .8rem var(--lm-mono); font-variant-numeric: tabular-nums; }
2621
+ .lm-val small { display: block; font: 400 .72rem var(--lm-font); color: var(--lm-muted); }
2622
+ .lm-scale { font: 400 .7rem var(--lm-mono); color: var(--lm-muted); }
2623
+ .lm-scale div { position: relative; height: 12px; }
2624
+ .lm-scale div span { position: absolute; transform: translateX(-50%); white-space: nowrap; }
2625
+
2626
+ .lm-controls label.lm-range { display: grid; gap: 4px; font-size: .84rem; }
2627
+ .lm-controls label.lm-range > span { display: flex; justify-content: space-between; gap: 8px; }
2628
+ .lm-controls output { font-family: var(--lm-mono); font-variant-numeric: tabular-nums; }
2629
+ .lm-controls input[type=range] { width: 100%; accent-color: var(--lm-accent); }
2630
+ .lm-presets { display: flex; flex-wrap: wrap; gap: 6px; }
2631
+ .lm-presets button { font: 500 .76rem var(--lm-font); background: var(--lm-accent-soft); color: var(--lm-fg); border: 1px solid transparent; border-radius: 5px; padding: 5px 10px; cursor: pointer; }
2632
+ .lm-presets button[aria-pressed="true"] { border-color: var(--lm-accent); }
2633
+ .lm-switch { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 0 8px; align-items: start; font-size: .84rem; cursor: pointer; }
2634
+ .lm-switch input { margin: 3px 0 0; accent-color: var(--lm-accent); }
2635
+ .lm-switch small, .lm-select small { grid-column: 2; color: var(--lm-muted); font-size: .74rem; line-height: 1.3; }
2636
+ .lm-select { display: grid; gap: 4px; font-size: .84rem; }
2637
+ .lm-select select { width: 100%; min-width: 0; font: 400 .84rem var(--lm-font); color: var(--lm-fg); background: var(--lm-surface); border: 1px solid var(--lm-line); border-radius: 5px; padding: 5px 8px; }
2638
+ .lm-off { opacity: .45; cursor: default; }
2639
+
2640
+ .lm-facts { margin: 0; padding-left: 1.1em; font-size: .88rem; columns: 2; column-gap: 28px; }
2641
+ @container (max-width: 860px) { .lm-facts { columns: 1; } }
2642
+ .lm-facts li { margin-bottom: 8px; break-inside: avoid; }
2643
+ .lm-prov { font: 600 .66rem var(--lm-font); text-transform: uppercase; letter-spacing: .06em; }
2644
+ .lm-prov[data-kind="measured"] { color: var(--lm-ok); } .lm-prov[data-kind="estimated"] { color: var(--lm-warn); }
2645
+ .lm-prov[data-kind="configured"] { color: var(--lm-accent); }
2646
+
2647
+ /* scenario identity colours (s1–s4) are checked for colour-blind separation on both surfaces; text never wears them */
2648
+ .lm-scenarios { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; border: 0; padding: 0; margin: 0; min-width: 0; }
2649
+ .lm-scenarios legend { float: left; font: 600 .74rem var(--lm-font); text-transform: uppercase; letter-spacing: .08em; color: var(--lm-muted); margin-right: 6px; padding: 0; }
2650
+ .lm-scenarios button { font: 500 .84rem var(--lm-font); color: var(--lm-fg); background: var(--lm-surface); border: 1px solid var(--lm-line); border-radius: 6px; padding: 6px 12px; cursor: pointer; }
2651
+ .lm-scenarios button[aria-pressed="true"] { border-color: var(--lm-fg); box-shadow: inset 0 0 0 1px var(--lm-fg); }
2652
+ .lm-scenarios i, .lm-table i { display: inline-block; width: 10px; height: 10px; border-radius: 50%; vertical-align: -1px; margin-right: 6px; }
2653
+ .lm-story { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; margin: 0; min-width: 0; padding: 8px 12px; border: 1px solid var(--lm-line); border-left: 3px solid var(--lm-accent); border-radius: 6px; background: var(--lm-surface); }
2654
+ .lm-story legend { float: left; font: 600 .74rem var(--lm-font); text-transform: uppercase; letter-spacing: .08em; color: var(--lm-muted); padding: 0; }
2655
+ .lm-story p { flex: 1 1 240px; display: grid; margin: 0; font: 400 .9rem/1.4 var(--lm-font); color: var(--lm-fg); }
2656
+ .lm-story p > span { grid-area: 1 / 1; }
2657
+ .lm-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
2658
+ .lm-story p > span:not([data-shown]), .lm-story em:not([data-shown]) { visibility: hidden; }
2659
+ .lm-story-progress { display: flex; align-items: center; gap: 4px; }
2660
+ .lm-story-progress i { position: relative; width: 28px; height: 4px; border-radius: 2px; background: var(--lm-line); overflow: hidden; }
2661
+ .lm-story-progress i[data-state="done"], .lm-story:not([data-playing]) .lm-story-progress i[data-state="now"] { background: var(--lm-accent); }
2662
+ .lm-story[data-playing] .lm-story-progress i[data-state="now"]::before { content: ""; position: absolute; inset: 0; background: var(--lm-accent); transform-origin: left; animation: lm-step var(--lm-step) linear both; }
2663
+ @keyframes lm-step { from { transform: scaleX(0); } to { transform: scaleX(1); } }
2664
+ .lm-story b { font-weight: 600; color: var(--lm-muted); margin-right: 4px; white-space: nowrap; }
2665
+ .lm-story-nav { display: flex; gap: 6px; }
2666
+ .lm-story em { color: var(--lm-muted); }
2667
+ .lm-story button { font: 500 .84rem var(--lm-font); color: var(--lm-fg); background: var(--lm-surface); border: 1px solid var(--lm-line); border-radius: 6px; padding: 6px 12px; cursor: pointer; }
2668
+ .lm-story button[aria-disabled="true"] { opacity: .45; cursor: default; }
2669
+ .lm-own { font-size: .78rem; color: var(--lm-muted); }
2670
+ .lm-key { display: inline-block; width: 14px; height: 2px; border-radius: 1px; vertical-align: 3px; margin-right: 6px; }
2671
+
2672
+ .lm-compare-text { margin: 0; }
2673
+ .lm-table-wrap { overflow-x: auto; }
2674
+ .lm-table { border-collapse: collapse; width: 100%; font-size: .84rem; }
2675
+ .lm-table th, .lm-table td { text-align: left; padding: 6px 10px 6px 0; border-bottom: 1px solid var(--lm-line); vertical-align: top; }
2676
+ .lm-table thead th { font: 600 .7rem var(--lm-font); text-transform: uppercase; letter-spacing: .06em; color: var(--lm-muted); }
2677
+ .lm-table tbody th { font-weight: 600; white-space: nowrap; }
2678
+ .lm-table td { font-family: var(--lm-mono); font-variant-numeric: tabular-nums; }
2679
+ .lm-table td.lm-text { font-family: var(--lm-font); }
2680
+ .lm-table td small { display: block; font: 400 .72rem var(--lm-font); color: var(--lm-muted); }
2681
+ .lm-table tr[aria-current] th { text-decoration: underline; text-underline-offset: 3px; }
2682
+
2683
+ .lm-chart { position: relative; min-width: 0; }
2684
+ .lm-chart svg { display: block; overflow: visible; }
2685
+ .lm-chart:focus-visible { outline: 2px solid var(--lm-accent); outline-offset: 2px; }
2686
+ .lm-axis, .lm-axis text { font: 400 11px var(--lm-mono); fill: var(--lm-muted); }
2687
+ .lm-mark { font: 600 11px var(--lm-mono); fill: var(--lm-fg); }
2688
+ .lm-tip { position: absolute; z-index: 2; display: grid; gap: 2px; width: max-content; max-width: min(17rem, calc(100% - 8px)); overflow-wrap: anywhere; padding: 8px 10px; font-size: .78rem; background: var(--lm-surface); color: var(--lm-fg); border: 1px solid var(--lm-line); border-radius: 6px; box-shadow: 0 4px 14px rgb(0 0 0 / .14); pointer-events: none; }
2689
+ .lm-tip strong { font: 600 .82rem var(--lm-mono); font-variant-numeric: tabular-nums; }
2690
+ .lm-tip .lm-sub { color: var(--lm-muted); }
2691
+ .lm-nowrap { white-space: nowrap; }
2692
+ .lm-node { cursor: pointer; outline: none; }
2693
+ .lm-node:focus-visible > :first-child { stroke-width: 3; }
2694
+
2695
+ @media (prefers-reduced-motion: reduce) {
2696
+ .lm-fill { transition: none; }
2697
+ .lm-story[data-playing] .lm-story-progress i[data-state="now"]::before { animation: none; transform: none; }
2698
+ }
2699
+ `;
2700
+ /** Adds the stylesheet once per document. */
2701
+ function injectStyles(doc = document) {
2702
+ if (doc.getElementById("loadmap-css")) return;
2703
+ const el = doc.createElement("style");
2704
+ el.id = "loadmap-css";
2705
+ el.textContent = LOADMAP_CSS;
2706
+ doc.head.appendChild(el);
2707
+ }
2708
+ // src/engine.ts
2709
+ const TOKENS = [
2710
+ "accent",
2711
+ "alt",
2712
+ "ok",
2713
+ "warn",
2714
+ "drop",
2715
+ "muted",
2716
+ "fg",
2717
+ "surface",
2718
+ "line"
2719
+ ];
2720
+ /** The stroke of a hollow dot, in scene units. */
2721
+ const RING = 1.4;
2722
+ /** Seconds the breathing of the first limit takes, in and out. */
2723
+ const BREATH = 2.4;
2724
+ /** Sets an attribute only when it changes: most frames change nothing. */
2725
+ function set(el, name, value) {
2726
+ if (el.getAttribute(name) !== value) el.setAttribute(name, value);
2727
+ }
2728
+ /**
2729
+ * Everything that moves, without React: the sim, the dots on the canvas, the worker fills in the SVG, and the move from
2730
+ * one structure to the next. React renders the structure once per scene, and once per frame while it moves; the engine
2731
+ * updates the moving parts every frame, and export drives it frame by frame instead of the animation loop.
2732
+ */
2733
+ var Engine = class {
2734
+ model;
2735
+ view;
2736
+ sim;
2737
+ ev;
2738
+ scene = null;
2739
+ /** What the diagram draws now: the scene, or a frame of the move to it. */
2740
+ frame = null;
2741
+ /** Counts the frames: export waits until the diagram drew this one. */
2742
+ frameId = 0;
2743
+ drawnFrame = -1;
2744
+ /** Seconds a new structure takes to move in; 0 cuts. */
2745
+ transition = .8;
2746
+ /** The structure key the current values want; `scene.key` catches up once the layout is done. */
2747
+ wantKey = "";
2748
+ /** The values React last drew labels and colours for; a frame is complete once they match `ev.values`. */
2749
+ drawnValues = "";
2750
+ /** The component a story step points at, and the one the diagram last outlined: export waits for them to match. */
2751
+ wantFocus = null;
2752
+ /** The story step shown, set as soon as one is chosen: a recorder holding an old handle still reads it. */
2753
+ storyStep = null;
2754
+ drawnFocus = null;
2755
+ paused = false;
2756
+ /** Flights cut and the first limit holds still. */
2757
+ reducedMotion = false;
2758
+ /** The part of the scene the board shows while the story plays; null for all of it. */
2759
+ camera = null;
2760
+ /** What the diagram says about the step the story plays; null when it does not play. */
2761
+ cue = null;
2762
+ host = null;
2763
+ colors = {};
2764
+ svg = null;
2765
+ canvas = null;
2766
+ #o;
2767
+ #slots = [];
2768
+ #paths = /* @__PURE__ */ new Map();
2769
+ #move = null;
2770
+ #listeners = /* @__PURE__ */ new Set();
2771
+ /** The last steps came while paused: export drives a paused engine, a page that only paused it does not. */
2772
+ #driven = false;
2773
+ /** While the structure moves, each leg's path in this frame, shared by the dots on it. */
2774
+ #legs = {
2775
+ frame: -1,
2776
+ paths: /* @__PURE__ */ new Map()
2777
+ };
2778
+ /** Seconds the engine has run since the last reset: the first limit breathes on it. */
2779
+ #clock = 0;
2780
+ #story = null;
2781
+ constructor(model, view, ev, o = {}) {
2782
+ this.model = model;
2783
+ this.view = view;
2784
+ this.ev = ev;
2785
+ this.#o = o;
2786
+ this.sim = createSim(model, ev, o);
2787
+ }
2788
+ setEvaluation(ev) {
2789
+ if (ev === this.ev) return;
2790
+ const same = JSON.stringify(ev.values) === JSON.stringify(this.ev.values);
2791
+ this.ev = ev;
2792
+ if (!same) this.sim.update(ev);
2793
+ }
2794
+ /**
2795
+ * Takes a new scene. A new structure moves in from what is drawn now, unless `cut`, the diagram turned (a new
2796
+ * direction is a new screen size, not a new design), or it is paused with nothing stepping it; the first scene just
2797
+ * shows.
2798
+ */
2799
+ setScene(scene, o = {}) {
2800
+ if (scene === this.scene) return;
2801
+ const from = this.frame;
2802
+ const seconds = this.transition;
2803
+ this.scene = scene;
2804
+ this.#paths.clear();
2805
+ const move = from && !o.cut && seconds > 0 && Number.isFinite(seconds) && (!this.paused || this.#driven) && from.direction === scene.direction && from.key !== scene.key;
2806
+ this.#move = move ? {
2807
+ at: morph(from, scene),
2808
+ t: 0,
2809
+ seconds
2810
+ } : null;
2811
+ this.#show(move ? this.#move.at(0) : scene);
2812
+ }
2813
+ /** Calls `f` whenever the frame changes; returns a function that stops it. */
2814
+ subscribe = (f) => {
2815
+ this.#listeners.add(f);
2816
+ return () => this.#listeners.delete(f);
2817
+ };
2818
+ #show(frame) {
2819
+ this.frame = frame;
2820
+ this.frameId++;
2821
+ for (const f of this.#listeners) f();
2822
+ }
2823
+ /** Starts the sim over from empty queues, with this seed (default: the original one), and ends a move. */
2824
+ reset(seed) {
2825
+ this.sim = createSim(this.model, this.ev, {
2826
+ ...this.#o,
2827
+ seed: seed ?? this.#o.seed
2828
+ });
2829
+ this.#paths.clear();
2830
+ this.#clock = 0;
2831
+ if (this.#move && this.scene) {
2832
+ this.#move = null;
2833
+ this.#show(this.scene);
2834
+ }
2835
+ }
2836
+ bind(svg, canvas) {
2837
+ const fresh = canvas !== this.canvas;
2838
+ this.svg = svg;
2839
+ this.canvas = canvas;
2840
+ this.#slots = [];
2841
+ if (!svg) return;
2842
+ for (const el of svg.querySelectorAll("rect[data-slot]")) this.#slots.push({
2843
+ el,
2844
+ stage: el.dataset.stage,
2845
+ index: Number(el.dataset.slot),
2846
+ y: Number(el.dataset.y),
2847
+ s: Number(el.dataset.s)
2848
+ });
2849
+ if (fresh) this.resize();
2850
+ this.drawFills();
2851
+ this.applyCamera();
2852
+ }
2853
+ /** Reads the theme tokens from the element that carries them. Call again when the theme changes. */
2854
+ readColors(root) {
2855
+ const cs = getComputedStyle(root);
2856
+ for (const t of TOKENS) this.colors[t] = cs.getPropertyValue(`--lm-${t}`).trim();
2857
+ }
2858
+ flowColor(flow) {
2859
+ const c = this.view.def.flows[flow]?.color ?? "accent";
2860
+ return this.colors[c] || c;
2861
+ }
2862
+ outcomeColor(outcome) {
2863
+ if (outcome === "dropped" || outcome === "rejected") return this.colors.drop || "#b7392e";
2864
+ if (outcome === "superseded" || outcome === "unread") return this.colors.muted || "#5d6d7c";
2865
+ return this.colors.ok || "#2a7f5a";
2866
+ }
2867
+ resize() {
2868
+ const c = this.canvas;
2869
+ if (!c || !this.scene) return;
2870
+ const r = c.getBoundingClientRect();
2871
+ if (!r.width) return;
2872
+ const dpr = Math.min(2, globalThis.devicePixelRatio || 1);
2873
+ const w = Math.round(r.width * dpr);
2874
+ const h = Math.round(r.height * dpr);
2875
+ if (c.width === w && c.height === h) return;
2876
+ c.width = w;
2877
+ c.height = h;
2878
+ this.draw();
2879
+ }
2880
+ /** Advances the sim, the move to a new structure and the story played, by `dtReal` seconds. */
2881
+ step(dtReal, o = {}) {
2882
+ this.#driven = this.paused;
2883
+ this.sim.step(dtReal, o);
2884
+ if (dtReal > 0) this.#clock += dtReal;
2885
+ const m = this.#move;
2886
+ if (m && dtReal > 0) {
2887
+ m.t += dtReal / m.seconds;
2888
+ if (m.t >= 1) this.#move = null;
2889
+ this.#show(m.at(m.t));
2890
+ }
2891
+ if (this.#story) this.#direct(dtReal);
2892
+ }
2893
+ /** The story plays: from the whole diagram, step `from` and the ones after it. */
2894
+ get playing() {
2895
+ return !!this.#story && this.#story.shot !== "back";
2896
+ }
2897
+ /**
2898
+ * Plays the story from step `from` on the engine's clock: the whole diagram, then for each step a flight in to what it
2899
+ * changes, the change, a flight out and the whole diagram for its seconds. The host shows each step's values. False
2900
+ * when it cannot: nothing is drawn yet, or there is no such step.
2901
+ */
2902
+ playStory(from) {
2903
+ if (!this.frame || !this.model.story[from]) return false;
2904
+ this.#story = {
2905
+ i: from - 1,
2906
+ shot: "establish",
2907
+ t: 0,
2908
+ from: whole(this.frame),
2909
+ close: whole(this.frame),
2910
+ zoom: false,
2911
+ targets: [],
2912
+ components: [],
2913
+ before: this.ev,
2914
+ waiting: false
2915
+ };
2916
+ this.#setCamera(null);
2917
+ this.host?.playing(true);
2918
+ return true;
2919
+ }
2920
+ /** Stops the story: the camera flies back to the whole diagram (cuts with `cut`), and the step shown stays. */
2921
+ stopStory(o = {}) {
2922
+ const s = this.#story;
2923
+ if (!s) return;
2924
+ this.cue = null;
2925
+ this.host?.cue(null);
2926
+ if (s.shot !== "back") this.host?.playing(false);
2927
+ if (o.cut || !this.camera || this.reducedMotion) {
2928
+ this.#story = null;
2929
+ this.#setCamera(null);
2930
+ } else this.#story = {
2931
+ ...s,
2932
+ shot: "back",
2933
+ t: 0,
2934
+ from: this.camera
2935
+ };
2936
+ }
2937
+ /** The page has drawn the values and the structure the engine has: a step's change can run. */
2938
+ #caughtUp() {
2939
+ return !!this.scene && this.scene.key === this.wantKey && this.drawnValues === JSON.stringify(this.ev.values);
2940
+ }
2941
+ #length(s) {
2942
+ if (s.shot === "change") return changeSeconds(this.transition);
2943
+ if (s.shot === "wide") return this.model.story[s.i]?.seconds ?? 0;
2944
+ return SHOTS[s.shot];
2945
+ }
2946
+ /** For tests and recordings: the shot the story is at. */
2947
+ get story() {
2948
+ const s = this.#story;
2949
+ return s && {
2950
+ i: s.i,
2951
+ shot: s.shot,
2952
+ t: s.t
2953
+ };
2954
+ }
2955
+ #direct(dt) {
2956
+ const s = this.#story;
2957
+ const frame = this.frame;
2958
+ if (!frame) return;
2959
+ if (s.waiting) {
2960
+ if (!this.#caughtUp()) return;
2961
+ s.waiting = false;
2962
+ }
2963
+ s.t += dt;
2964
+ while (this.#story === s && s.t >= this.#length(s) && !s.waiting) {
2965
+ s.t -= this.#length(s);
2966
+ this.#next(s);
2967
+ }
2968
+ if (this.#story !== s) return;
2969
+ const p = this.#length(s) > 0 ? s.t / this.#length(s) : 1;
2970
+ const cut = this.reducedMotion;
2971
+ const all = whole(frame);
2972
+ let cam;
2973
+ if (s.shot === "in") cam = cut ? s.close : between(all, s.close, p);
2974
+ else if (s.shot === "close") cam = s.close;
2975
+ else if (s.shot === "change") cam = s.zoom ? framing(frame, s.targets, { hold: true }) : all;
2976
+ else if (s.shot === "out" || s.shot === "back") cam = cut ? all : between(s.from, all, p);
2977
+ else cam = all;
2978
+ this.#setCamera(cam);
2979
+ }
2980
+ /** The shot after `s.shot`. */
2981
+ #next(s) {
2982
+ const frame = this.frame;
2983
+ const story = this.model.story;
2984
+ if (s.shot === "back") {
2985
+ this.#story = null;
2986
+ this.#setCamera(null);
2987
+ return;
2988
+ }
2989
+ if (s.shot === "establish" || s.shot === "wide") {
2990
+ if (s.i + 1 >= story.length) {
2991
+ this.#story = null;
2992
+ this.#setCamera(null);
2993
+ this.cue = null;
2994
+ this.host?.cue(null);
2995
+ this.host?.playing(false);
2996
+ return;
2997
+ }
2998
+ const i = s.i + 1;
2999
+ const st = story[i];
3000
+ const after = this.model.evaluate(st.values);
3001
+ const host = this.host;
3002
+ const ids = host ? targets(frame, this.ev, after, {
3003
+ a: host.shapes(this.ev),
3004
+ b: host.shapes(after)
3005
+ }, st.focus) : [];
3006
+ const nodes = frame.nodes.filter((n) => ids.includes(n.id));
3007
+ const components = [...new Set(nodes.map((n) => boxComponent(after, n)).filter((c) => c != null))];
3008
+ const close = framing(frame, ids);
3009
+ const zoom = close.w < frame.width - 1e-6;
3010
+ Object.assign(s, {
3011
+ i,
3012
+ shot: "in",
3013
+ from: whole(frame),
3014
+ close,
3015
+ zoom,
3016
+ targets: ids,
3017
+ components,
3018
+ before: this.ev
3019
+ });
3020
+ this.#cue({
3021
+ step: i,
3022
+ title: stepTitle(this.model, this.ev.values, st, i),
3023
+ detail: stepDetail(this.ev, null, components),
3024
+ after: false,
3025
+ top: close.y + close.h / 2 > frame.height * .55
3026
+ });
3027
+ return;
3028
+ }
3029
+ if (s.shot === "in") s.shot = "close";
3030
+ else if (s.shot === "close") {
3031
+ s.shot = "change";
3032
+ s.waiting = true;
3033
+ this.host?.show(s.i);
3034
+ this.#cue({
3035
+ ...this.cue,
3036
+ detail: stepDetail(s.before, this.ev, s.components),
3037
+ after: true
3038
+ });
3039
+ } else if (s.shot === "change") {
3040
+ s.shot = "out";
3041
+ s.from = this.camera ?? whole(frame);
3042
+ } else if (s.shot === "out") s.shot = "wide";
3043
+ }
3044
+ #cue(c) {
3045
+ this.cue = c;
3046
+ this.host?.cue(c);
3047
+ }
3048
+ #setCamera(cam) {
3049
+ const f = this.frame;
3050
+ const all = f && cam && Math.abs(cam.x) < 1e-6 && Math.abs(cam.y) < 1e-6 && Math.abs(cam.w - f.width) < 1e-6;
3051
+ this.camera = !cam || all ? null : cam;
3052
+ this.applyCamera();
3053
+ }
3054
+ /** Points the SVG at the camera: React draws the whole scene's viewBox, the camera replaces it after each render. */
3055
+ applyCamera() {
3056
+ const f = this.frame;
3057
+ if (!this.svg || !f) return;
3058
+ const c = this.camera ?? whole(f);
3059
+ const box = `${c.x} ${c.y} ${c.w} ${c.h}`;
3060
+ if (this.svg.getAttribute("viewBox") !== box) this.svg.setAttribute("viewBox", box);
3061
+ }
3062
+ /** Draws the dots on the overlay canvas and the worker fills in the SVG. */
3063
+ draw(o = {}) {
3064
+ this.drawFills();
3065
+ const c = this.canvas;
3066
+ const ctx = c?.getContext("2d");
3067
+ if (!c || !ctx || !this.frame) return;
3068
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
3069
+ ctx.clearRect(0, 0, c.width, c.height);
3070
+ if (o.particles === false) return;
3071
+ this.paintParticles(ctx, c.width / this.frame.width);
3072
+ }
3073
+ drawFills() {
3074
+ const first = this.ev.firstLimit;
3075
+ const breathe = !this.reducedMotion && (this.playing || first?.state === "warn" || first?.state === "over");
3076
+ const b = breathe ? .5 - .5 * Math.cos(2 * Math.PI * this.#clock / BREATH) : .5;
3077
+ for (const el of this.svg?.querySelectorAll("g[data-halo]") ?? []) {
3078
+ const [cx, cy] = [Number(el.dataset.cx), Number(el.dataset.cy)];
3079
+ const k = 1 + .035 * b;
3080
+ set(el, "transform", breathe ? `translate(${cx} ${cy}) scale(${k.toFixed(4)}) translate(${-cx} ${-cy})` : "");
3081
+ const glow = el.querySelector("[data-glow]");
3082
+ if (glow) set(glow, "stroke-opacity", (.1 + .25 * b).toFixed(3));
3083
+ }
3084
+ for (const sl of this.#slots) {
3085
+ const b = this.sim.slotBusy(sl.stage, sl.index);
3086
+ const h = b < .02 ? 0 : (sl.s - 2) * b;
3087
+ sl.el.setAttribute("y", (sl.y + sl.s - 1 - h).toFixed(2));
3088
+ sl.el.setAttribute("height", h.toFixed(2));
3089
+ }
3090
+ }
3091
+ /** Every dot as it is drawn now, in scene units: for the canvas, and for an SVG export. */
3092
+ dots() {
3093
+ const scene = this.frame;
3094
+ if (!scene) return [];
3095
+ const out = [];
3096
+ const live = /* @__PURE__ */ new Set();
3097
+ for (const d of this.sim.particles) {
3098
+ live.add(d.id);
3099
+ const [x, y] = this.#position(scene, d);
3100
+ const inCell = d.to.cell != null && d.phase !== "move";
3101
+ const done = d.outcome === "delivered" || d.outcome === "answered";
3102
+ out.push({
3103
+ x,
3104
+ y: y - (d.phase === "fade" && !done ? d.t / d.dur * 8 : 0),
3105
+ r: inCell ? 3 : 3.4,
3106
+ color: d.phase === "fade" ? this.outcomeColor(d.outcome) : this.flowColor(d.flow),
3107
+ alpha: d.phase === "fade" ? Math.max(0, 1 - d.t / d.dur) : 1,
3108
+ ...d.attempt ? { ring: RING } : {}
3109
+ });
3110
+ }
3111
+ for (const id of this.#paths.keys()) if (!live.has(id)) this.#paths.delete(id);
3112
+ return out;
3113
+ }
3114
+ /**
3115
+ * Paints the dots onto any 2D context, scene units × `scale`: the overlay, or an export frame. Under the camera they
3116
+ * go where the SVG shows their places (its viewBox, centred where its shape differs), so they keep matching the bars.
3117
+ */
3118
+ paintParticles(ctx, scale) {
3119
+ const f = this.frame;
3120
+ if (!f) return;
3121
+ const c = this.camera ?? whole(f);
3122
+ const [bw, bh] = [f.width * scale, f.height * scale];
3123
+ const k = Math.min(bw / c.w, bh / c.h);
3124
+ ctx.save();
3125
+ ctx.transform(k, 0, 0, k, (bw - c.w * k) / 2 - c.x * k, (bh - c.h * k) / 2 - c.y * k);
3126
+ for (const d of this.dots()) {
3127
+ ctx.globalAlpha = d.alpha;
3128
+ ctx.beginPath();
3129
+ if (d.ring) {
3130
+ ctx.strokeStyle = d.color;
3131
+ ctx.lineWidth = d.ring;
3132
+ ctx.arc(d.x, d.y, d.r - d.ring / 2, 0, Math.PI * 2);
3133
+ ctx.stroke();
3134
+ } else {
3135
+ ctx.fillStyle = d.color;
3136
+ ctx.arc(d.x, d.y, d.r, 0, Math.PI * 2);
3137
+ ctx.fill();
3138
+ }
3139
+ }
3140
+ ctx.restore();
3141
+ }
3142
+ #position(scene, d) {
3143
+ if (d.phase !== "move") return anchor(scene, d.to, d.flow);
3144
+ const key = `${d.leg}|${d.from.stage}|${d.from.cell}|${d.to.stage}|${d.to.cell}`;
3145
+ if (this.#move) {
3146
+ const legs = this.#legs;
3147
+ if (legs.frame !== this.frameId) {
3148
+ legs.frame = this.frameId;
3149
+ legs.paths.clear();
3150
+ }
3151
+ const leg = `${d.flow}|${key}`;
3152
+ let points = legs.paths.get(leg);
3153
+ if (!points) {
3154
+ points = legPath(scene, d.from, d.to, d.flow);
3155
+ legs.paths.set(leg, points);
3156
+ }
3157
+ return pointAt(points, d.t / d.dur);
3158
+ }
3159
+ let p = this.#paths.get(d.id);
3160
+ if (!p || p.key !== key) {
3161
+ p = {
3162
+ key,
3163
+ points: legPath(scene, d.from, d.to, d.flow)
3164
+ };
3165
+ this.#paths.set(d.id, p);
3166
+ }
3167
+ return pointAt(p.points, d.t / d.dur);
3168
+ }
3169
+ };
3170
+ // src/useLoadmap.ts
3171
+ /** The state behind a loadmap: values, the model's evaluation, the layout and the engine. */
3172
+ function useLoadmap(model, view, o = {}) {
3173
+ const init = () => ({
3174
+ ...model.defaults(),
3175
+ ...o.initial
3176
+ });
3177
+ const [state, setState] = useState(() => ({
3178
+ model,
3179
+ values: init()
3180
+ }));
3181
+ const evaluated = useRef(null);
3182
+ let values = state.values;
3183
+ if (state.model !== model) {
3184
+ values = init();
3185
+ evaluated.current = null;
3186
+ setState({
3187
+ model,
3188
+ values
3189
+ });
3190
+ }
3191
+ const fresh = !evaluated.current || evaluated.current.values === values;
3192
+ const ev = useMemo(() => evaluated.current?.values === values ? evaluated.current.ev : model.evaluate(values), [model, values]);
3193
+ const engineRef = useRef(null);
3194
+ if (!engineRef.current || engineRef.current.model !== model || engineRef.current.view !== view) engineRef.current = new Engine(model, view, ev, o);
3195
+ const engine = engineRef.current;
3196
+ engine.transition = o.transition ?? .8;
3197
+ const [root, setRoot] = useState(null);
3198
+ const wide = o.direction ?? "RIGHT";
3199
+ const [direction, setDirection] = useState(wide);
3200
+ const [measure, setMeasure] = useState(null);
3201
+ const [laid, setLaid] = useState(null);
3202
+ const scene = laid?.view === view ? laid.scene : null;
3203
+ const reducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
3204
+ engine.reducedMotion = reducedMotion;
3205
+ const narrowBelow = o.narrowBelow ?? 640;
3206
+ useEffect(() => {
3207
+ if (!evaluated.current || evaluated.current.values === values) engine.setEvaluation(ev);
3208
+ }, [
3209
+ engine,
3210
+ ev,
3211
+ values
3212
+ ]);
3213
+ useEffect(() => {
3214
+ if (!root) return;
3215
+ setMeasure(() => canvasMeasure(getComputedStyle(root).fontFamily));
3216
+ const ro = new ResizeObserver(([e]) => {
3217
+ const w = e?.contentRect.width ?? root.clientWidth;
3218
+ setDirection(w > 0 && w < narrowBelow ? "DOWN" : wide);
3219
+ });
3220
+ ro.observe(root);
3221
+ return () => ro.disconnect();
3222
+ }, [
3223
+ root,
3224
+ narrowBelow,
3225
+ wide
3226
+ ]);
3227
+ const key = useMemo(() => measure ? structureKey(view, ev, {
3228
+ direction,
3229
+ measure
3230
+ }) : "", [
3231
+ view,
3232
+ ev,
3233
+ direction,
3234
+ measure
3235
+ ]);
3236
+ if (fresh) engine.wantKey = key;
3237
+ const elk = o.elk;
3238
+ useEffect(() => {
3239
+ if (!measure || !key) return;
3240
+ let live = true;
3241
+ layout(view, engine.ev, {
3242
+ direction,
3243
+ measure,
3244
+ elk: elk ?? pageElk()
3245
+ }).then((s) => {
3246
+ if (live) setLaid({
3247
+ view,
3248
+ scene: s
3249
+ });
3250
+ }, (err) => console.error("loadmap: layout failed", err));
3251
+ return () => {
3252
+ live = false;
3253
+ };
3254
+ }, [
3255
+ key,
3256
+ view,
3257
+ engine,
3258
+ direction,
3259
+ measure,
3260
+ elk
3261
+ ]);
3262
+ const labels = useMemo(() => labelsAt(view, ev), [view, ev]);
3263
+ const valuesRef = useRef(values);
3264
+ if (fresh) valuesRef.current = values;
3265
+ const apply = useCallback((v) => {
3266
+ const next = {
3267
+ ...valuesRef.current,
3268
+ ...v
3269
+ };
3270
+ valuesRef.current = next;
3271
+ const nextEv = model.evaluate(next);
3272
+ evaluated.current = {
3273
+ values: next,
3274
+ ev: nextEv
3275
+ };
3276
+ engine.setEvaluation(nextEv);
3277
+ setState({
3278
+ model,
3279
+ values: next
3280
+ });
3281
+ }, [engine, model]);
3282
+ const [played, setPlayed] = useState({
3283
+ engine,
3284
+ on: false,
3285
+ cue: null
3286
+ });
3287
+ const playing = played.engine === engine && played.on;
3288
+ const cue = played.engine === engine ? played.cue : null;
3289
+ const stop = useCallback(() => engine.stopStory(), [engine]);
3290
+ const setValues = useCallback((v) => {
3291
+ stop();
3292
+ apply(v);
3293
+ }, [stop, apply]);
3294
+ const scenario = useMemo(() => model.scenarioOf(values), [model, values]);
3295
+ const setScenario = useCallback((label) => {
3296
+ const s = model.scenarios.find((x) => x.label === label);
3297
+ if (s) setValues(s.values);
3298
+ }, [model, setValues]);
3299
+ const [stepState, setStepState] = useState({
3300
+ model,
3301
+ i: null
3302
+ });
3303
+ const step = stepState.model === model && stepState.i != null && stepState.i < model.story.length ? stepState.i : null;
3304
+ const show = useCallback((i) => {
3305
+ const st = i == null ? void 0 : model.story[i];
3306
+ if (st) apply(st.values);
3307
+ engine.wantFocus = st?.focus ?? null;
3308
+ engine.storyStep = st ? i : null;
3309
+ setStepState({
3310
+ model,
3311
+ i: st ? i : null
3312
+ });
3313
+ }, [
3314
+ model,
3315
+ apply,
3316
+ engine
3317
+ ]);
3318
+ const setStep = useCallback((i) => {
3319
+ stop();
3320
+ show(i);
3321
+ }, [stop, show]);
3322
+ const shown = step == null ? void 0 : model.story[step];
3323
+ const stepChanged = !!shown && Object.entries(shown.values).some(([k, v]) => values[k] !== v);
3324
+ const focus = shown && !stepChanged ? shown.focus ?? null : null;
3325
+ engine.wantFocus = focus;
3326
+ engine.storyStep = step;
3327
+ const measureRef = useRef(measure);
3328
+ measureRef.current = measure;
3329
+ engine.host = {
3330
+ playing: (on) => setPlayed((p) => ({
3331
+ engine,
3332
+ on,
3333
+ cue: on && p.engine === engine ? p.cue : null
3334
+ })),
3335
+ show,
3336
+ cue: (c) => setPlayed((p) => ({
3337
+ engine,
3338
+ on: p.engine === engine && p.on,
3339
+ cue: c
3340
+ })),
3341
+ shapes: (e) => shapesOf(view, e, {
3342
+ direction,
3343
+ measure: measureRef.current ?? void 0
3344
+ })
3345
+ };
3346
+ useEffect(() => {
3347
+ if (playing && stepChanged) stop();
3348
+ }, [
3349
+ playing,
3350
+ stepChanged,
3351
+ stop
3352
+ ]);
3353
+ const storyPlaying = playing && model.story.length > 0;
3354
+ const setStoryPlaying = useCallback((on) => {
3355
+ if (!on) return stop();
3356
+ const last = model.story.length - 1;
3357
+ if (last < 0) return;
3358
+ const from = step == null || step === last ? 0 : stepChanged ? step : step + 1;
3359
+ if (stepChanged) show(null);
3360
+ engine.playStory(from);
3361
+ if (!document.fullscreenElement && !root?.hasAttribute("data-full")) root?.querySelector(".lm-board")?.scrollIntoView({ block: "nearest" });
3362
+ }, [
3363
+ step,
3364
+ stepChanged,
3365
+ model,
3366
+ engine,
3367
+ stop,
3368
+ show,
3369
+ root
3370
+ ]);
3371
+ const [screen, setScreen] = useState(false);
3372
+ const [overlay, setOverlay] = useState(false);
3373
+ const fullScreen = screen || overlay;
3374
+ useEffect(() => {
3375
+ const f = () => setScreen(!!root && document.fullscreenElement === root);
3376
+ document.addEventListener("fullscreenchange", f);
3377
+ return () => document.removeEventListener("fullscreenchange", f);
3378
+ }, [root]);
3379
+ const start = o.fullScreenMode ?? "panels";
3380
+ const [modeState, setModeState] = useState({
3381
+ start,
3382
+ mode: start
3383
+ });
3384
+ const fullScreenMode = modeState.start === start ? modeState.mode : start;
3385
+ const setFullScreenMode = useCallback((mode) => setModeState({
3386
+ start,
3387
+ mode
3388
+ }), [start]);
3389
+ useEffect(() => {
3390
+ if (!root || !fullScreen) return;
3391
+ root.setAttribute("data-full", overlay ? "overlay" : "screen");
3392
+ const top = overlay && typeof root.showPopover === "function";
3393
+ if (top) {
3394
+ root.popover = "manual";
3395
+ root.showPopover();
3396
+ }
3397
+ return () => {
3398
+ root.removeAttribute("data-full");
3399
+ if (top) {
3400
+ root.hidePopover();
3401
+ root.removeAttribute("popover");
3402
+ }
3403
+ };
3404
+ }, [
3405
+ root,
3406
+ fullScreen,
3407
+ overlay
3408
+ ]);
3409
+ useEffect(() => {
3410
+ if (!root || !fullScreen) return;
3411
+ root.setAttribute("data-mode", fullScreenMode);
3412
+ return () => root.removeAttribute("data-mode");
3413
+ }, [
3414
+ root,
3415
+ fullScreen,
3416
+ fullScreenMode
3417
+ ]);
3418
+ useEffect(() => {
3419
+ if (!overlay) return;
3420
+ const f = (e) => e.key === "Escape" && setOverlay(false);
3421
+ document.addEventListener("keydown", f);
3422
+ return () => document.removeEventListener("keydown", f);
3423
+ }, [overlay]);
3424
+ const toggleFullScreen = useCallback(() => {
3425
+ if (!root) return;
3426
+ if (overlay) setOverlay(false);
3427
+ else if (document.fullscreenElement) document.exitFullscreen().catch(() => {});
3428
+ else if (root.requestFullscreen) root.requestFullscreen().catch(() => setOverlay(true));
3429
+ else setOverlay(true);
3430
+ }, [root, overlay]);
3431
+ return {
3432
+ model,
3433
+ view,
3434
+ values,
3435
+ setValues,
3436
+ scenario,
3437
+ setScenario,
3438
+ step,
3439
+ stepChanged,
3440
+ setStep,
3441
+ focus,
3442
+ storyPlaying,
3443
+ setStoryPlaying,
3444
+ cue: storyPlaying ? cue : null,
3445
+ fullScreen,
3446
+ toggleFullScreen,
3447
+ fullScreenMode,
3448
+ setFullScreenMode,
3449
+ ev,
3450
+ scene,
3451
+ labels,
3452
+ direction,
3453
+ reducedMotion,
3454
+ engine,
3455
+ rootRef: setRoot,
3456
+ root
3457
+ };
3458
+ }
3459
+ function useMediaQuery(q) {
3460
+ const [on, setOn] = useState(() => typeof matchMedia === "function" && matchMedia(q).matches);
3461
+ useEffect(() => {
3462
+ if (typeof matchMedia !== "function") return;
3463
+ const m = matchMedia(q);
3464
+ const f = () => setOn(m.matches);
3465
+ f();
3466
+ m.addEventListener("change", f);
3467
+ return () => m.removeEventListener("change", f);
3468
+ }, [q]);
3469
+ return on;
3470
+ }
3471
+ function canvasMeasure(fontFamily) {
3472
+ const ctx = document.createElement("canvas").getContext("2d");
3473
+ if (!ctx) return (t, size) => t.length * size * .6;
3474
+ return (text, size, weight = 400) => {
3475
+ ctx.font = `${weight} ${size}px ${fontFamily}`;
3476
+ return Math.ceil(ctx.measureText(text).width);
3477
+ };
3478
+ }
3479
+ // src/Loadmap.tsx
3480
+ /** What the page's own switch says, on `<html>`: `data-theme`, or a `dark` or `light` class; null when it says nothing. */
3481
+ function pageTheme() {
3482
+ if (typeof document === "undefined") return null;
3483
+ const html = document.documentElement;
3484
+ const t = html.dataset.theme;
3485
+ if (t === "dark" || t === "light") return t;
3486
+ if (html.classList.contains("dark")) return "dark";
3487
+ if (html.classList.contains("light")) return "light";
3488
+ return null;
3489
+ }
3490
+ const following = /* @__PURE__ */ new Set();
3491
+ let observer = null;
3492
+ function follow(changed) {
3493
+ following.add(changed);
3494
+ if (!observer && typeof MutationObserver !== "undefined") {
3495
+ observer = new MutationObserver(() => {
3496
+ for (const f of following) f();
3497
+ });
3498
+ observer.observe(document.documentElement, {
3499
+ attributes: true,
3500
+ attributeFilter: ["data-theme", "class"]
3501
+ });
3502
+ }
3503
+ return () => {
3504
+ following.delete(changed);
3505
+ if (following.size) return;
3506
+ observer?.disconnect();
3507
+ observer = null;
3508
+ };
3509
+ }
3510
+ const stay = () => () => {};
3511
+ /**
3512
+ * The theme to draw: `theme` itself; with `inherit`, what the page's own switch says, followed as it changes, and the
3513
+ * system's (`auto`) while it says nothing, as on the server.
3514
+ */
3515
+ function usePageTheme(theme = "auto") {
3516
+ const page = useSyncExternalStore(theme === "inherit" ? follow : stay, pageTheme, () => null);
3517
+ return theme === "inherit" ? page ?? "auto" : theme;
3518
+ }
3519
+ /** The root element: theme tokens, styles, and the size the layout direction follows. */
3520
+ function LoadmapRoot({ lm, theme = "auto", children }) {
3521
+ useEffect(() => injectStyles(), []);
3522
+ const shown = usePageTheme(theme);
3523
+ useEffect(() => {
3524
+ if (!lm.root) return;
3525
+ lm.engine.readColors(lm.root);
3526
+ const m = matchMedia("(prefers-color-scheme: dark)");
3527
+ const f = () => lm.root && lm.engine.readColors(lm.root);
3528
+ m.addEventListener("change", f);
3529
+ return () => m.removeEventListener("change", f);
3530
+ }, [
3531
+ lm.root,
3532
+ lm.engine,
3533
+ shown
3534
+ ]);
3535
+ return /* @__PURE__ */ jsx("div", {
3536
+ className: "lm",
3537
+ "data-theme": shown === "auto" ? void 0 : shown,
3538
+ ref: lm.rootRef,
3539
+ children
3540
+ });
3541
+ }
3542
+ /** The panels full screen shows with the diagram, compact: the verdict and the assumptions in a line under it. */
3543
+ const LOADMAP_PANELS = [
3544
+ "verdict",
3545
+ "live",
3546
+ "limits",
3547
+ "controls",
3548
+ "headroom",
3549
+ "compare",
3550
+ "assumptions"
3551
+ ];
3552
+ /** The whole page piece: scenarios, diagram, verdict, headroom, live meters, limits, controls and assumptions. */
3553
+ function Loadmap({ model, view, theme, title, assumptions, headroom = true, compare = true, fullScreen = LOADMAP_PANELS, onNodeClick, selected, ref, ...o }) {
3554
+ const lm = useLoadmap(model, view, o);
3555
+ useImperativeHandle(ref, () => handleOf(lm), [lm]);
3556
+ const side = compare && model.scenarios.length > 1;
3557
+ const charts = [];
3558
+ if (headroom) charts.push("headroom");
3559
+ if (side) charts.push("compare");
3560
+ const out = (...panels) => panels.some((p) => fullScreen.includes(p)) ? void 0 : "";
3561
+ const listed = (p) => fullScreen.includes(p) && (p === "headroom" ? headroom : p !== "compare" || side);
3562
+ const full = lm.fullScreen;
3563
+ const focus = full && lm.fullScreenMode === "focus";
3564
+ const [drawer, setDrawer] = useState(null);
3565
+ if (drawer && !full) setDrawer(null);
3566
+ const close = useRef(null);
3567
+ useEffect(() => {
3568
+ if (drawer) close.current?.focus();
3569
+ }, [drawer]);
3570
+ const open = (p, from) => setDrawer({
3571
+ panel: p,
3572
+ from
3573
+ });
3574
+ const shut = () => {
3575
+ drawer?.from.focus();
3576
+ setDrawer(null);
3577
+ };
3578
+ useEffect(() => {
3579
+ if (!drawer) return;
3580
+ const f = (e) => {
3581
+ if (e.key !== "Escape") return;
3582
+ e.stopPropagation();
3583
+ drawer.from.focus();
3584
+ setDrawer(null);
3585
+ };
3586
+ document.addEventListener("keydown", f, true);
3587
+ return () => document.removeEventListener("keydown", f, true);
3588
+ }, [drawer]);
3589
+ const drawn = (...panels) => drawer && panels.includes(drawer.panel) ? "" : void 0;
3590
+ const panel = (id, children) => /* @__PURE__ */ jsx("div", {
3591
+ className: "lm-panel",
3592
+ "data-panel": id,
3593
+ "data-out": out(id),
3594
+ "data-drawn": drawn(id),
3595
+ children: (!full || drawer?.panel === id) && children
3596
+ });
3597
+ const heading = title !== false && /* @__PURE__ */ jsx("h2", { children: title ?? model.title });
3598
+ const verdict = listed("verdict");
3599
+ const line = focus ? verdict || listed("controls") : verdict || listed("assumptions");
3600
+ return /* @__PURE__ */ jsxs(LoadmapRoot, {
3601
+ lm,
3602
+ theme,
3603
+ children: [
3604
+ full ? /* @__PURE__ */ jsxs("div", {
3605
+ className: "lm-head",
3606
+ children: [heading, /* @__PURE__ */ jsx(Scenarios, { lm })]
3607
+ }) : /* @__PURE__ */ jsxs(Fragment, { children: [heading, /* @__PURE__ */ jsx(Scenarios, { lm })] }),
3608
+ /* @__PURE__ */ jsx(Story, { lm }),
3609
+ /* @__PURE__ */ jsx(Diagram, {
3610
+ lm,
3611
+ onNodeClick,
3612
+ selected
3613
+ }),
3614
+ full && line && /* @__PURE__ */ jsxs("div", {
3615
+ className: "lm-line",
3616
+ "data-tier": lm.ev.verdict.tier,
3617
+ children: [/* @__PURE__ */ jsx(VerdictLine, {
3618
+ lm,
3619
+ verdict,
3620
+ extra: assumptions?.length,
3621
+ open,
3622
+ assumptions: !focus && listed("assumptions")
3623
+ }), focus && listed("controls") && /* @__PURE__ */ jsx(LoadRange, { lm })]
3624
+ }),
3625
+ full && !focus && /* @__PURE__ */ jsx(Dock, {
3626
+ lm,
3627
+ panels: LOADMAP_PANELS.filter(listed),
3628
+ open
3629
+ }),
3630
+ /* @__PURE__ */ jsxs("div", {
3631
+ className: "lm-side lm-drawer",
3632
+ "data-out": out("verdict", "live", "limits", "controls", ...charts, "assumptions"),
3633
+ "data-drawer": drawer?.panel,
3634
+ ...drawer && {
3635
+ role: "dialog",
3636
+ "aria-label": "The whole panel"
3637
+ },
3638
+ children: [
3639
+ drawer && /* @__PURE__ */ jsx("div", {
3640
+ className: "lm-drawer-bar",
3641
+ "data-drawn": "",
3642
+ children: /* @__PURE__ */ jsx("button", {
3643
+ type: "button",
3644
+ className: "lm-btn",
3645
+ onClick: shut,
3646
+ ref: close,
3647
+ children: "✕ Back to full screen"
3648
+ })
3649
+ }),
3650
+ panel("verdict", /* @__PURE__ */ jsx(Verdict, { lm })),
3651
+ charts.length > 0 && /* @__PURE__ */ jsxs("div", {
3652
+ className: charts.length > 1 ? "lm-charts lm-strip" : "lm-charts",
3653
+ "data-out": out(...charts),
3654
+ "data-drawn": drawn(...charts),
3655
+ children: [headroom && panel("headroom", /* @__PURE__ */ jsx(HeadroomChart, { lm })), side && panel("compare", /* @__PURE__ */ jsx(Compare, { lm }))]
3656
+ }),
3657
+ /* @__PURE__ */ jsxs("div", {
3658
+ className: "lm-strip lm-live",
3659
+ "data-out": out("live", "limits", "controls"),
3660
+ "data-drawn": drawn("live", "limits", "controls"),
3661
+ children: [/* @__PURE__ */ jsxs("div", {
3662
+ className: "lm-card",
3663
+ "data-out": out("live", "limits"),
3664
+ "data-drawn": drawn("live", "limits"),
3665
+ children: [panel("live", /* @__PURE__ */ jsx(Meters, { lm })), panel("limits", /* @__PURE__ */ jsx(Limits, { lm }))]
3666
+ }), panel("controls", /* @__PURE__ */ jsx(Controls, { lm }))]
3667
+ }),
3668
+ panel("assumptions", /* @__PURE__ */ jsx(Assumptions, {
3669
+ lm,
3670
+ extra: assumptions
3671
+ }))
3672
+ ]
3673
+ })
3674
+ ]
3675
+ });
3676
+ }
3677
+ function handleOf(lm) {
3678
+ const { engine } = lm;
3679
+ return {
3680
+ engine,
3681
+ async ready(timeoutMs = 1e4) {
3682
+ const t0 = performance.now();
3683
+ const drawn = () => engine.scene && engine.scene.key === engine.wantKey && engine.svg && engine.drawnValues === JSON.stringify(engine.ev.values) && engine.drawnFocus === engine.wantFocus && engine.drawnFrame === engine.frameId;
3684
+ while (!drawn()) {
3685
+ if (performance.now() - t0 > timeoutMs) throw new Error("loadmap: layout not ready");
3686
+ await new Promise((r) => requestAnimationFrame(r));
3687
+ }
3688
+ },
3689
+ pause: () => {
3690
+ engine.paused = true;
3691
+ },
3692
+ resume: () => {
3693
+ engine.paused = false;
3694
+ },
3695
+ values: () => engine.ev.values,
3696
+ setValues: (v) => lm.setValues(v),
3697
+ setStoryStep: (i) => lm.setStep(i),
3698
+ storyStep: () => engine.storyStep,
3699
+ playStory: () => {
3700
+ if (!engine.playStory(0)) throw new Error("loadmap: the story cannot play: nothing is drawn yet, or there is none");
3701
+ return storySeconds(engine.model.story, engine.transition);
3702
+ },
3703
+ reset: (seed) => engine.reset(seed),
3704
+ step: (dt) => {
3705
+ engine.step(dt, { particles: true });
3706
+ engine.draw({ particles: true });
3707
+ },
3708
+ board: () => engine.svg && engine.canvas && engine.frame ? {
3709
+ svg: engine.svg,
3710
+ canvas: engine.canvas,
3711
+ scene: engine.frame
3712
+ } : null
3713
+ };
3714
+ }
3715
+ export { Compare as _, usePageTheme as a, scenarioColor as b, injectStyles as c, Controls as d, Limits as f, Diagram as g, workerElk as h, handleOf as i, Story as l, Verdict as m, Loadmap as n, useLoadmap as o, Meters as p, LoadmapRoot as r, LOADMAP_CSS as s, LOADMAP_PANELS as t, Assumptions as u, HeadroomChart as v, useComparison as x, Scenarios as y };