@loadmap/react 0.14.0 → 0.16.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.
@@ -1,7 +1,7 @@
1
- import { compare, headroom, reach } from "@loadmap/core";
1
+ import { compare, headroom } from "@loadmap/core";
2
2
  import { compact, fmt, monthOf, multiple, multiples, pct, secs } from "@loadmap/core/format";
3
3
  import { anchor, directionOf, labelsAt, layout, legPath, localElk, pointAt, structureKey } from "@loadmap/layout";
4
- import { memo, useCallback, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
4
+ import { Suspense, lazy, memo, useCallback, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
5
5
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
6
6
  import { morph, shapesOf } from "@loadmap/layout/internal";
7
7
  import { createSim } from "@loadmap/sim";
@@ -211,767 +211,226 @@ function stepDetail(a, b, components) {
211
211
  return now ? `${was.name} ${u(was.util)} → ${u(now.util)}` : `${was.name} ${u(was.util)}`;
212
212
  }).filter(Boolean).join(" · ");
213
213
  }
214
- // src/scenarios.tsx
215
- /** Scenario identity colours, in declaration order; a fifth and later scenario is drawn muted. */
216
- const SERIES = [
217
- "var(--lm-s1)",
218
- "var(--lm-s2)",
219
- "var(--lm-s3)",
220
- "var(--lm-s4)"
221
- ];
222
- /** The colour of a scenario by label; values of the reader's own are drawn in the text colour. */
223
- function scenarioColor(model, label) {
224
- if (label == null) return "var(--lm-fg)";
225
- const i = model.scenarios.findIndex((s) => s.label === label);
226
- return SERIES[i] ?? "var(--lm-muted)";
227
- }
228
- const lineName = (l) => l.label ?? "These values";
229
- /** A month for a table cell or an axis: "Mar 2031"; "now" for a crossing already reached. */
230
- function when(model, x) {
231
- const d = model.dateAt(x);
232
- return d ? monthOf(d, true) : x != null && x <= 1 && model.growth ? "now" : "";
233
- }
234
- /** The months of both edges: "Sep 2029–Feb 2030", or one month when they agree. */
235
- function whenRange(model, r) {
236
- if (!r) return "";
237
- const [lo, hi] = [when(model, r.low), when(model, r.high)];
238
- return !hi || lo === hi ? lo : `${lo}–${hi}`;
239
- }
240
- /** The comparison at the shown load: crossings do not depend on it, the verdicts do. */
241
- function useComparison(lm) {
242
- return useMemo(() => compare(lm.model, lm.values.load), [lm.model, lm.values.load]);
243
- }
244
- /** One button per scenario: a reader switches designs without touching the controls. The load stays. */
245
- function Scenarios({ lm }) {
246
- const { model } = lm;
247
- if (!model.scenarios.length) return null;
248
- return /* @__PURE__ */ jsxs("fieldset", {
249
- className: "lm-scenarios",
250
- children: [
251
- /* @__PURE__ */ jsx("legend", { children: "Scenario" }),
252
- model.scenarios.map((s) => /* @__PURE__ */ jsxs("button", {
253
- type: "button",
254
- "aria-pressed": lm.scenario?.label === s.label,
255
- onClick: () => lm.setScenario(s.label),
256
- children: [/* @__PURE__ */ jsx("i", { style: { background: scenarioColor(model, s.label) } }), s.label]
257
- }, s.label)),
258
- !lm.scenario && /* @__PURE__ */ jsx("span", {
259
- className: "lm-own",
260
- children: "your own values"
261
- })
262
- ]
263
- });
264
- }
265
- /** "+107 %" against the baseline; "same" within a rounding; nothing where either never runs out. */
266
- function change(x) {
267
- if (x == null || !Number.isFinite(x) || x === 0) return "";
268
- if (Math.abs(x - 1) < .005) return "same";
269
- return `${x > 1 ? "+" : "−"}${pct(Math.abs(x - 1))}`;
270
- }
271
- /** The scenarios side by side: which buys more headroom, where each first runs out, and per component. */
272
- function Compare({ lm, title = "Scenarios compared" }) {
273
- const { model } = lm;
274
- const c = useComparison(lm);
275
- if (c.rows.length < 2) return null;
276
- const target = `${pct(model.thresholds.target)} target`;
277
- 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) })] });
278
- return /* @__PURE__ */ jsxs("div", {
279
- className: "lm-card lm-compare",
280
- children: [
281
- /* @__PURE__ */ jsx("h3", { children: title }),
282
- /* @__PURE__ */ jsx("p", {
283
- className: "lm-compare-text",
284
- children: c.text
285
- }),
286
- /* @__PURE__ */ jsx("div", {
287
- className: "lm-table-wrap",
288
- children: /* @__PURE__ */ jsxs("table", {
289
- className: "lm-table",
290
- children: [/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [
291
- /* @__PURE__ */ jsx("th", {
292
- scope: "col",
293
- children: "Scenario"
294
- }),
295
- /* @__PURE__ */ jsx("th", {
296
- scope: "col",
297
- children: "Limited by"
298
- }),
299
- /* @__PURE__ */ jsx("th", {
300
- scope: "col",
301
- children: target
302
- }),
303
- /* @__PURE__ */ jsx("th", {
304
- scope: "col",
305
- children: "Runs out"
306
- })
307
- ] }) }), /* @__PURE__ */ jsx("tbody", { children: c.rows.map((r) => /* @__PURE__ */ jsxs("tr", {
308
- "data-scenario": r.label,
309
- "aria-current": lm.scenario?.label === r.label || void 0,
310
- children: [
311
- /* @__PURE__ */ jsxs("th", {
312
- scope: "row",
313
- children: [/* @__PURE__ */ jsx("i", { style: { background: scenarioColor(model, r.label) } }), r.label]
314
- }),
315
- /* @__PURE__ */ jsx("td", {
316
- className: "lm-text",
317
- children: r.firstLimit?.name ?? "—"
318
- }),
319
- /* @__PURE__ */ jsx("td", {
320
- "data-multiple": r.target ?? "",
321
- "data-high": r.targetRange?.high ?? "",
322
- children: at(r.targetRange)
323
- }),
324
- /* @__PURE__ */ jsx("td", {
325
- "data-multiple": r.full ?? "",
326
- "data-high": r.fullRange?.high ?? "",
327
- children: at(r.fullRange)
328
- })
329
- ]
330
- }, r.label)) })]
331
- })
332
- }),
333
- /* @__PURE__ */ jsxs("h3", { children: [target, ", by component"] }),
334
- /* @__PURE__ */ jsx("div", {
335
- className: "lm-table-wrap",
336
- children: /* @__PURE__ */ jsxs("table", {
337
- className: "lm-table",
338
- children: [/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [/* @__PURE__ */ jsx("th", {
339
- scope: "col",
340
- children: "Component"
341
- }), c.rows.map((r) => /* @__PURE__ */ jsx("th", {
342
- scope: "col",
343
- children: r.label
344
- }, r.label))] }) }), /* @__PURE__ */ jsx("tbody", { children: model.componentIds.map((id, k) => /* @__PURE__ */ jsxs("tr", {
345
- "data-component": id,
346
- children: [/* @__PURE__ */ jsx("th", {
347
- scope: "row",
348
- children: c.rows[0].components[k].name
349
- }), c.rows.map((r, i) => {
350
- const x = r.components[k];
351
- return /* @__PURE__ */ jsxs("td", {
352
- "data-multiple": x.target ?? "",
353
- children: [x.targetRange == null ? "off" : multiples(x.targetRange, model.searchMax, true), i > 0 && change(x.change) && /* @__PURE__ */ jsx("small", { children: change(x.change) })]
354
- }, r.label);
355
- })]
356
- }, id)) })]
357
- })
358
- })
359
- ]
214
+ // src/Diagram.tsx
215
+ const Detail = lazy(() => import("./later-ChRpEoLJ.js").then((m) => ({ default: m.Detail })));
216
+ const STATE_STROKE = {
217
+ off: "var(--lm-line)",
218
+ ok: "var(--lm-ok)",
219
+ warn: "var(--lm-warn)",
220
+ over: "var(--lm-drop)"
221
+ };
222
+ const tokenColor = (c) => [
223
+ "accent",
224
+ "alt",
225
+ "ok",
226
+ "warn",
227
+ "drop",
228
+ "muted"
229
+ ].includes(c) ? `var(--lm-${c})` : c;
230
+ function Diagram({ lm, legend = true, onNodeClick, selected = null, canvas = false }) {
231
+ const { scene, engine, reducedMotion } = lm;
232
+ const zoom = lm.zoom || !!canvas;
233
+ const inset = {
234
+ top: 0,
235
+ right: 0,
236
+ bottom: 0,
237
+ left: 0,
238
+ ...typeof canvas === "object" ? canvas : {}
239
+ };
240
+ const insetKey = `${inset.top} ${inset.right} ${inset.bottom} ${inset.left}`;
241
+ const click = useRef(onNodeClick);
242
+ click.current = onNodeClick;
243
+ const [onClick] = useState(() => (id) => click.current?.(id));
244
+ const svgRef = useRef(null);
245
+ const canvasRef = useRef(null);
246
+ const wrapRef = useRef(null);
247
+ const barRef = useRef(null);
248
+ const boardRef = useRef(null);
249
+ const buttonRef = useRef(null);
250
+ const titleRef = useRef(null);
251
+ const full = lm.fullScreen;
252
+ const [tip, setTip] = useState(null);
253
+ const detailId = useId();
254
+ useLayoutEffect(() => {
255
+ if (scene) engine.setScene(scene, { cut: reducedMotion });
256
+ }, [
257
+ engine,
258
+ scene,
259
+ reducedMotion
260
+ ]);
261
+ const frameId = useSyncExternalStore(engine.subscribe, () => engine.frameId);
262
+ const frame = engine.frame;
263
+ const hand = useSyncExternalStore(engine.subscribe, () => engine.handover);
264
+ useEffect(() => {
265
+ engine.bind(svgRef.current, canvasRef.current);
266
+ }, [
267
+ engine,
268
+ frame,
269
+ reducedMotion
270
+ ]);
271
+ useLayoutEffect(() => {
272
+ engine.applyCamera();
273
+ engine.drawHalos();
360
274
  });
361
- }
362
- /** The size of an element in CSS pixels, kept current: a chart draws at its own size so text stays legible. */
363
- function useSize(fallback) {
364
- const ref = useRef(null);
365
- const [size, setSize] = useState({
366
- width: fallback,
367
- height: 0
275
+ useEffect(() => {
276
+ if (lm.root) engine.readColors(lm.root);
277
+ }, [
278
+ engine,
279
+ scene,
280
+ lm.root
281
+ ]);
282
+ useEffect(() => {
283
+ engine.drawnValues = JSON.stringify(lm.values);
284
+ engine.drawnFocus = lm.focus;
285
+ engine.drawnFrame = frameId;
368
286
  });
369
287
  useEffect(() => {
370
- const el = ref.current;
371
- if (!el) return;
372
- const ro = new ResizeObserver(([e]) => {
373
- const width = Math.round(e?.contentRect.width ?? el.clientWidth);
374
- const height = Math.round(e?.contentRect.height ?? el.clientHeight);
375
- if (width > 0) setSize((s) => s.width === width && s.height === height ? s : {
376
- width,
377
- height
378
- });
379
- });
380
- ro.observe(el);
288
+ const board = boardRef.current;
289
+ if (!board) return;
290
+ const ro = new ResizeObserver(() => engine.resize());
291
+ ro.observe(board);
381
292
  return () => ro.disconnect();
382
- }, []);
383
- return [ref, size];
384
- }
385
- /** Every scenario's line over the load: it depends on every value but the load, which is only the marker. */
386
- function useHeadroom(lm) {
387
- const { model, values } = lm;
388
- const rest = JSON.stringify({
389
- ...values,
390
- load: null
293
+ }, [engine]);
294
+ const shape = useRef({
295
+ canvas: !!canvas,
296
+ inset
391
297
  });
392
- return useMemo(() => headroom(model, {
393
- ...values,
394
- load: model.load.default
395
- }), [model, rest]);
396
- }
397
- /**
398
- * The width of a label in the chart's 11 px monospace (`--lm-mono`), measured once the chart is on the page, so its
399
- * labels are kept inside it whatever the theme's font.
400
- */
401
- function useAxisMeasure(el) {
402
- const [measure, setMeasure] = useState(() => (text, _weight) => text.length * 6.7);
403
- useLayoutEffect(() => {
404
- const ctx = el.current && document.createElement("canvas").getContext("2d");
405
- if (!ctx) return;
406
- const font = getComputedStyle(el.current).getPropertyValue("--lm-mono").trim() || "monospace";
407
- setMeasure(() => (text, weight = 400) => {
408
- ctx.font = `${weight} 11px ${font}`;
409
- return ctx.measureText(text).width;
410
- });
411
- }, [el]);
412
- return measure;
413
- }
414
- /** 1, 2, 5, 10, 20, 50, … inside [from, to]; decades only when there is little room. */
415
- function ticks(from, to, roomy) {
416
- const out = [];
417
- for (let d = Math.floor(Math.log10(from)); d <= Math.ceil(Math.log10(to)); d++) for (const k of roomy ? [
418
- 1,
419
- 2,
420
- 5
421
- ] : [1]) {
422
- const v = k * 10 ** d;
423
- if (v >= from * .999 && v <= to * 1.001) out.push(Number(v.toPrecision(6)));
424
- }
425
- return out;
426
- }
427
- /**
428
- * Utilization over the load multiple. Each scenario's line is its highest utilization, so it crosses the target and
429
- * 100 % exactly where its first limit does; the dots are those crossings, taken from the limits, not from the line.
430
- * With a ± on a capacity, a band shows the line at every capacity's low and high bound, and a bracket on the target
431
- * and 100 % lines spans where the band crosses them. The shown scenario's components are the thin lines under it.
432
- * Hover or arrow keys read every line at one load.
433
- */
434
- function HeadroomChart({ lm, title = "Headroom" }) {
435
- const { model, values } = lm;
436
- const h = useHeadroom(lm);
437
- const [wrap, { width }] = useSize(640);
438
- const [hover, setHover] = useState(null);
439
- const clip = useId().replace(/:/g, "");
440
- const measure = useAxisMeasure(wrap);
441
- const tip = useRef(null);
442
- useLayoutEffect(() => {
443
- const el = tip.current;
444
- if (el && hover != null) el.style.left = `${Math.max(0, Math.min(lx(xs[hover]) + 10, W - el.offsetWidth))}px`;
445
- });
446
- const dated = !!model.growth;
447
- const m = {
448
- l: 44,
449
- r: 14,
450
- t: 14,
451
- b: dated ? 40 : 26
298
+ shape.current = {
299
+ canvas: !!canvas,
300
+ inset
452
301
  };
453
- const W = width;
454
- const H = Math.round(Math.min(300, Math.max(200, W * .45)));
455
- const pw = W - m.l - m.r;
456
- const ph = H - m.t - m.b;
457
- const top = Math.max(1.5, model.thresholds.full * 1.5);
458
- const lx = (x) => m.l + pw * Math.log(x / h.from) / Math.log(h.to / h.from);
459
- const ly = (u) => m.t + ph * (1 - Math.min(u, top * 1.2) / top);
460
- const path = (s) => {
461
- let d = "";
462
- let pen = false;
463
- for (const [x, u] of s) {
464
- if (u == null) {
465
- pen = false;
466
- continue;
467
- }
468
- d += `${pen ? "L" : "M"}${lx(x).toFixed(1)} ${ly(u).toFixed(1)}`;
469
- pen = true;
302
+ const zoomed = useRef(null);
303
+ useEffect(() => {
304
+ const board = boardRef.current;
305
+ if (!zoom || !board) return;
306
+ let gone = false;
307
+ import("./zoom-C_qebdpE.js").then(({ mountZoom }) => {
308
+ if (!gone) zoomed.current = mountZoom(board, engine, () => shape.current);
309
+ }).catch(() => {});
310
+ return () => {
311
+ gone = true;
312
+ zoomed.current?.off();
313
+ zoomed.current = null;
314
+ };
315
+ }, [
316
+ engine,
317
+ zoom,
318
+ !!canvas
319
+ ]);
320
+ useEffect(() => zoomed.current?.measure(), [insetKey]);
321
+ const follow = () => {
322
+ const wrap = wrapRef.current;
323
+ const board = boardRef.current;
324
+ const c = engine.camera;
325
+ const title = titleRef.current;
326
+ if (!c && !engine.cue) return;
327
+ if (!wrap || !board || !engine.frame || wrap.scrollHeight <= wrap.clientHeight) {
328
+ title?.style.removeProperty("top");
329
+ title?.style.removeProperty("bottom");
330
+ return;
331
+ }
332
+ const k = board.clientHeight / engine.frame.height;
333
+ const y = engine.viewer ? board.clientHeight / 2 : c && (c.y + c.h / 2) * k;
334
+ if (c && y != null) wrap.scrollTop = board.offsetTop + y - wrap.clientHeight / 2;
335
+ if (title) {
336
+ title.style.top = `${Math.max(0, wrap.scrollTop - board.offsetTop + (barRef.current?.offsetHeight ?? 0))}px`;
337
+ title.style.bottom = "auto";
470
338
  }
471
- return d;
472
- };
473
- const xs = h.lines[0]?.envelope.map(([x]) => x) ?? [];
474
- const selected = h.lines.find((l) => l.selected);
475
- const roomy = W >= 480;
476
- const tickList = ticks(h.from, h.to, roomy);
477
- const labelled = (x) => roomy || Number.isInteger(Math.log10(x));
478
- const near = (px) => {
479
- let best = 0;
480
- for (let i = 1; i < xs.length; i++) if (Math.abs(lx(xs[i]) - px) < Math.abs(lx(xs[best]) - px)) best = i;
481
- return best;
482
- };
483
- const onMove = (e) => {
484
- const r = e.currentTarget.ownerSVGElement.getBoundingClientRect();
485
- setHover(near(e.clientX - r.left));
486
- };
487
- const onKey = (e) => {
488
- const i = hover ?? near(lx(Math.min(h.to, Math.max(h.from, values.load))));
489
- if (e.key === "ArrowRight" || e.key === "ArrowLeft") {
490
- e.preventDefault();
491
- setHover(Math.max(0, Math.min(xs.length - 1, i + (e.key === "ArrowRight" ? 1 : -1))));
492
- } else if (e.key === "Escape") setHover(null);
493
339
  };
494
- const area = (b) => {
495
- const both = b.upper.flatMap(([x, u], i) => {
496
- const v = b.lower[i][1];
497
- return u == null || v == null ? [] : [[
498
- x,
499
- u,
500
- v
501
- ]];
340
+ useEffect(() => {
341
+ let raf = 0;
342
+ let last = 0;
343
+ const frame = (ts) => {
344
+ const dt = last ? Math.min(.05, (ts - last) / 1e3) : 0;
345
+ last = ts;
346
+ if (!engine.paused && engine.scene) {
347
+ engine.step(dt, { particles: !reducedMotion });
348
+ engine.draw({ particles: !reducedMotion });
349
+ follow();
350
+ }
351
+ raf = requestAnimationFrame(frame);
352
+ };
353
+ raf = requestAnimationFrame(frame);
354
+ return () => cancelAnimationFrame(raf);
355
+ }, [engine, reducedMotion]);
356
+ const was = useRef(false);
357
+ useEffect(() => {
358
+ if (was.current && !full) buttonRef.current?.focus();
359
+ was.current = full;
360
+ }, [full]);
361
+ useEffect(() => {
362
+ const wrap = wrapRef.current;
363
+ const bar = barRef.current;
364
+ const root = lm.root;
365
+ if (!full || !scene || !wrap || !bar || !root) return;
366
+ const px = (x) => Number.parseFloat(x) || 0;
367
+ const fit = () => {
368
+ const rs = getComputedStyle(root);
369
+ let around = px(rs.paddingTop) + px(rs.paddingBottom);
370
+ const add = (el) => {
371
+ const cs = getComputedStyle(el);
372
+ if (cs.display === "none" || cs.position === "absolute" || cs.position === "fixed") return;
373
+ around += px(rs.rowGap) + (px(cs.flexGrow) > 0 ? px(cs.minHeight) : el.offsetHeight);
374
+ };
375
+ for (const el of root.children) if (el !== wrap) add(el);
376
+ if (getComputedStyle(root, "::after").content !== "none") around += px(rs.rowGap);
377
+ const h = root.clientHeight - around - bar.offsetHeight - px(getComputedStyle(wrap).rowGap);
378
+ const w = Math.min(wrap.clientWidth, h * scene.width / scene.height);
379
+ wrap.style.setProperty("--lm-fit", `${Math.max(0, Math.floor(w))}px`);
380
+ };
381
+ const ro = new ResizeObserver(fit);
382
+ const watch = () => {
383
+ ro.disconnect();
384
+ ro.observe(bar);
385
+ ro.observe(root);
386
+ for (const el of root.children) ro.observe(el);
387
+ };
388
+ watch();
389
+ const mo = new MutationObserver(() => {
390
+ watch();
391
+ fit();
502
392
  });
503
- if (both.length < 2) return "";
504
- const up = both.map(([x, u]) => `${lx(x).toFixed(1)} ${ly(u).toFixed(1)}`);
505
- const down = both.map(([x, , v]) => `${lx(x).toFixed(1)} ${ly(v).toFixed(1)}`).reverse();
506
- return `M${up.join("L")}L${down.join("L")}Z`;
507
- };
508
- const reaches = (r, x) => r && l0(r) ? multiples(r, model.searchMax) : multiple(x, model.searchMax);
509
- const l0 = (r) => multiple(r.low, model.searchMax) !== multiple(r.high, model.searchMax);
510
- 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("; ");
511
- const loadX = lx(Math.min(h.to, Math.max(h.from, values.load)));
512
- const hx = hover == null ? null : xs[hover];
513
- const fromLeft = {
514
- x: 0,
515
- textAnchor: "start"
516
- };
517
- const fromRight = {
518
- x: W,
519
- textAnchor: "end"
520
- };
521
- /** A label beside a line at x: on the side it prefers if it fits, else the other, else against the nearer edge. */
522
- const beside = (x, w, prefer, gap = 4) => {
523
- const right = {
524
- x: x + gap,
525
- textAnchor: "start"
393
+ mo.observe(root, {
394
+ childList: true,
395
+ attributeFilter: ["data-mode"]
396
+ });
397
+ return () => {
398
+ ro.disconnect();
399
+ mo.disconnect();
400
+ wrap.style.removeProperty("--lm-fit");
526
401
  };
527
- const left = {
528
- x: x - gap,
529
- textAnchor: "end"
402
+ }, [
403
+ full,
404
+ scene,
405
+ lm.root
406
+ ]);
407
+ const { setFullScreenMode, fullScreenMode } = lm;
408
+ const modesRef = useRef(null);
409
+ useEffect(() => {
410
+ const root = lm.root;
411
+ if (!full || !root || lm.fill) return;
412
+ const f = (e) => {
413
+ if (e.key !== "f" && e.key !== "F" || e.ctrlKey || e.metaKey || e.altKey) return;
414
+ if (typing(e.composedPath()[0] ?? null) || root.querySelector(":scope > [data-drawer]")) return;
415
+ e.preventDefault();
416
+ if (e.repeat) return;
417
+ const next = fullScreenMode === "focus" ? "panels" : "focus";
418
+ if (document.activeElement?.closest(".lm-dock, .lm-line")) modesRef.current?.querySelector(`[data-mode="${next}"]`)?.focus();
419
+ setFullScreenMode(next);
530
420
  };
531
- const fitsRight = x + gap + w <= W;
532
- const fitsLeft = x - gap - w >= 0;
533
- if (prefer === "right" ? fitsRight : !fitsLeft && fitsRight) return right;
534
- if (fitsLeft) return left;
535
- return x < W / 2 ? fromLeft : fromRight;
536
- };
537
- /** A label centred on x, unless that passes an edge. */
538
- const centred = (x, w) => x - w / 2 < 0 ? fromLeft : x + w / 2 > W ? fromRight : {
539
- x,
540
- textAnchor: "middle"
541
- };
542
- const shown = `shown: ${fmt(values.load)}×`;
543
- /** A crossing's multiple, left of its dot where it fits. */
544
- const mark = (t, x, y) => /* @__PURE__ */ jsx("text", {
545
- ...beside(x, measure(t, 600), "left", 6),
546
- y,
547
- className: "lm-mark",
548
- children: t
549
- });
421
+ document.addEventListener("keydown", f);
422
+ return () => document.removeEventListener("keydown", f);
423
+ }, [
424
+ full,
425
+ fullScreenMode,
426
+ setFullScreenMode,
427
+ lm.root,
428
+ lm.fill
429
+ ]);
550
430
  return /* @__PURE__ */ jsxs("div", {
551
- className: "lm-card lm-headroom",
552
- children: [
553
- /* @__PURE__ */ jsx("h3", { children: title }),
554
- h.lines.length > 1 && /* @__PURE__ */ jsxs("div", {
555
- className: "lm-legend",
556
- children: [h.lines.map((l) => /* @__PURE__ */ jsxs("span", { children: [/* @__PURE__ */ jsx("b", {
557
- className: "lm-key",
558
- style: { background: scenarioColor(model, l.label) }
559
- }), lineName(l)] }, lineName(l))), selected && /* @__PURE__ */ jsxs("span", { children: ["thin lines: each component of ", lineName(selected)] })]
560
- }),
561
- /* @__PURE__ */ jsxs("div", {
562
- className: "lm-chart",
563
- ref: wrap,
564
- role: "slider",
565
- "aria-label": `Utilization over the load multiple. ${summary}.`,
566
- "aria-valuemin": h.from,
567
- "aria-valuemax": h.to,
568
- "aria-valuenow": hx ?? values.load,
569
- "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(", ")}`,
570
- tabIndex: 0,
571
- onKeyDown: onKey,
572
- onBlur: () => setHover(null),
573
- children: [/* @__PURE__ */ jsxs("svg", {
574
- width: W,
575
- height: H,
576
- viewBox: `0 0 ${W} ${H}`,
577
- "aria-hidden": "true",
578
- children: [
579
- /* @__PURE__ */ jsx("defs", { children: /* @__PURE__ */ jsx("clipPath", {
580
- id: clip,
581
- children: /* @__PURE__ */ jsx("rect", {
582
- x: m.l,
583
- y: m.t,
584
- width: pw,
585
- height: ph + 2
586
- })
587
- }) }),
588
- [
589
- 0,
590
- model.thresholds.target,
591
- model.thresholds.full
592
- ].map((u) => /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("line", {
593
- x1: m.l,
594
- x2: W - m.r,
595
- y1: ly(u),
596
- y2: ly(u),
597
- stroke: "var(--lm-line)"
598
- }), /* @__PURE__ */ jsx("text", {
599
- x: m.l - 6,
600
- y: ly(u) + 4,
601
- textAnchor: "end",
602
- className: "lm-axis",
603
- children: pct(u)
604
- })] }, u)),
605
- /* @__PURE__ */ jsx("text", {
606
- x: W - m.r,
607
- y: ly(model.thresholds.target) - 5,
608
- textAnchor: "end",
609
- className: "lm-axis",
610
- children: "target"
611
- }),
612
- tickList.map((x) => {
613
- const label = `${fmt(x)}×`;
614
- const date = dated && x > 1 ? when(model, x) : "";
615
- return /* @__PURE__ */ jsxs("g", {
616
- className: "lm-axis",
617
- children: [/* @__PURE__ */ jsx("line", {
618
- x1: lx(x),
619
- x2: lx(x),
620
- y1: m.t + ph,
621
- y2: m.t + ph + 4,
622
- stroke: "var(--lm-line)"
623
- }), labelled(x) && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("text", {
624
- ...centred(lx(x), measure(label)),
625
- y: m.t + ph + 16,
626
- children: label
627
- }), date && /* @__PURE__ */ jsx("text", {
628
- ...centred(lx(x), measure(date)),
629
- y: m.t + ph + 30,
630
- children: date
631
- })] })]
632
- }, x);
633
- }),
634
- /* @__PURE__ */ jsxs("g", {
635
- clipPath: `url(#${clip})`,
636
- children: [
637
- [...h.lines].sort((a, b) => Number(a.selected) - Number(b.selected)).map((l) => l.band ? /* @__PURE__ */ jsx("path", {
638
- "data-band": lineName(l),
639
- d: area(l.band),
640
- fill: scenarioColor(model, l.label),
641
- fillOpacity: l.selected ? .2 : .08
642
- }, lineName(l)) : null),
643
- selected?.components.map((c) => /* @__PURE__ */ jsx("path", {
644
- d: path(c.points),
645
- fill: "none",
646
- stroke: "var(--lm-muted)",
647
- strokeOpacity: ".55",
648
- strokeWidth: "1"
649
- }, c.id)),
650
- [...h.lines].sort((a, b) => Number(a.selected) - Number(b.selected)).map((l) => /* @__PURE__ */ jsx("path", {
651
- "data-line": lineName(l),
652
- d: path(l.envelope),
653
- fill: "none",
654
- stroke: scenarioColor(model, l.label),
655
- strokeWidth: "2",
656
- strokeLinejoin: "round",
657
- strokeLinecap: "round"
658
- }, lineName(l)))
659
- ]
660
- }),
661
- /* @__PURE__ */ jsx("line", {
662
- x1: loadX,
663
- x2: loadX,
664
- y1: m.t,
665
- y2: m.t + ph,
666
- stroke: "var(--lm-fg)",
667
- strokeOpacity: ".45"
668
- }),
669
- /* @__PURE__ */ jsx("text", {
670
- ...beside(loadX, measure(shown), "right"),
671
- y: m.t + 10,
672
- className: "lm-axis",
673
- children: shown
674
- }),
675
- h.lines.flatMap((l) => [[
676
- "target",
677
- l.targetRange,
678
- model.thresholds.target
679
- ], [
680
- "full",
681
- l.fullRange,
682
- model.thresholds.full
683
- ]].map(([kind, r, u]) => {
684
- if (!l.band || !r || !Number.isFinite(r.low) || r.low > h.to) return null;
685
- const [x1, x2] = [lx(Math.max(h.from, r.low)), lx(Math.min(h.to, r.high))];
686
- const y = ly(u);
687
- return /* @__PURE__ */ jsxs("g", {
688
- "data-range": kind,
689
- "data-scenario": lineName(l),
690
- "data-low": r.low,
691
- "data-high": r.high,
692
- stroke: scenarioColor(model, l.label),
693
- strokeWidth: l.selected ? 3 : 2,
694
- strokeOpacity: l.selected ? 1 : .6,
695
- children: [
696
- /* @__PURE__ */ jsx("line", {
697
- x1,
698
- x2,
699
- y1: y,
700
- y2: y
701
- }),
702
- /* @__PURE__ */ jsx("line", {
703
- x1,
704
- x2: x1,
705
- y1: y - 5,
706
- y2: y + 5
707
- }),
708
- Number.isFinite(r.high) && r.high <= h.to && /* @__PURE__ */ jsx("line", {
709
- x1: x2,
710
- x2,
711
- y1: y - 5,
712
- y2: y + 5
713
- })
714
- ]
715
- }, `${lineName(l)}/${kind}/range`);
716
- })),
717
- h.lines.flatMap((l) => [[
718
- "target",
719
- l.target,
720
- l.targetRange,
721
- model.thresholds.target
722
- ], [
723
- "full",
724
- l.full,
725
- l.fullRange,
726
- model.thresholds.full
727
- ]].map(([kind, x, r, u]) => x != null && Number.isFinite(x) && x >= h.from && x <= h.to ? /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("circle", {
728
- "data-crossing": kind,
729
- "data-scenario": lineName(l),
730
- "data-multiple": x,
731
- cx: lx(x),
732
- cy: ly(u),
733
- r: "4",
734
- fill: scenarioColor(model, l.label),
735
- stroke: "var(--lm-surface)",
736
- strokeWidth: "2"
737
- }), 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)),
738
- hx != null && /* @__PURE__ */ jsx("line", {
739
- x1: lx(hx),
740
- x2: lx(hx),
741
- y1: m.t,
742
- y2: m.t + ph,
743
- stroke: "var(--lm-fg)",
744
- strokeOpacity: ".8"
745
- }),
746
- /* @__PURE__ */ jsx("rect", {
747
- x: m.l,
748
- y: m.t,
749
- width: pw,
750
- height: ph,
751
- fill: "transparent",
752
- onPointerMove: onMove,
753
- onPointerDown: onMove,
754
- onPointerLeave: () => setHover(null)
755
- })
756
- ]
757
- }), hover != null && hx != null && /* @__PURE__ */ jsxs("div", {
758
- className: "lm-tip",
759
- role: "status",
760
- ref: tip,
761
- style: {
762
- left: lx(hx) + 10,
763
- top: m.t
764
- },
765
- children: [
766
- /* @__PURE__ */ jsxs("b", { children: [
767
- fmt(hx),
768
- "×",
769
- when(model, hx) && ` · ${when(model, hx)}`
770
- ] }),
771
- h.lines.map((l) => /* @__PURE__ */ jsxs("span", { children: [
772
- /* @__PURE__ */ jsx("b", {
773
- className: "lm-key",
774
- style: { background: scenarioColor(model, l.label) }
775
- }),
776
- /* @__PURE__ */ jsx("strong", { children: l.envelope[hover][1] == null ? "off" : pct(l.envelope[hover][1]) }),
777
- " ",
778
- lineName(l)
779
- ] }, lineName(l))),
780
- selected?.components.map((c) => /* @__PURE__ */ jsxs("span", {
781
- className: "lm-sub",
782
- children: [
783
- /* @__PURE__ */ jsx("strong", { children: c.points[hover][1] == null ? "off" : pct(c.points[hover][1]) }),
784
- " ",
785
- c.name
786
- ]
787
- }, c.id))
788
- ]
789
- })]
790
- })
791
- ]
792
- });
793
- }
794
- // src/Diagram.tsx
795
- const STATE_STROKE = {
796
- off: "var(--lm-line)",
797
- ok: "var(--lm-ok)",
798
- warn: "var(--lm-warn)",
799
- over: "var(--lm-drop)"
800
- };
801
- const tokenColor = (c) => [
802
- "accent",
803
- "alt",
804
- "ok",
805
- "warn",
806
- "drop",
807
- "muted"
808
- ].includes(c) ? `var(--lm-${c})` : c;
809
- function Diagram({ lm, legend = true, onNodeClick, selected = null }) {
810
- const { scene, engine, reducedMotion } = lm;
811
- const click = useRef(onNodeClick);
812
- click.current = onNodeClick;
813
- const [onClick] = useState(() => (id) => click.current?.(id));
814
- const svgRef = useRef(null);
815
- const canvasRef = useRef(null);
816
- const wrapRef = useRef(null);
817
- const barRef = useRef(null);
818
- const boardRef = useRef(null);
819
- const buttonRef = useRef(null);
820
- const titleRef = useRef(null);
821
- const full = lm.fullScreen;
822
- const [tip, setTip] = useState(null);
823
- const detailId = useId();
824
- useLayoutEffect(() => {
825
- if (scene) engine.setScene(scene, { cut: reducedMotion });
826
- }, [
827
- engine,
828
- scene,
829
- reducedMotion
830
- ]);
831
- const frameId = useSyncExternalStore(engine.subscribe, () => engine.frameId);
832
- const frame = engine.frame;
833
- const hand = useSyncExternalStore(engine.subscribe, () => engine.handover);
834
- useEffect(() => {
835
- engine.bind(svgRef.current, canvasRef.current);
836
- }, [
837
- engine,
838
- frame,
839
- reducedMotion
840
- ]);
841
- useLayoutEffect(() => {
842
- engine.applyCamera();
843
- engine.drawHalos();
844
- });
845
- useEffect(() => {
846
- if (lm.root) engine.readColors(lm.root);
847
- }, [
848
- engine,
849
- scene,
850
- lm.root
851
- ]);
852
- useEffect(() => {
853
- engine.drawnValues = JSON.stringify(lm.values);
854
- engine.drawnFocus = lm.focus;
855
- engine.drawnFrame = frameId;
856
- });
857
- useEffect(() => {
858
- const board = boardRef.current;
859
- if (!board) return;
860
- const ro = new ResizeObserver(() => engine.resize());
861
- ro.observe(board);
862
- return () => ro.disconnect();
863
- }, [engine]);
864
- const follow = () => {
865
- const wrap = wrapRef.current;
866
- const board = boardRef.current;
867
- const c = engine.camera;
868
- const title = titleRef.current;
869
- if (!c && !engine.cue) return;
870
- if (!wrap || !board || !engine.frame || wrap.scrollHeight <= wrap.clientHeight) {
871
- title?.style.removeProperty("top");
872
- title?.style.removeProperty("bottom");
873
- return;
874
- }
875
- const k = board.clientHeight / engine.frame.height;
876
- if (c) wrap.scrollTop = board.offsetTop + (c.y + c.h / 2) * k - wrap.clientHeight / 2;
877
- if (title) {
878
- title.style.top = `${Math.max(0, wrap.scrollTop - board.offsetTop + (barRef.current?.offsetHeight ?? 0))}px`;
879
- title.style.bottom = "auto";
880
- }
881
- };
882
- useEffect(() => {
883
- let raf = 0;
884
- let last = 0;
885
- const frame = (ts) => {
886
- const dt = last ? Math.min(.05, (ts - last) / 1e3) : 0;
887
- last = ts;
888
- if (!engine.paused && engine.scene) {
889
- engine.step(dt, { particles: !reducedMotion });
890
- engine.draw({ particles: !reducedMotion });
891
- follow();
892
- }
893
- raf = requestAnimationFrame(frame);
894
- };
895
- raf = requestAnimationFrame(frame);
896
- return () => cancelAnimationFrame(raf);
897
- }, [engine, reducedMotion]);
898
- const was = useRef(false);
899
- useEffect(() => {
900
- if (was.current && !full) buttonRef.current?.focus();
901
- was.current = full;
902
- }, [full]);
903
- useEffect(() => {
904
- const wrap = wrapRef.current;
905
- const bar = barRef.current;
906
- const root = lm.root;
907
- if (!full || !scene || !wrap || !bar || !root) return;
908
- const px = (x) => Number.parseFloat(x) || 0;
909
- const fit = () => {
910
- const rs = getComputedStyle(root);
911
- let around = px(rs.paddingTop) + px(rs.paddingBottom);
912
- const add = (el) => {
913
- const cs = getComputedStyle(el);
914
- if (cs.display === "none" || cs.position === "absolute" || cs.position === "fixed") return;
915
- around += px(rs.rowGap) + (px(cs.flexGrow) > 0 ? px(cs.minHeight) : el.offsetHeight);
916
- };
917
- for (const el of root.children) if (el !== wrap) add(el);
918
- if (getComputedStyle(root, "::after").content !== "none") around += px(rs.rowGap);
919
- const h = root.clientHeight - around - bar.offsetHeight - px(getComputedStyle(wrap).rowGap);
920
- const w = Math.min(wrap.clientWidth, h * scene.width / scene.height);
921
- wrap.style.setProperty("--lm-fit", `${Math.max(0, Math.floor(w))}px`);
922
- };
923
- const ro = new ResizeObserver(fit);
924
- const watch = () => {
925
- ro.disconnect();
926
- ro.observe(bar);
927
- ro.observe(root);
928
- for (const el of root.children) ro.observe(el);
929
- };
930
- watch();
931
- const mo = new MutationObserver(() => {
932
- watch();
933
- fit();
934
- });
935
- mo.observe(root, {
936
- childList: true,
937
- attributeFilter: ["data-mode"]
938
- });
939
- return () => {
940
- ro.disconnect();
941
- mo.disconnect();
942
- wrap.style.removeProperty("--lm-fit");
943
- };
944
- }, [
945
- full,
946
- scene,
947
- lm.root
948
- ]);
949
- const { setFullScreenMode, fullScreenMode } = lm;
950
- const modesRef = useRef(null);
951
- useEffect(() => {
952
- const root = lm.root;
953
- if (!full || !root || lm.fill) return;
954
- const f = (e) => {
955
- if (e.key !== "f" && e.key !== "F" || e.ctrlKey || e.metaKey || e.altKey) return;
956
- if (typing(e.composedPath()[0] ?? null) || root.querySelector(":scope > [data-drawer]")) return;
957
- e.preventDefault();
958
- if (e.repeat) return;
959
- const next = fullScreenMode === "focus" ? "panels" : "focus";
960
- if (document.activeElement?.closest(".lm-dock, .lm-line")) modesRef.current?.querySelector(`[data-mode="${next}"]`)?.focus();
961
- setFullScreenMode(next);
962
- };
963
- document.addEventListener("keydown", f);
964
- return () => document.removeEventListener("keydown", f);
965
- }, [
966
- full,
967
- fullScreenMode,
968
- setFullScreenMode,
969
- lm.root,
970
- lm.fill
971
- ]);
972
- return /* @__PURE__ */ jsxs("div", {
973
- className: "lm-wrap",
974
- ref: wrapRef,
431
+ className: "lm-wrap",
432
+ ref: wrapRef,
433
+ "data-canvas": canvas ? "" : void 0,
975
434
  children: [
976
435
  /* @__PURE__ */ jsxs("div", {
977
436
  className: "lm-bar",
@@ -990,7 +449,7 @@ function Diagram({ lm, legend = true, onNodeClick, selected = null }) {
990
449
  onClick: () => setFullScreenMode(m),
991
450
  children: m === "panels" ? "Panels" : "Focus"
992
451
  }, m))
993
- }), !lm.fill && /* @__PURE__ */ jsx("button", {
452
+ }), !lm.fill && !canvas && /* @__PURE__ */ jsx("button", {
994
453
  type: "button",
995
454
  className: "lm-btn",
996
455
  onClick: lm.toggleFullScreen,
@@ -1003,7 +462,8 @@ function Diagram({ lm, legend = true, onNodeClick, selected = null }) {
1003
462
  /* @__PURE__ */ jsxs("div", {
1004
463
  className: "lm-board",
1005
464
  ref: boardRef,
1006
- style: frame ? { aspectRatio: `${frame.width} / ${frame.height}` } : { minHeight: 240 },
465
+ "data-zoom": zoom ? "" : void 0,
466
+ style: canvas ? void 0 : frame ? { aspectRatio: `${frame.width} / ${frame.height}` } : { minHeight: 240 },
1007
467
  children: [
1008
468
  frame && /* @__PURE__ */ jsx(Structure, {
1009
469
  lm,
@@ -1028,12 +488,15 @@ function Diagram({ lm, legend = true, onNodeClick, selected = null }) {
1028
488
  })
1029
489
  ]
1030
490
  }),
1031
- frame && tip && !lm.storyPlaying && /* @__PURE__ */ jsx(Detail, {
1032
- lm,
1033
- scene: frame,
1034
- id: tip.id,
1035
- board: boardRef.current,
1036
- detailId
491
+ frame && tip && !lm.storyPlaying && /* @__PURE__ */ jsx(Suspense, {
492
+ fallback: null,
493
+ children: /* @__PURE__ */ jsx(Detail, {
494
+ lm,
495
+ scene: frame,
496
+ id: tip.id,
497
+ board: boardRef.current,
498
+ detailId
499
+ })
1037
500
  })
1038
501
  ]
1039
502
  });
@@ -1503,974 +966,1074 @@ function Halo({ n, kind, component, tag }) {
1503
966
  });
1504
967
  }
1505
968
  /**
1506
- * A quiet badge on a box's top edge: where the next in line reach the target ("2nd · 20×"), or, while the limit
1507
- * passes on, where the old limit is now. No ring, no breathing. `was`: a note the engine fades in and out.
969
+ * A quiet badge on a box's top edge: where the next in line reach the target ("2nd · 20×"), or, while the limit
970
+ * passes on, where the old limit is now. No ring, no breathing. `was`: a note the engine fades in and out.
971
+ */
972
+ function Badge({ n, text, was }) {
973
+ const w = tagWidth(text, 4.9);
974
+ const tx = n.x + n.w - w - 6;
975
+ return /* @__PURE__ */ jsx("g", {
976
+ className: "lm-badge",
977
+ "data-badge": text,
978
+ "data-was": was || void 0,
979
+ opacity: n.fade,
980
+ pointerEvents: "none",
981
+ children: /* @__PURE__ */ jsxs("g", {
982
+ "data-show": "",
983
+ children: [/* @__PURE__ */ jsx("rect", {
984
+ x: tx,
985
+ y: n.y - 7,
986
+ width: w,
987
+ height: "14",
988
+ rx: "7",
989
+ fill: "var(--lm-surface)",
990
+ stroke: "var(--lm-muted)"
991
+ }), /* @__PURE__ */ jsx("text", {
992
+ x: tx + w / 2,
993
+ y: n.y + 3,
994
+ textAnchor: "middle",
995
+ fontSize: "8.5",
996
+ fontWeight: "600",
997
+ fill: "var(--lm-muted)",
998
+ children: text
999
+ })]
1000
+ })
1001
+ });
1002
+ }
1003
+ // src/elk.ts
1004
+ let shared = null;
1005
+ /**
1006
+ * One ELK worker for every loadmap on the page, started on the first layout. When the worker cannot start or load
1007
+ * (no Worker, a CSP without worker-src, a dev server that pre-bundled this package away from the worker file), every
1008
+ * layout runs on the main thread instead: slower to start, the same result.
1009
+ */
1010
+ function pageElk() {
1011
+ shared ??= workerElk(() => new Worker(new URL("./elk.worker.js", import.meta.url), {
1012
+ type: "module",
1013
+ name: "loadmap-elk"
1014
+ }));
1015
+ return shared;
1016
+ }
1017
+ /**
1018
+ * ELK in the worker `make` starts, falling back to the main thread: `<Loadmap elk={workerElk(…)}>` for a page whose
1019
+ * bundler inlines the worker (`@loadmap/react/elk.worker.js`), or that serves it from another place. Make it once,
1020
+ * outside a component: each engine starts its own worker.
1021
+ */
1022
+ function workerElk(make) {
1023
+ let worker = null;
1024
+ let broken = typeof Worker === "undefined";
1025
+ let told = false;
1026
+ let next = 0;
1027
+ const pending = /* @__PURE__ */ new Map();
1028
+ const tell = (why) => {
1029
+ if (told || typeof Worker === "undefined") return;
1030
+ told = true;
1031
+ 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).`);
1032
+ };
1033
+ const fallBack = (why) => {
1034
+ tell(why);
1035
+ broken = true;
1036
+ worker?.terminate();
1037
+ worker = null;
1038
+ for (const [id, p] of pending) {
1039
+ pending.delete(id);
1040
+ localElk().then((elk) => elk.layout(p.graph)).then(p.resolve, p.reject);
1041
+ }
1042
+ };
1043
+ const start = () => {
1044
+ if (worker || broken) return worker;
1045
+ try {
1046
+ worker = make();
1047
+ } catch (err) {
1048
+ fallBack(err instanceof Error ? err.message : String(err));
1049
+ return null;
1050
+ }
1051
+ worker.onmessage = ({ data }) => {
1052
+ const p = pending.get(data.id);
1053
+ if (!p) return;
1054
+ pending.delete(data.id);
1055
+ if (data.error != null) p.reject(new Error(data.error));
1056
+ else p.resolve(data.graph);
1057
+ };
1058
+ worker.onerror = (e) => {
1059
+ e.preventDefault();
1060
+ fallBack(e.message || "it failed to load or to run");
1061
+ };
1062
+ return worker;
1063
+ };
1064
+ return { layout(graph) {
1065
+ const w = start();
1066
+ if (!w) {
1067
+ tell("no Worker here");
1068
+ return localElk().then((elk) => elk.layout(graph));
1069
+ }
1070
+ return new Promise((resolve, reject) => {
1071
+ const id = next++;
1072
+ pending.set(id, {
1073
+ graph,
1074
+ resolve,
1075
+ reject
1076
+ });
1077
+ w.postMessage({
1078
+ id,
1079
+ graph
1080
+ });
1081
+ });
1082
+ } };
1083
+ }
1084
+ // src/panels.tsx
1085
+ /** The model's one-sentence answer for the current values, and which capacity to measure when it is unsure. */
1086
+ function Verdict({ lm }) {
1087
+ const { measure } = lm.ev;
1088
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("p", {
1089
+ className: "lm-verdict",
1090
+ "data-tier": lm.ev.verdict.tier,
1091
+ "aria-live": "polite",
1092
+ children: lm.ev.verdict.text
1093
+ }), measure && /* @__PURE__ */ jsx("p", {
1094
+ className: "lm-measure",
1095
+ "data-component": measure.component,
1096
+ children: measure.text
1097
+ })] });
1098
+ }
1099
+ /** "±30 %" for a capacity with a range. */
1100
+ const plusMinus = (c) => c?.within ? `±${pct(c.within)}` : "";
1101
+ /** Each component's utilization in the order they reach the target, with where they cross it and 100 %. */
1102
+ function Limits({ lm, title = "Where it runs out, in order" }) {
1103
+ const { ev, model } = lm;
1104
+ const top = Math.max(1.5, model.thresholds.full * 1.5);
1105
+ const at = (u) => `${u / top * 100}%`;
1106
+ const span = (r, x) => r ? multiples(r, model.searchMax, true) : multiple(x, model.searchMax);
1107
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1108
+ /* @__PURE__ */ jsx("h3", { children: title }),
1109
+ /* @__PURE__ */ jsxs("div", {
1110
+ className: "lm-scale",
1111
+ "aria-hidden": "true",
1112
+ children: [
1113
+ /* @__PURE__ */ jsx("span", {}),
1114
+ /* @__PURE__ */ jsxs("div", { children: [
1115
+ /* @__PURE__ */ jsx("span", {
1116
+ style: {
1117
+ left: 0,
1118
+ transform: "none"
1119
+ },
1120
+ children: "0"
1121
+ }),
1122
+ /* @__PURE__ */ jsxs("span", {
1123
+ style: { left: at(model.thresholds.target) },
1124
+ children: [pct(model.thresholds.target), " target"]
1125
+ }),
1126
+ /* @__PURE__ */ jsx("span", {
1127
+ style: { left: at(model.thresholds.full) },
1128
+ children: pct(model.thresholds.full)
1129
+ }),
1130
+ /* @__PURE__ */ jsx("span", {
1131
+ style: {
1132
+ left: "100%",
1133
+ transform: "translateX(-100%)"
1134
+ },
1135
+ children: pct(top)
1136
+ })
1137
+ ] }),
1138
+ /* @__PURE__ */ jsx("span", {})
1139
+ ]
1140
+ }),
1141
+ /* @__PURE__ */ jsx("div", {
1142
+ className: "lm-limits",
1143
+ children: ev.ranked.map((c) => /* @__PURE__ */ jsxs("div", {
1144
+ className: "lm-lim",
1145
+ "data-component": c.id,
1146
+ children: [
1147
+ /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsxs("b", { children: [
1148
+ c.name,
1149
+ c === ev.firstLimit && /* @__PURE__ */ jsx("span", {
1150
+ className: "lm-tag",
1151
+ "data-kind": "first",
1152
+ children: "limit"
1153
+ }),
1154
+ c.capacity?.provenance === "estimated" ? /* @__PURE__ */ jsxs("span", {
1155
+ className: "lm-tag",
1156
+ "data-kind": "estimated",
1157
+ children: ["estimate", c.capacity.within ? ` ${plusMinus(c.capacity)}` : ""]
1158
+ }) : !!c.capacity?.within && /* @__PURE__ */ jsx("span", {
1159
+ className: "lm-tag",
1160
+ "data-kind": "range",
1161
+ children: plusMinus(c.capacity)
1162
+ })
1163
+ ] }), /* @__PURE__ */ jsx("span", {
1164
+ className: "lm-sub",
1165
+ children: c.describe ?? (c.capacity ? `${fmt(c.capacity.value)} ${c.capacity.unit}` : "switched off")
1166
+ })] }),
1167
+ /* @__PURE__ */ jsxs("div", {
1168
+ className: "lm-track",
1169
+ role: "img",
1170
+ "aria-label": `${c.name} at ${c.util == null ? "off" : pct(c.util)}`,
1171
+ children: [
1172
+ /* @__PURE__ */ jsx("div", {
1173
+ className: "lm-fill",
1174
+ "data-state": c.state,
1175
+ style: { width: `${Math.min(100, (c.util ?? 0) / top * 100)}%` }
1176
+ }),
1177
+ /* @__PURE__ */ jsx("div", {
1178
+ className: "lm-tick",
1179
+ style: { left: at(model.thresholds.target) }
1180
+ }),
1181
+ /* @__PURE__ */ jsx("div", {
1182
+ className: "lm-tick",
1183
+ style: { left: at(model.thresholds.full) }
1184
+ })
1185
+ ]
1186
+ }),
1187
+ /* @__PURE__ */ jsxs("div", {
1188
+ className: "lm-val",
1189
+ 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)}` })]
1190
+ })
1191
+ ]
1192
+ }, c.id))
1193
+ })
1194
+ ] });
1195
+ }
1196
+ /**
1197
+ * Live numbers: from the sim, lag and drops per queue, busy workers, rejected requests; from the model, pods running,
1198
+ * cache answers and retries.
1508
1199
  */
1509
- function Badge({ n, text, was }) {
1510
- const w = tagWidth(text, 4.9);
1511
- const tx = n.x + n.w - w - 6;
1512
- return /* @__PURE__ */ jsx("g", {
1513
- className: "lm-badge",
1514
- "data-badge": text,
1515
- "data-was": was || void 0,
1516
- opacity: n.fade,
1517
- pointerEvents: "none",
1518
- children: /* @__PURE__ */ jsxs("g", {
1519
- "data-show": "",
1520
- children: [/* @__PURE__ */ jsx("rect", {
1521
- x: tx,
1522
- y: n.y - 7,
1523
- width: w,
1524
- height: "14",
1525
- rx: "7",
1526
- fill: "var(--lm-surface)",
1527
- stroke: "var(--lm-muted)"
1528
- }), /* @__PURE__ */ jsx("text", {
1529
- x: tx + w / 2,
1530
- y: n.y + 3,
1531
- textAnchor: "middle",
1532
- fontSize: "8.5",
1533
- fontWeight: "600",
1534
- fill: "var(--lm-muted)",
1535
- children: text
1200
+ function Meters({ lm }) {
1201
+ const [, tick] = useState(0);
1202
+ useEffect(() => {
1203
+ const t = setInterval(() => tick((x) => x + 1), 250);
1204
+ return () => clearInterval(t);
1205
+ }, []);
1206
+ const { ev, engine, model } = lm;
1207
+ const sim = engine.sim;
1208
+ const flowLabel = (f) => model.def.flows[f]?.label ?? f;
1209
+ const items = [];
1210
+ for (const s of Object.values(ev.stages)) {
1211
+ if (s.kind === "queue") for (const f of model.flowIds.filter((x) => ev.routes[x]?.includes(s.id))) {
1212
+ const q = sim.queue(s.id, f);
1213
+ const rules = ev.overload[f] ?? {};
1214
+ items.push({
1215
+ key: `${s.id}/${f}/lag`,
1216
+ value: secs(q.lag),
1217
+ label: `${flowLabel(f)} lag in ${s.label}`,
1218
+ state: q.lag > 60 ? "over" : q.lag > 5 ? "warn" : "ok"
1219
+ });
1220
+ if (rules.merge) items.push({
1221
+ key: `${s.id}/${f}/merge`,
1222
+ value: compact(q.merged),
1223
+ label: `${flowLabel(f)} superseded /s (${rules.merge.reason ?? "newest kept"})`,
1224
+ state: q.merged > .5 ? "warn" : "ok"
1225
+ });
1226
+ if (rules.drop) items.push({
1227
+ key: `${s.id}/${f}/drop`,
1228
+ value: compact(q.dropped),
1229
+ label: `${flowLabel(f)} dropped /s (${rules.drop.reason ?? "too old"})`,
1230
+ state: q.dropped > .5 ? "over" : "ok"
1231
+ });
1232
+ }
1233
+ if (s.kind === "workers") {
1234
+ const b = sim.busy(s.id);
1235
+ items.push({
1236
+ key: `${s.id}/busy`,
1237
+ value: pct(b),
1238
+ label: `${s.label} busy`,
1239
+ state: b > .95 ? "over" : b > .5 ? "warn" : "ok"
1240
+ });
1241
+ if (s.autoscale) items.push({
1242
+ key: `${s.id}/pods`,
1243
+ value: `${s.running} of ${s.pods}`,
1244
+ label: `${s.label} pods running`,
1245
+ state: s.running < s.pods ? "ok" : (ev.components[s.component]?.util ?? 0) > model.thresholds.full ? "over" : "warn"
1246
+ });
1247
+ }
1248
+ if (s.kind === "cache") items.push({
1249
+ key: `${s.id}/hits`,
1250
+ value: compact(sim.arriving(s.id) * (1 - sim.shed(s.id)) * s.hit),
1251
+ label: `answered at ${s.label} /s (${pct(s.hit)} hits)`,
1252
+ state: "ok"
1253
+ });
1254
+ if ((s.kind === "pass" || s.kind === "limit" || s.kind === "cache") && sim.shed(s.id) > 0) items.push({
1255
+ key: `${s.id}/shed`,
1256
+ value: pct(sim.shed(s.id)),
1257
+ label: `rejected at ${s.label}`,
1258
+ state: "over"
1259
+ });
1260
+ }
1261
+ for (const f of model.flowIds) {
1262
+ const r = ev.retry[f];
1263
+ if (!r || !(r.rate > 0)) continue;
1264
+ const per = r.attempts / r.rate;
1265
+ items.push({
1266
+ key: `${f}/attempts`,
1267
+ value: `${fmt(per)}×`,
1268
+ label: `${flowLabel(f)} attempts per ${model.def.flows[f]?.unit ?? "unit"}`,
1269
+ state: per > 1.05 ? "warn" : "ok"
1270
+ });
1271
+ items.push({
1272
+ key: `${f}/failed`,
1273
+ value: pct(r.failed),
1274
+ label: `${flowLabel(f)} failing after ${r.times} ${r.times === 1 ? "retry" : "retries"}`,
1275
+ state: r.failed > .005 ? "over" : "ok"
1276
+ });
1277
+ }
1278
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("h3", { children: "Live" }), /* @__PURE__ */ jsx("div", {
1279
+ className: "lm-meters",
1280
+ children: items.map((m) => /* @__PURE__ */ jsxs("div", {
1281
+ className: "lm-meter",
1282
+ "data-state": m.state,
1283
+ children: [/* @__PURE__ */ jsx("b", { children: m.value }), /* @__PURE__ */ jsx("span", {
1284
+ title: m.label,
1285
+ children: m.label
1536
1286
  })]
1537
- })
1287
+ }, m.key))
1288
+ })] });
1289
+ }
1290
+ /** The load slider with its label and value. */
1291
+ function LoadRange({ lm }) {
1292
+ const load = lm.model.load;
1293
+ const x = lm.values.load;
1294
+ return /* @__PURE__ */ jsxs("label", {
1295
+ className: "lm-range",
1296
+ children: [/* @__PURE__ */ jsxs("span", { children: [
1297
+ load.label,
1298
+ " ",
1299
+ /* @__PURE__ */ jsxs("output", { children: [fmt(x), "×"] })
1300
+ ] }), /* @__PURE__ */ jsx("input", {
1301
+ type: "range",
1302
+ min: load.min,
1303
+ max: load.max,
1304
+ step: load.step,
1305
+ value: x,
1306
+ onChange: (e) => lm.setValues({ load: Number(e.target.value) })
1307
+ })]
1538
1308
  });
1539
1309
  }
1540
- /**
1541
- * A box's component in words, over the board: utilization, demand against capacity and where it came from, where it
1542
- * reaches the target and 100 % (with dates, given growth), and its target in each scenario. HTML, so exports leave it out.
1543
- */
1544
- function Detail({ lm, scene, id, board, detailId }) {
1545
- const { model, ev } = lm;
1546
- const n = scene.nodes.find((x) => x.id === id);
1547
- const cid = n && componentOf(lm, n);
1548
- const comparison = useComparison(lm);
1549
- const rows = model.scenarios.length > 1 ? comparison.rows : [];
1550
- useEffect(() => {
1551
- const el = board?.querySelector(`[data-node="${CSS.escape(id)}"]`);
1552
- el?.setAttribute("aria-describedby", detailId);
1553
- return () => el?.removeAttribute("aria-describedby");
1554
- }, [
1555
- board,
1556
- id,
1557
- detailId
1558
- ]);
1559
- const c = cid ? ev.components[cid] : void 0;
1560
- const tip = useRef(null);
1561
- const box = n && `${n.x} ${n.y} ${n.w} ${n.h}`;
1562
- useLayoutEffect(() => {
1563
- const el = tip.current;
1564
- const wrap = el?.offsetParent;
1565
- if (!el || !n || !board || !(wrap instanceof HTMLElement)) return;
1566
- const place = () => {
1567
- const k = board.clientWidth / scene.width;
1568
- const w = wrap.getBoundingClientRect();
1569
- const y = (v) => v - w.top - wrap.clientTop + wrap.scrollTop;
1570
- let lo = 0;
1571
- let hi = innerHeight;
1572
- for (let a = wrap; a; a = a.parentElement) {
1573
- if (getComputedStyle(a).overflowY === "visible") continue;
1574
- const r = a.getBoundingClientRect();
1575
- lo = Math.max(lo, r.top);
1576
- hi = Math.min(hi, r.bottom);
1577
- }
1578
- const [top, bottom] = [y(lo) + 4, y(hi) - 4];
1579
- const h = el.offsetHeight;
1580
- const boxTop = board.offsetTop + n.y * k;
1581
- const boxBottom = board.offsetTop + (n.y + n.h) * k;
1582
- const below = boxBottom + 6;
1583
- const above = boxTop - 6 - h;
1584
- const fits = (n.y + n.h / 2 < scene.height / 2 ? [below, above] : [above, below]).find((t) => t >= top && t + h <= bottom);
1585
- const roomier = bottom - boxBottom >= boxTop - top ? below : above;
1586
- el.style.top = `${Math.max(top, Math.min(fits ?? roomier, bottom - h))}px`;
1587
- el.style.left = `${Math.max(0, Math.min(board.offsetLeft + n.x * k, wrap.clientWidth - el.offsetWidth))}px`;
1588
- };
1589
- place();
1590
- const ro = new ResizeObserver(place);
1591
- ro.observe(el);
1592
- ro.observe(board);
1593
- document.addEventListener("scroll", place, {
1594
- capture: true,
1595
- passive: true
1596
- });
1597
- addEventListener("resize", place);
1598
- return () => {
1599
- ro.disconnect();
1600
- document.removeEventListener("scroll", place, { capture: true });
1601
- removeEventListener("resize", place);
1602
- };
1603
- }, [
1604
- box,
1605
- board,
1606
- scene
1607
- ]);
1608
- if (!n || !c || !board) return null;
1609
- const at = (r, x) => r ? reach(r, model.searchMax, model.dateAt) : multiple(x, model.searchMax);
1610
- const num = (x) => Math.abs(x) >= 1e3 ? compact(x) : fmt(x);
1611
- const cap = c.capacity;
1612
- const rank = rankLabels(ev, model).get(c.id);
1310
+ /** The load slider, the presets and every parameter, greyed out where it does not apply. */
1311
+ function Controls({ lm }) {
1312
+ const { model, values, setValues, ev } = lm;
1313
+ const v = values;
1613
1314
  return /* @__PURE__ */ jsxs("div", {
1614
- id: detailId,
1615
- className: "lm-tip lm-detail",
1616
- role: "tooltip",
1617
- ref: tip,
1315
+ className: "lm-card lm-controls",
1618
1316
  children: [
1619
- /* @__PURE__ */ jsxs("b", { children: [c.name, rank && /* @__PURE__ */ jsx("span", {
1620
- className: "lm-tag",
1621
- "data-kind": rank.rank === 1 ? "first" : "rank",
1622
- children: rank.word
1623
- })] }),
1624
- c.util == null || !cap ? /* @__PURE__ */ jsx("span", { children: "switched off" }) : /* @__PURE__ */ jsxs(Fragment, { children: [
1625
- /* @__PURE__ */ jsxs("span", { children: [
1626
- /* @__PURE__ */ jsx("strong", { children: pct(c.util) }),
1627
- " · ",
1628
- num(c.demand ?? 0),
1629
- " of ",
1630
- fmt(cap.value),
1631
- " ",
1632
- cap.unit,
1633
- cap.within ? ` ±${pct(cap.within)}` : ""
1634
- ] }),
1635
- /* @__PURE__ */ jsxs("span", {
1636
- className: "lm-sub",
1317
+ /* @__PURE__ */ jsx("h3", { children: "Load" }),
1318
+ /* @__PURE__ */ jsx(LoadRange, { lm }),
1319
+ /* @__PURE__ */ jsx("div", {
1320
+ className: "lm-presets",
1321
+ children: ev.presets.map((p) => {
1322
+ const on = Object.entries(p.values).every(([k, x]) => v[k] === x);
1323
+ return /* @__PURE__ */ jsx("button", {
1324
+ type: "button",
1325
+ "aria-pressed": on,
1326
+ onClick: () => setValues(p.values),
1327
+ children: p.label
1328
+ }, p.label);
1329
+ })
1330
+ }),
1331
+ model.params.length > 1 && /* @__PURE__ */ jsx("h3", { children: "Design" }),
1332
+ model.params.map(({ id, def }) => {
1333
+ if (def.kind === "load") return null;
1334
+ const enabled = model.isEnabled(id, v);
1335
+ const tag = def.tag && /* @__PURE__ */ jsx("span", {
1336
+ className: "lm-tag",
1337
+ "data-kind": "estimated",
1338
+ children: def.tag
1339
+ });
1340
+ if (def.kind === "switch") return /* @__PURE__ */ jsxs("label", {
1341
+ className: `lm-switch${enabled ? "" : " lm-off"}`,
1637
1342
  children: [
1638
- "capacity",
1639
- " ",
1640
- /* @__PURE__ */ jsx("span", {
1641
- className: "lm-prov",
1642
- "data-kind": cap.provenance,
1643
- children: cap.provenance
1343
+ /* @__PURE__ */ jsx("input", {
1344
+ type: "checkbox",
1345
+ checked: Boolean(v[id]),
1346
+ disabled: !enabled,
1347
+ onChange: (e) => setValues({ [id]: e.target.checked })
1644
1348
  }),
1645
- cap.source ? `, ${cap.source}` : ""
1349
+ /* @__PURE__ */ jsxs("span", { children: [def.label, tag] }),
1350
+ def.hint && /* @__PURE__ */ jsx("small", { children: def.hint })
1646
1351
  ]
1647
- }),
1648
- /* @__PURE__ */ jsxs("span", { children: [
1649
- pct(model.thresholds.target),
1650
- " at ",
1651
- at(c.targetRange, c.target)
1652
- ] }),
1653
- /* @__PURE__ */ jsxs("span", { children: [
1654
- pct(model.thresholds.full),
1655
- " at ",
1656
- at(c.fullRange, c.full)
1657
- ] }),
1658
- blocks(lm, n).map((line) => /* @__PURE__ */ jsx("span", { children: line }, line)),
1659
- c.over && /* @__PURE__ */ jsxs("span", {
1660
- className: "lm-sub",
1352
+ }, id);
1353
+ if (def.kind === "select") return /* @__PURE__ */ jsxs("label", {
1354
+ className: `lm-select${enabled ? "" : " lm-off"}`,
1661
1355
  children: [
1662
- "Past ",
1663
- pct(model.thresholds.full),
1664
- ": ",
1665
- c.over,
1666
- "."
1356
+ /* @__PURE__ */ jsxs("span", { children: [def.label, tag] }),
1357
+ /* @__PURE__ */ jsx("select", {
1358
+ value: String(v[id]),
1359
+ disabled: !enabled,
1360
+ onChange: (e) => {
1361
+ const opt = def.options.find((o) => String(o) === e.target.value);
1362
+ setValues({ [id]: opt });
1363
+ },
1364
+ children: def.options.map((o) => /* @__PURE__ */ jsx("option", {
1365
+ value: String(o),
1366
+ children: def.format ? def.format(o) : String(o)
1367
+ }, String(o)))
1368
+ }),
1369
+ def.hint && /* @__PURE__ */ jsx("small", { children: def.hint })
1667
1370
  ]
1668
- })
1669
- ] }),
1670
- rows.length > 0 && /* @__PURE__ */ jsxs("span", {
1671
- className: "lm-sub",
1672
- children: [
1673
- pct(model.thresholds.target),
1674
- " by scenario:",
1675
- " ",
1676
- rows.map((r, i) => {
1677
- const x = r.components.find((y) => y.id === cid);
1678
- return /* @__PURE__ */ jsxs("span", {
1679
- className: "lm-nowrap",
1680
- children: [
1681
- i > 0 && " · ",
1682
- /* @__PURE__ */ jsx("b", {
1683
- className: "lm-key",
1684
- style: { background: scenarioColor(model, r.label) }
1685
- }),
1686
- r.label,
1687
- " ",
1688
- x?.targetRange == null ? "off" : multiples(x.targetRange, model.searchMax, true)
1689
- ]
1690
- }, r.label);
1691
- })
1692
- ]
1371
+ }, id);
1372
+ return /* @__PURE__ */ jsxs("label", {
1373
+ className: `lm-range${enabled ? "" : " lm-off"}`,
1374
+ children: [
1375
+ /* @__PURE__ */ jsxs("span", { children: [
1376
+ def.label,
1377
+ tag,
1378
+ " ",
1379
+ /* @__PURE__ */ jsx("output", { children: def.format ? def.format(v[id]) : fmt(v[id]) })
1380
+ ] }),
1381
+ /* @__PURE__ */ jsx("input", {
1382
+ type: "range",
1383
+ min: def.min,
1384
+ max: def.max,
1385
+ step: def.step,
1386
+ value: v[id],
1387
+ disabled: !enabled,
1388
+ onChange: (e) => setValues({ [id]: Number(e.target.value) })
1389
+ }),
1390
+ def.hint && /* @__PURE__ */ jsx("small", { children: def.hint })
1391
+ ]
1392
+ }, id);
1693
1393
  })
1694
1394
  ]
1695
1395
  });
1696
1396
  }
1697
- /** What a box's building blocks do at these values: pods running, cache answers, what a stage turns away. */
1698
- function blocks(lm, n) {
1699
- const out = [];
1700
- for (const id of n.stages) {
1701
- const s = lm.ev.stages[id];
1702
- if (s?.kind === "workers" && s.autoscale) out.push(`${s.running} of ${s.pods} pods running, each held near ${pct(s.autoscale.target)}`);
1703
- if (s?.kind === "cache") out.push(`${pct(s.hit)} answered here`);
1704
- if ((s?.kind === "pass" || s?.kind === "limit" || s?.kind === "cache") && s.shed > 0) out.push(`${pct(s.shed)} of what reaches it turned away`);
1705
- }
1706
- return out;
1707
- }
1708
- // src/elk.ts
1709
- let shared = null;
1710
- /**
1711
- * One ELK worker for every loadmap on the page, started on the first layout. When the worker cannot start or load
1712
- * (no Worker, a CSP without worker-src, a dev server that pre-bundled this package away from the worker file), every
1713
- * layout runs on the main thread instead: slower to start, the same result.
1714
- */
1715
- function pageElk() {
1716
- shared ??= workerElk(() => new Worker(new URL("./elk.worker.js", import.meta.url), {
1717
- type: "module",
1718
- name: "loadmap-elk"
1719
- }));
1720
- return shared;
1721
- }
1722
- /**
1723
- * ELK in the worker `make` starts, falling back to the main thread: `<Loadmap elk={workerElk(…)}>` for a page whose
1724
- * bundler inlines the worker (`@loadmap/react/elk.worker.js`), or that serves it from another place. Make it once,
1725
- * outside a component: each engine starts its own worker.
1726
- */
1727
- function workerElk(make) {
1728
- let worker = null;
1729
- let broken = typeof Worker === "undefined";
1730
- let told = false;
1731
- let next = 0;
1732
- const pending = /* @__PURE__ */ new Map();
1733
- const tell = (why) => {
1734
- if (told || typeof Worker === "undefined") return;
1735
- told = true;
1736
- 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).`);
1737
- };
1738
- const fallBack = (why) => {
1739
- tell(why);
1740
- broken = true;
1741
- worker?.terminate();
1742
- worker = null;
1743
- for (const [id, p] of pending) {
1744
- pending.delete(id);
1745
- localElk().then((elk) => elk.layout(p.graph)).then(p.resolve, p.reject);
1746
- }
1747
- };
1748
- const start = () => {
1749
- if (worker || broken) return worker;
1750
- try {
1751
- worker = make();
1752
- } catch (err) {
1753
- fallBack(err instanceof Error ? err.message : String(err));
1754
- return null;
1755
- }
1756
- worker.onmessage = ({ data }) => {
1757
- const p = pending.get(data.id);
1758
- if (!p) return;
1759
- pending.delete(data.id);
1760
- if (data.error != null) p.reject(new Error(data.error));
1761
- else p.resolve(data.graph);
1762
- };
1763
- worker.onerror = (e) => {
1764
- e.preventDefault();
1765
- fallBack(e.message || "it failed to load or to run");
1766
- };
1767
- return worker;
1768
- };
1769
- return { layout(graph) {
1770
- const w = start();
1771
- if (!w) {
1772
- tell("no Worker here");
1773
- return localElk().then((elk) => elk.layout(graph));
1774
- }
1775
- return new Promise((resolve, reject) => {
1776
- const id = next++;
1777
- pending.set(id, {
1778
- graph,
1779
- resolve,
1780
- reject
1781
- });
1782
- w.postMessage({
1783
- id,
1784
- graph
1785
- });
1786
- });
1787
- } };
1788
- }
1789
- // src/panels.tsx
1790
- /** The model's one-sentence answer for the current values, and which capacity to measure when it is unsure. */
1791
- function Verdict({ lm }) {
1792
- const { measure } = lm.ev;
1793
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("p", {
1794
- className: "lm-verdict",
1795
- "data-tier": lm.ev.verdict.tier,
1796
- "aria-live": "polite",
1797
- children: lm.ev.verdict.text
1798
- }), measure && /* @__PURE__ */ jsx("p", {
1799
- className: "lm-measure",
1800
- "data-component": measure.component,
1801
- children: measure.text
1802
- })] });
1803
- }
1804
- /** "±30 %" for a capacity with a range. */
1805
- const plusMinus = (c) => c?.within ? `±${pct(c.within)}` : "";
1806
- /** Each component's utilization in the order they reach the target, with where they cross it and 100 %. */
1807
- function Limits({ lm, title = "Where it runs out, in order" }) {
1808
- const { ev, model } = lm;
1809
- const top = Math.max(1.5, model.thresholds.full * 1.5);
1810
- const at = (u) => `${u / top * 100}%`;
1811
- const span = (r, x) => r ? multiples(r, model.searchMax, true) : multiple(x, model.searchMax);
1397
+ /** What the model assumes: every capacity with its provenance, every fit, and anything the page adds. */
1398
+ function Assumptions({ lm, extra = [] }) {
1399
+ return /* @__PURE__ */ jsxs("div", {
1400
+ className: "lm-card",
1401
+ children: [/* @__PURE__ */ jsx("h3", { children: "What this assumes" }), /* @__PURE__ */ jsxs("ul", {
1402
+ className: "lm-facts",
1403
+ 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}`))]
1404
+ })]
1405
+ });
1406
+ }
1407
+ function describe(a) {
1408
+ if (a.kind === "capacity") {
1409
+ const c = a.capacity;
1410
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1411
+ /* @__PURE__ */ jsxs("b", { children: [a.name, ":"] }),
1412
+ " ",
1413
+ fmt(c.value),
1414
+ " ",
1415
+ c.unit,
1416
+ c.within ? ` ${plusMinus(c)}` : "",
1417
+ ",",
1418
+ " ",
1419
+ /* @__PURE__ */ jsx("span", {
1420
+ className: "lm-prov",
1421
+ "data-kind": c.provenance,
1422
+ children: c.provenance
1423
+ }),
1424
+ c.source ? ` (${c.source})` : "",
1425
+ "."
1426
+ ] });
1427
+ }
1428
+ const f = a.fit;
1812
1429
  return /* @__PURE__ */ jsxs(Fragment, { children: [
1813
- /* @__PURE__ */ jsx("h3", { children: title }),
1814
- /* @__PURE__ */ jsxs("div", {
1815
- className: "lm-scale",
1816
- "aria-hidden": "true",
1817
- children: [
1818
- /* @__PURE__ */ jsx("span", {}),
1819
- /* @__PURE__ */ jsxs("div", { children: [
1820
- /* @__PURE__ */ jsx("span", {
1821
- style: {
1822
- left: 0,
1823
- transform: "none"
1824
- },
1825
- children: "0"
1826
- }),
1827
- /* @__PURE__ */ jsxs("span", {
1828
- style: { left: at(model.thresholds.target) },
1829
- children: [pct(model.thresholds.target), " target"]
1830
- }),
1831
- /* @__PURE__ */ jsx("span", {
1832
- style: { left: at(model.thresholds.full) },
1833
- children: pct(model.thresholds.full)
1834
- }),
1835
- /* @__PURE__ */ jsx("span", {
1836
- style: {
1837
- left: "100%",
1838
- transform: "translateX(-100%)"
1839
- },
1840
- children: pct(top)
1841
- })
1842
- ] }),
1843
- /* @__PURE__ */ jsx("span", {})
1844
- ]
1430
+ /* @__PURE__ */ jsxs("b", { children: [a.name, ":"] }),
1431
+ " ",
1432
+ f.y,
1433
+ " = ",
1434
+ sig(f.a),
1435
+ " + ",
1436
+ sig(f.b),
1437
+ " × ",
1438
+ f.x,
1439
+ ", r² ",
1440
+ f.r2.toFixed(3),
1441
+ " over ",
1442
+ f.n,
1443
+ " points,",
1444
+ " ",
1445
+ /* @__PURE__ */ jsx("span", {
1446
+ className: "lm-prov",
1447
+ "data-kind": "measured",
1448
+ children: "measured"
1845
1449
  }),
1846
- /* @__PURE__ */ jsx("div", {
1847
- className: "lm-limits",
1848
- children: ev.ranked.map((c) => /* @__PURE__ */ jsxs("div", {
1849
- className: "lm-lim",
1850
- "data-component": c.id,
1851
- children: [
1852
- /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsxs("b", { children: [
1853
- c.name,
1854
- c === ev.firstLimit && /* @__PURE__ */ jsx("span", {
1855
- className: "lm-tag",
1856
- "data-kind": "first",
1857
- children: "limit"
1450
+ f.source ? ` (${f.source})` : "",
1451
+ "."
1452
+ ] });
1453
+ }
1454
+ /** Exact below 1,000 (3.9 cores), compact above (12k req/s). */
1455
+ const num = (x) => Math.abs(x) >= 1e3 ? compact(x) : fmt(x);
1456
+ const sig = (x) => Number(x.toPrecision(3)).toString();
1457
+ // src/scenarios.tsx
1458
+ /** Scenario identity colours, in declaration order; a fifth and later scenario is drawn muted. */
1459
+ const SERIES = [
1460
+ "var(--lm-s1)",
1461
+ "var(--lm-s2)",
1462
+ "var(--lm-s3)",
1463
+ "var(--lm-s4)"
1464
+ ];
1465
+ /** The colour of a scenario by label; values of the reader's own are drawn in the text colour. */
1466
+ function scenarioColor(model, label) {
1467
+ if (label == null) return "var(--lm-fg)";
1468
+ const i = model.scenarios.findIndex((s) => s.label === label);
1469
+ return SERIES[i] ?? "var(--lm-muted)";
1470
+ }
1471
+ const lineName = (l) => l.label ?? "These values";
1472
+ /** A month for a table cell or an axis: "Mar 2031"; "now" for a crossing already reached. */
1473
+ function when(model, x) {
1474
+ const d = model.dateAt(x);
1475
+ return d ? monthOf(d, true) : x != null && x <= 1 && model.growth ? "now" : "";
1476
+ }
1477
+ /** The months of both edges: "Sep 2029–Feb 2030", or one month when they agree. */
1478
+ function whenRange(model, r) {
1479
+ if (!r) return "";
1480
+ const [lo, hi] = [when(model, r.low), when(model, r.high)];
1481
+ return !hi || lo === hi ? lo : `${lo}–${hi}`;
1482
+ }
1483
+ /** The comparison at the shown load: crossings do not depend on it, the verdicts do. */
1484
+ function useComparison(lm) {
1485
+ return useMemo(() => compare(lm.model, lm.values.load), [lm.model, lm.values.load]);
1486
+ }
1487
+ /** One button per scenario: a reader switches designs without touching the controls. The load stays. */
1488
+ function Scenarios({ lm }) {
1489
+ const { model } = lm;
1490
+ if (!model.scenarios.length) return null;
1491
+ return /* @__PURE__ */ jsxs("fieldset", {
1492
+ className: "lm-scenarios",
1493
+ children: [
1494
+ /* @__PURE__ */ jsx("legend", { children: "Scenario" }),
1495
+ model.scenarios.map((s) => /* @__PURE__ */ jsxs("button", {
1496
+ type: "button",
1497
+ "aria-pressed": lm.scenario?.label === s.label,
1498
+ onClick: () => lm.setScenario(s.label),
1499
+ children: [/* @__PURE__ */ jsx("i", { style: { background: scenarioColor(model, s.label) } }), s.label]
1500
+ }, s.label)),
1501
+ !lm.scenario && /* @__PURE__ */ jsx("span", {
1502
+ className: "lm-own",
1503
+ children: "your own values"
1504
+ })
1505
+ ]
1506
+ });
1507
+ }
1508
+ /** "+107 %" against the baseline; "same" within a rounding; nothing where either never runs out. */
1509
+ function change(x) {
1510
+ if (x == null || !Number.isFinite(x) || x === 0) return "";
1511
+ if (Math.abs(x - 1) < .005) return "same";
1512
+ return `${x > 1 ? "+" : "−"}${pct(Math.abs(x - 1))}`;
1513
+ }
1514
+ /** The scenarios side by side: which buys more headroom, where each first runs out, and per component. */
1515
+ function Compare({ lm, title = "Scenarios compared" }) {
1516
+ const { model } = lm;
1517
+ const c = useComparison(lm);
1518
+ if (c.rows.length < 2) return null;
1519
+ const target = `${pct(model.thresholds.target)} target`;
1520
+ 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) })] });
1521
+ return /* @__PURE__ */ jsxs("div", {
1522
+ className: "lm-card lm-compare",
1523
+ children: [
1524
+ /* @__PURE__ */ jsx("h3", { children: title }),
1525
+ /* @__PURE__ */ jsx("p", {
1526
+ className: "lm-compare-text",
1527
+ children: c.text
1528
+ }),
1529
+ /* @__PURE__ */ jsx("div", {
1530
+ className: "lm-table-wrap",
1531
+ children: /* @__PURE__ */ jsxs("table", {
1532
+ className: "lm-table",
1533
+ children: [/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [
1534
+ /* @__PURE__ */ jsx("th", {
1535
+ scope: "col",
1536
+ children: "Scenario"
1858
1537
  }),
1859
- c.capacity?.provenance === "estimated" ? /* @__PURE__ */ jsxs("span", {
1860
- className: "lm-tag",
1861
- "data-kind": "estimated",
1862
- children: ["estimate", c.capacity.within ? ` ${plusMinus(c.capacity)}` : ""]
1863
- }) : !!c.capacity?.within && /* @__PURE__ */ jsx("span", {
1864
- className: "lm-tag",
1865
- "data-kind": "range",
1866
- children: plusMinus(c.capacity)
1538
+ /* @__PURE__ */ jsx("th", {
1539
+ scope: "col",
1540
+ children: "Limited by"
1541
+ }),
1542
+ /* @__PURE__ */ jsx("th", {
1543
+ scope: "col",
1544
+ children: target
1545
+ }),
1546
+ /* @__PURE__ */ jsx("th", {
1547
+ scope: "col",
1548
+ children: "Runs out"
1867
1549
  })
1868
- ] }), /* @__PURE__ */ jsx("span", {
1869
- className: "lm-sub",
1870
- children: c.describe ?? (c.capacity ? `${fmt(c.capacity.value)} ${c.capacity.unit}` : "switched off")
1871
- })] }),
1872
- /* @__PURE__ */ jsxs("div", {
1873
- className: "lm-track",
1874
- role: "img",
1875
- "aria-label": `${c.name} at ${c.util == null ? "off" : pct(c.util)}`,
1550
+ ] }) }), /* @__PURE__ */ jsx("tbody", { children: c.rows.map((r) => /* @__PURE__ */ jsxs("tr", {
1551
+ "data-scenario": r.label,
1552
+ "aria-current": lm.scenario?.label === r.label || void 0,
1876
1553
  children: [
1877
- /* @__PURE__ */ jsx("div", {
1878
- className: "lm-fill",
1879
- "data-state": c.state,
1880
- style: { width: `${Math.min(100, (c.util ?? 0) / top * 100)}%` }
1554
+ /* @__PURE__ */ jsxs("th", {
1555
+ scope: "row",
1556
+ children: [/* @__PURE__ */ jsx("i", { style: { background: scenarioColor(model, r.label) } }), r.label]
1881
1557
  }),
1882
- /* @__PURE__ */ jsx("div", {
1883
- className: "lm-tick",
1884
- style: { left: at(model.thresholds.target) }
1558
+ /* @__PURE__ */ jsx("td", {
1559
+ className: "lm-text",
1560
+ children: r.firstLimit?.name ?? "—"
1885
1561
  }),
1886
- /* @__PURE__ */ jsx("div", {
1887
- className: "lm-tick",
1888
- style: { left: at(model.thresholds.full) }
1562
+ /* @__PURE__ */ jsx("td", {
1563
+ "data-multiple": r.target ?? "",
1564
+ "data-high": r.targetRange?.high ?? "",
1565
+ children: at(r.targetRange)
1566
+ }),
1567
+ /* @__PURE__ */ jsx("td", {
1568
+ "data-multiple": r.full ?? "",
1569
+ "data-high": r.fullRange?.high ?? "",
1570
+ children: at(r.fullRange)
1889
1571
  })
1890
1572
  ]
1891
- }),
1892
- /* @__PURE__ */ jsxs("div", {
1893
- className: "lm-val",
1894
- 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)}` })]
1895
- })
1896
- ]
1897
- }, c.id))
1898
- })
1899
- ] });
1573
+ }, r.label)) })]
1574
+ })
1575
+ }),
1576
+ /* @__PURE__ */ jsxs("h3", { children: [target, ", by component"] }),
1577
+ /* @__PURE__ */ jsx("div", {
1578
+ className: "lm-table-wrap",
1579
+ children: /* @__PURE__ */ jsxs("table", {
1580
+ className: "lm-table",
1581
+ children: [/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [/* @__PURE__ */ jsx("th", {
1582
+ scope: "col",
1583
+ children: "Component"
1584
+ }), c.rows.map((r) => /* @__PURE__ */ jsx("th", {
1585
+ scope: "col",
1586
+ children: r.label
1587
+ }, r.label))] }) }), /* @__PURE__ */ jsx("tbody", { children: model.componentIds.map((id, k) => /* @__PURE__ */ jsxs("tr", {
1588
+ "data-component": id,
1589
+ children: [/* @__PURE__ */ jsx("th", {
1590
+ scope: "row",
1591
+ children: c.rows[0].components[k].name
1592
+ }), c.rows.map((r, i) => {
1593
+ const x = r.components[k];
1594
+ return /* @__PURE__ */ jsxs("td", {
1595
+ "data-multiple": x.target ?? "",
1596
+ children: [x.targetRange == null ? "off" : multiples(x.targetRange, model.searchMax, true), i > 0 && change(x.change) && /* @__PURE__ */ jsx("small", { children: change(x.change) })]
1597
+ }, r.label);
1598
+ })]
1599
+ }, id)) })]
1600
+ })
1601
+ })
1602
+ ]
1603
+ });
1900
1604
  }
1901
- /**
1902
- * Live numbers: from the sim, lag and drops per queue, busy workers, rejected requests; from the model, pods running,
1903
- * cache answers and retries.
1904
- */
1905
- function Meters({ lm }) {
1906
- const [, tick] = useState(0);
1605
+ /** The size of an element in CSS pixels, kept current: a chart draws at its own size so text stays legible. */
1606
+ function useSize(fallback) {
1607
+ const ref = useRef(null);
1608
+ const [size, setSize] = useState({
1609
+ width: fallback,
1610
+ height: 0
1611
+ });
1907
1612
  useEffect(() => {
1908
- const t = setInterval(() => tick((x) => x + 1), 250);
1909
- return () => clearInterval(t);
1910
- }, []);
1911
- const { ev, engine, model } = lm;
1912
- const sim = engine.sim;
1913
- const flowLabel = (f) => model.def.flows[f]?.label ?? f;
1914
- const items = [];
1915
- for (const s of Object.values(ev.stages)) {
1916
- if (s.kind === "queue") for (const f of model.flowIds.filter((x) => ev.routes[x]?.includes(s.id))) {
1917
- const q = sim.queue(s.id, f);
1918
- const rules = ev.overload[f] ?? {};
1919
- items.push({
1920
- key: `${s.id}/${f}/lag`,
1921
- value: secs(q.lag),
1922
- label: `${flowLabel(f)} lag in ${s.label}`,
1923
- state: q.lag > 60 ? "over" : q.lag > 5 ? "warn" : "ok"
1924
- });
1925
- if (rules.merge) items.push({
1926
- key: `${s.id}/${f}/merge`,
1927
- value: compact(q.merged),
1928
- label: `${flowLabel(f)} superseded /s (${rules.merge.reason ?? "newest kept"})`,
1929
- state: q.merged > .5 ? "warn" : "ok"
1930
- });
1931
- if (rules.drop) items.push({
1932
- key: `${s.id}/${f}/drop`,
1933
- value: compact(q.dropped),
1934
- label: `${flowLabel(f)} dropped /s (${rules.drop.reason ?? "too old"})`,
1935
- state: q.dropped > .5 ? "over" : "ok"
1936
- });
1937
- }
1938
- if (s.kind === "workers") {
1939
- const b = sim.busy(s.id);
1940
- items.push({
1941
- key: `${s.id}/busy`,
1942
- value: pct(b),
1943
- label: `${s.label} busy`,
1944
- state: b > .95 ? "over" : b > .5 ? "warn" : "ok"
1945
- });
1946
- if (s.autoscale) items.push({
1947
- key: `${s.id}/pods`,
1948
- value: `${s.running} of ${s.pods}`,
1949
- label: `${s.label} pods running`,
1950
- state: s.running < s.pods ? "ok" : (ev.components[s.component]?.util ?? 0) > model.thresholds.full ? "over" : "warn"
1613
+ const el = ref.current;
1614
+ if (!el) return;
1615
+ const ro = new ResizeObserver(([e]) => {
1616
+ const width = Math.round(e?.contentRect.width ?? el.clientWidth);
1617
+ const height = Math.round(e?.contentRect.height ?? el.clientHeight);
1618
+ if (width > 0) setSize((s) => s.width === width && s.height === height ? s : {
1619
+ width,
1620
+ height
1951
1621
  });
1952
- }
1953
- if (s.kind === "cache") items.push({
1954
- key: `${s.id}/hits`,
1955
- value: compact(sim.arriving(s.id) * (1 - sim.shed(s.id)) * s.hit),
1956
- label: `answered at ${s.label} /s (${pct(s.hit)} hits)`,
1957
- state: "ok"
1958
- });
1959
- if ((s.kind === "pass" || s.kind === "limit" || s.kind === "cache") && sim.shed(s.id) > 0) items.push({
1960
- key: `${s.id}/shed`,
1961
- value: pct(sim.shed(s.id)),
1962
- label: `rejected at ${s.label}`,
1963
- state: "over"
1964
- });
1965
- }
1966
- for (const f of model.flowIds) {
1967
- const r = ev.retry[f];
1968
- if (!r || !(r.rate > 0)) continue;
1969
- const per = r.attempts / r.rate;
1970
- items.push({
1971
- key: `${f}/attempts`,
1972
- value: `${fmt(per)}×`,
1973
- label: `${flowLabel(f)} attempts per ${model.def.flows[f]?.unit ?? "unit"}`,
1974
- state: per > 1.05 ? "warn" : "ok"
1975
1622
  });
1976
- items.push({
1977
- key: `${f}/failed`,
1978
- value: pct(r.failed),
1979
- label: `${flowLabel(f)} failing after ${r.times} ${r.times === 1 ? "retry" : "retries"}`,
1980
- state: r.failed > .005 ? "over" : "ok"
1623
+ ro.observe(el);
1624
+ return () => ro.disconnect();
1625
+ }, []);
1626
+ return [ref, size];
1627
+ }
1628
+ /** Every scenario's line over the load: it depends on every value but the load, which is only the marker. */
1629
+ function useHeadroom(lm) {
1630
+ const { model, values } = lm;
1631
+ const rest = JSON.stringify({
1632
+ ...values,
1633
+ load: null
1634
+ });
1635
+ return useMemo(() => headroom(model, {
1636
+ ...values,
1637
+ load: model.load.default
1638
+ }), [model, rest]);
1639
+ }
1640
+ /**
1641
+ * The width of a label in the chart's 11 px monospace (`--lm-mono`), measured once the chart is on the page, so its
1642
+ * labels are kept inside it whatever the theme's font.
1643
+ */
1644
+ function useAxisMeasure(el) {
1645
+ const [measure, setMeasure] = useState(() => (text, _weight) => text.length * 6.7);
1646
+ useLayoutEffect(() => {
1647
+ const ctx = el.current && document.createElement("canvas").getContext("2d");
1648
+ if (!ctx) return;
1649
+ const font = getComputedStyle(el.current).getPropertyValue("--lm-mono").trim() || "monospace";
1650
+ setMeasure(() => (text, weight = 400) => {
1651
+ ctx.font = `${weight} 11px ${font}`;
1652
+ return ctx.measureText(text).width;
1981
1653
  });
1654
+ }, [el]);
1655
+ return measure;
1656
+ }
1657
+ /** 1, 2, 5, 10, 20, 50, … inside [from, to]; decades only when there is little room. */
1658
+ function ticks(from, to, roomy) {
1659
+ const out = [];
1660
+ for (let d = Math.floor(Math.log10(from)); d <= Math.ceil(Math.log10(to)); d++) for (const k of roomy ? [
1661
+ 1,
1662
+ 2,
1663
+ 5
1664
+ ] : [1]) {
1665
+ const v = k * 10 ** d;
1666
+ if (v >= from * .999 && v <= to * 1.001) out.push(Number(v.toPrecision(6)));
1982
1667
  }
1983
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("h3", { children: "Live" }), /* @__PURE__ */ jsx("div", {
1984
- className: "lm-meters",
1985
- children: items.map((m) => /* @__PURE__ */ jsxs("div", {
1986
- className: "lm-meter",
1987
- "data-state": m.state,
1988
- children: [/* @__PURE__ */ jsx("b", { children: m.value }), /* @__PURE__ */ jsx("span", {
1989
- title: m.label,
1990
- children: m.label
1991
- })]
1992
- }, m.key))
1993
- })] });
1668
+ return out;
1994
1669
  }
1995
- /** The load slider with its label and value. */
1996
- function LoadRange({ lm }) {
1997
- const load = lm.model.load;
1998
- const x = lm.values.load;
1999
- return /* @__PURE__ */ jsxs("label", {
2000
- className: "lm-range",
2001
- children: [/* @__PURE__ */ jsxs("span", { children: [
2002
- load.label,
2003
- " ",
2004
- /* @__PURE__ */ jsxs("output", { children: [fmt(x), "×"] })
2005
- ] }), /* @__PURE__ */ jsx("input", {
2006
- type: "range",
2007
- min: load.min,
2008
- max: load.max,
2009
- step: load.step,
2010
- value: x,
2011
- onChange: (e) => lm.setValues({ load: Number(e.target.value) })
2012
- })]
1670
+ /**
1671
+ * Utilization over the load multiple. Each scenario's line is its highest utilization, so it crosses the target and
1672
+ * 100 % exactly where its first limit does; the dots are those crossings, taken from the limits, not from the line.
1673
+ * With a ± on a capacity, a band shows the line at every capacity's low and high bound, and a bracket on the target
1674
+ * and 100 % lines spans where the band crosses them. The shown scenario's components are the thin lines under it.
1675
+ * Hover or arrow keys read every line at one load.
1676
+ */
1677
+ function HeadroomChart({ lm, title = "Headroom" }) {
1678
+ const { model, values } = lm;
1679
+ const h = useHeadroom(lm);
1680
+ const [wrap, { width }] = useSize(640);
1681
+ const [hover, setHover] = useState(null);
1682
+ const clip = useId().replace(/:/g, "");
1683
+ const measure = useAxisMeasure(wrap);
1684
+ const tip = useRef(null);
1685
+ useLayoutEffect(() => {
1686
+ const el = tip.current;
1687
+ if (el && hover != null) el.style.left = `${Math.max(0, Math.min(lx(xs[hover]) + 10, W - el.offsetWidth))}px`;
1688
+ });
1689
+ const dated = !!model.growth;
1690
+ const m = {
1691
+ l: 44,
1692
+ r: 14,
1693
+ t: 14,
1694
+ b: dated ? 40 : 26
1695
+ };
1696
+ const W = width;
1697
+ const H = Math.round(Math.min(300, Math.max(200, W * .45)));
1698
+ const pw = W - m.l - m.r;
1699
+ const ph = H - m.t - m.b;
1700
+ const top = Math.max(1.5, model.thresholds.full * 1.5);
1701
+ const lx = (x) => m.l + pw * Math.log(x / h.from) / Math.log(h.to / h.from);
1702
+ const ly = (u) => m.t + ph * (1 - Math.min(u, top * 1.2) / top);
1703
+ const path = (s) => {
1704
+ let d = "";
1705
+ let pen = false;
1706
+ for (const [x, u] of s) {
1707
+ if (u == null) {
1708
+ pen = false;
1709
+ continue;
1710
+ }
1711
+ d += `${pen ? "L" : "M"}${lx(x).toFixed(1)} ${ly(u).toFixed(1)}`;
1712
+ pen = true;
1713
+ }
1714
+ return d;
1715
+ };
1716
+ const xs = h.lines[0]?.envelope.map(([x]) => x) ?? [];
1717
+ const selected = h.lines.find((l) => l.selected);
1718
+ const roomy = W >= 480;
1719
+ const tickList = ticks(h.from, h.to, roomy);
1720
+ const labelled = (x) => roomy || Number.isInteger(Math.log10(x));
1721
+ const near = (px) => {
1722
+ let best = 0;
1723
+ for (let i = 1; i < xs.length; i++) if (Math.abs(lx(xs[i]) - px) < Math.abs(lx(xs[best]) - px)) best = i;
1724
+ return best;
1725
+ };
1726
+ const onMove = (e) => {
1727
+ const r = e.currentTarget.ownerSVGElement.getBoundingClientRect();
1728
+ setHover(near(e.clientX - r.left));
1729
+ };
1730
+ const onKey = (e) => {
1731
+ const i = hover ?? near(lx(Math.min(h.to, Math.max(h.from, values.load))));
1732
+ if (e.key === "ArrowRight" || e.key === "ArrowLeft") {
1733
+ e.preventDefault();
1734
+ setHover(Math.max(0, Math.min(xs.length - 1, i + (e.key === "ArrowRight" ? 1 : -1))));
1735
+ } else if (e.key === "Escape") setHover(null);
1736
+ };
1737
+ const area = (b) => {
1738
+ const both = b.upper.flatMap(([x, u], i) => {
1739
+ const v = b.lower[i][1];
1740
+ return u == null || v == null ? [] : [[
1741
+ x,
1742
+ u,
1743
+ v
1744
+ ]];
1745
+ });
1746
+ if (both.length < 2) return "";
1747
+ const up = both.map(([x, u]) => `${lx(x).toFixed(1)} ${ly(u).toFixed(1)}`);
1748
+ const down = both.map(([x, , v]) => `${lx(x).toFixed(1)} ${ly(v).toFixed(1)}`).reverse();
1749
+ return `M${up.join("L")}L${down.join("L")}Z`;
1750
+ };
1751
+ const reaches = (r, x) => r && l0(r) ? multiples(r, model.searchMax) : multiple(x, model.searchMax);
1752
+ const l0 = (r) => multiple(r.low, model.searchMax) !== multiple(r.high, model.searchMax);
1753
+ 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("; ");
1754
+ const loadX = lx(Math.min(h.to, Math.max(h.from, values.load)));
1755
+ const hx = hover == null ? null : xs[hover];
1756
+ const fromLeft = {
1757
+ x: 0,
1758
+ textAnchor: "start"
1759
+ };
1760
+ const fromRight = {
1761
+ x: W,
1762
+ textAnchor: "end"
1763
+ };
1764
+ /** A label beside a line at x: on the side it prefers if it fits, else the other, else against the nearer edge. */
1765
+ const beside = (x, w, prefer, gap = 4) => {
1766
+ const right = {
1767
+ x: x + gap,
1768
+ textAnchor: "start"
1769
+ };
1770
+ const left = {
1771
+ x: x - gap,
1772
+ textAnchor: "end"
1773
+ };
1774
+ const fitsRight = x + gap + w <= W;
1775
+ const fitsLeft = x - gap - w >= 0;
1776
+ if (prefer === "right" ? fitsRight : !fitsLeft && fitsRight) return right;
1777
+ if (fitsLeft) return left;
1778
+ return x < W / 2 ? fromLeft : fromRight;
1779
+ };
1780
+ /** A label centred on x, unless that passes an edge. */
1781
+ const centred = (x, w) => x - w / 2 < 0 ? fromLeft : x + w / 2 > W ? fromRight : {
1782
+ x,
1783
+ textAnchor: "middle"
1784
+ };
1785
+ const shown = `shown: ${fmt(values.load)}×`;
1786
+ /** A crossing's multiple, left of its dot where it fits. */
1787
+ const mark = (t, x, y) => /* @__PURE__ */ jsx("text", {
1788
+ ...beside(x, measure(t, 600), "left", 6),
1789
+ y,
1790
+ className: "lm-mark",
1791
+ children: t
2013
1792
  });
2014
- }
2015
- /** The load slider, the presets and every parameter, greyed out where it does not apply. */
2016
- function Controls({ lm }) {
2017
- const { model, values, setValues, ev } = lm;
2018
- const v = values;
2019
1793
  return /* @__PURE__ */ jsxs("div", {
2020
- className: "lm-card lm-controls",
1794
+ className: "lm-card lm-headroom",
2021
1795
  children: [
2022
- /* @__PURE__ */ jsx("h3", { children: "Load" }),
2023
- /* @__PURE__ */ jsx(LoadRange, { lm }),
2024
- /* @__PURE__ */ jsx("div", {
2025
- className: "lm-presets",
2026
- children: ev.presets.map((p) => {
2027
- const on = Object.entries(p.values).every(([k, x]) => v[k] === x);
2028
- return /* @__PURE__ */ jsx("button", {
2029
- type: "button",
2030
- "aria-pressed": on,
2031
- onClick: () => setValues(p.values),
2032
- children: p.label
2033
- }, p.label);
2034
- })
1796
+ /* @__PURE__ */ jsx("h3", { children: title }),
1797
+ h.lines.length > 1 && /* @__PURE__ */ jsxs("div", {
1798
+ className: "lm-legend",
1799
+ children: [h.lines.map((l) => /* @__PURE__ */ jsxs("span", { children: [/* @__PURE__ */ jsx("b", {
1800
+ className: "lm-key",
1801
+ style: { background: scenarioColor(model, l.label) }
1802
+ }), lineName(l)] }, lineName(l))), selected && /* @__PURE__ */ jsxs("span", { children: ["thin lines: each component of ", lineName(selected)] })]
2035
1803
  }),
2036
- model.params.length > 1 && /* @__PURE__ */ jsx("h3", { children: "Design" }),
2037
- model.params.map(({ id, def }) => {
2038
- if (def.kind === "load") return null;
2039
- const enabled = model.isEnabled(id, v);
2040
- const tag = def.tag && /* @__PURE__ */ jsx("span", {
2041
- className: "lm-tag",
2042
- "data-kind": "estimated",
2043
- children: def.tag
2044
- });
2045
- if (def.kind === "switch") return /* @__PURE__ */ jsxs("label", {
2046
- className: `lm-switch${enabled ? "" : " lm-off"}`,
1804
+ /* @__PURE__ */ jsxs("div", {
1805
+ className: "lm-chart",
1806
+ ref: wrap,
1807
+ role: "slider",
1808
+ "aria-label": `Utilization over the load multiple. ${summary}.`,
1809
+ "aria-valuemin": h.from,
1810
+ "aria-valuemax": h.to,
1811
+ "aria-valuenow": hx ?? values.load,
1812
+ "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(", ")}`,
1813
+ tabIndex: 0,
1814
+ onKeyDown: onKey,
1815
+ onBlur: () => setHover(null),
1816
+ children: [/* @__PURE__ */ jsxs("svg", {
1817
+ width: W,
1818
+ height: H,
1819
+ viewBox: `0 0 ${W} ${H}`,
1820
+ "aria-hidden": "true",
2047
1821
  children: [
2048
- /* @__PURE__ */ jsx("input", {
2049
- type: "checkbox",
2050
- checked: Boolean(v[id]),
2051
- disabled: !enabled,
2052
- onChange: (e) => setValues({ [id]: e.target.checked })
1822
+ /* @__PURE__ */ jsx("defs", { children: /* @__PURE__ */ jsx("clipPath", {
1823
+ id: clip,
1824
+ children: /* @__PURE__ */ jsx("rect", {
1825
+ x: m.l,
1826
+ y: m.t,
1827
+ width: pw,
1828
+ height: ph + 2
1829
+ })
1830
+ }) }),
1831
+ [
1832
+ 0,
1833
+ model.thresholds.target,
1834
+ model.thresholds.full
1835
+ ].map((u) => /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("line", {
1836
+ x1: m.l,
1837
+ x2: W - m.r,
1838
+ y1: ly(u),
1839
+ y2: ly(u),
1840
+ stroke: "var(--lm-line)"
1841
+ }), /* @__PURE__ */ jsx("text", {
1842
+ x: m.l - 6,
1843
+ y: ly(u) + 4,
1844
+ textAnchor: "end",
1845
+ className: "lm-axis",
1846
+ children: pct(u)
1847
+ })] }, u)),
1848
+ /* @__PURE__ */ jsx("text", {
1849
+ x: W - m.r,
1850
+ y: ly(model.thresholds.target) - 5,
1851
+ textAnchor: "end",
1852
+ className: "lm-axis",
1853
+ children: "target"
2053
1854
  }),
2054
- /* @__PURE__ */ jsxs("span", { children: [def.label, tag] }),
2055
- def.hint && /* @__PURE__ */ jsx("small", { children: def.hint })
2056
- ]
2057
- }, id);
2058
- if (def.kind === "select") return /* @__PURE__ */ jsxs("label", {
2059
- className: `lm-select${enabled ? "" : " lm-off"}`,
2060
- children: [
2061
- /* @__PURE__ */ jsxs("span", { children: [def.label, tag] }),
2062
- /* @__PURE__ */ jsx("select", {
2063
- value: String(v[id]),
2064
- disabled: !enabled,
2065
- onChange: (e) => {
2066
- const opt = def.options.find((o) => String(o) === e.target.value);
2067
- setValues({ [id]: opt });
2068
- },
2069
- children: def.options.map((o) => /* @__PURE__ */ jsx("option", {
2070
- value: String(o),
2071
- children: def.format ? def.format(o) : String(o)
2072
- }, String(o)))
1855
+ tickList.map((x) => {
1856
+ const label = `${fmt(x)}×`;
1857
+ const date = dated && x > 1 ? when(model, x) : "";
1858
+ return /* @__PURE__ */ jsxs("g", {
1859
+ className: "lm-axis",
1860
+ children: [/* @__PURE__ */ jsx("line", {
1861
+ x1: lx(x),
1862
+ x2: lx(x),
1863
+ y1: m.t + ph,
1864
+ y2: m.t + ph + 4,
1865
+ stroke: "var(--lm-line)"
1866
+ }), labelled(x) && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("text", {
1867
+ ...centred(lx(x), measure(label)),
1868
+ y: m.t + ph + 16,
1869
+ children: label
1870
+ }), date && /* @__PURE__ */ jsx("text", {
1871
+ ...centred(lx(x), measure(date)),
1872
+ y: m.t + ph + 30,
1873
+ children: date
1874
+ })] })]
1875
+ }, x);
1876
+ }),
1877
+ /* @__PURE__ */ jsxs("g", {
1878
+ clipPath: `url(#${clip})`,
1879
+ children: [
1880
+ [...h.lines].sort((a, b) => Number(a.selected) - Number(b.selected)).map((l) => l.band ? /* @__PURE__ */ jsx("path", {
1881
+ "data-band": lineName(l),
1882
+ d: area(l.band),
1883
+ fill: scenarioColor(model, l.label),
1884
+ fillOpacity: l.selected ? .2 : .08
1885
+ }, lineName(l)) : null),
1886
+ selected?.components.map((c) => /* @__PURE__ */ jsx("path", {
1887
+ d: path(c.points),
1888
+ fill: "none",
1889
+ stroke: "var(--lm-muted)",
1890
+ strokeOpacity: ".55",
1891
+ strokeWidth: "1"
1892
+ }, c.id)),
1893
+ [...h.lines].sort((a, b) => Number(a.selected) - Number(b.selected)).map((l) => /* @__PURE__ */ jsx("path", {
1894
+ "data-line": lineName(l),
1895
+ d: path(l.envelope),
1896
+ fill: "none",
1897
+ stroke: scenarioColor(model, l.label),
1898
+ strokeWidth: "2",
1899
+ strokeLinejoin: "round",
1900
+ strokeLinecap: "round"
1901
+ }, lineName(l)))
1902
+ ]
1903
+ }),
1904
+ /* @__PURE__ */ jsx("line", {
1905
+ x1: loadX,
1906
+ x2: loadX,
1907
+ y1: m.t,
1908
+ y2: m.t + ph,
1909
+ stroke: "var(--lm-fg)",
1910
+ strokeOpacity: ".45"
1911
+ }),
1912
+ /* @__PURE__ */ jsx("text", {
1913
+ ...beside(loadX, measure(shown), "right"),
1914
+ y: m.t + 10,
1915
+ className: "lm-axis",
1916
+ children: shown
1917
+ }),
1918
+ h.lines.flatMap((l) => [[
1919
+ "target",
1920
+ l.targetRange,
1921
+ model.thresholds.target
1922
+ ], [
1923
+ "full",
1924
+ l.fullRange,
1925
+ model.thresholds.full
1926
+ ]].map(([kind, r, u]) => {
1927
+ if (!l.band || !r || !Number.isFinite(r.low) || r.low > h.to) return null;
1928
+ const [x1, x2] = [lx(Math.max(h.from, r.low)), lx(Math.min(h.to, r.high))];
1929
+ const y = ly(u);
1930
+ return /* @__PURE__ */ jsxs("g", {
1931
+ "data-range": kind,
1932
+ "data-scenario": lineName(l),
1933
+ "data-low": r.low,
1934
+ "data-high": r.high,
1935
+ stroke: scenarioColor(model, l.label),
1936
+ strokeWidth: l.selected ? 3 : 2,
1937
+ strokeOpacity: l.selected ? 1 : .6,
1938
+ children: [
1939
+ /* @__PURE__ */ jsx("line", {
1940
+ x1,
1941
+ x2,
1942
+ y1: y,
1943
+ y2: y
1944
+ }),
1945
+ /* @__PURE__ */ jsx("line", {
1946
+ x1,
1947
+ x2: x1,
1948
+ y1: y - 5,
1949
+ y2: y + 5
1950
+ }),
1951
+ Number.isFinite(r.high) && r.high <= h.to && /* @__PURE__ */ jsx("line", {
1952
+ x1: x2,
1953
+ x2,
1954
+ y1: y - 5,
1955
+ y2: y + 5
1956
+ })
1957
+ ]
1958
+ }, `${lineName(l)}/${kind}/range`);
1959
+ })),
1960
+ h.lines.flatMap((l) => [[
1961
+ "target",
1962
+ l.target,
1963
+ l.targetRange,
1964
+ model.thresholds.target
1965
+ ], [
1966
+ "full",
1967
+ l.full,
1968
+ l.fullRange,
1969
+ model.thresholds.full
1970
+ ]].map(([kind, x, r, u]) => x != null && Number.isFinite(x) && x >= h.from && x <= h.to ? /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("circle", {
1971
+ "data-crossing": kind,
1972
+ "data-scenario": lineName(l),
1973
+ "data-multiple": x,
1974
+ cx: lx(x),
1975
+ cy: ly(u),
1976
+ r: "4",
1977
+ fill: scenarioColor(model, l.label),
1978
+ stroke: "var(--lm-surface)",
1979
+ strokeWidth: "2"
1980
+ }), 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)),
1981
+ hx != null && /* @__PURE__ */ jsx("line", {
1982
+ x1: lx(hx),
1983
+ x2: lx(hx),
1984
+ y1: m.t,
1985
+ y2: m.t + ph,
1986
+ stroke: "var(--lm-fg)",
1987
+ strokeOpacity: ".8"
2073
1988
  }),
2074
- def.hint && /* @__PURE__ */ jsx("small", { children: def.hint })
1989
+ /* @__PURE__ */ jsx("rect", {
1990
+ x: m.l,
1991
+ y: m.t,
1992
+ width: pw,
1993
+ height: ph,
1994
+ fill: "transparent",
1995
+ onPointerMove: onMove,
1996
+ onPointerDown: onMove,
1997
+ onPointerLeave: () => setHover(null)
1998
+ })
2075
1999
  ]
2076
- }, id);
2077
- return /* @__PURE__ */ jsxs("label", {
2078
- className: `lm-range${enabled ? "" : " lm-off"}`,
2000
+ }), hover != null && hx != null && /* @__PURE__ */ jsxs("div", {
2001
+ className: "lm-tip",
2002
+ role: "status",
2003
+ ref: tip,
2004
+ style: {
2005
+ left: lx(hx) + 10,
2006
+ top: m.t
2007
+ },
2079
2008
  children: [
2080
- /* @__PURE__ */ jsxs("span", { children: [
2081
- def.label,
2082
- tag,
2083
- " ",
2084
- /* @__PURE__ */ jsx("output", { children: def.format ? def.format(v[id]) : fmt(v[id]) })
2009
+ /* @__PURE__ */ jsxs("b", { children: [
2010
+ fmt(hx),
2011
+ "×",
2012
+ when(model, hx) && ` · ${when(model, hx)}`
2085
2013
  ] }),
2086
- /* @__PURE__ */ jsx("input", {
2087
- type: "range",
2088
- min: def.min,
2089
- max: def.max,
2090
- step: def.step,
2091
- value: v[id],
2092
- disabled: !enabled,
2093
- onChange: (e) => setValues({ [id]: Number(e.target.value) })
2094
- }),
2095
- def.hint && /* @__PURE__ */ jsx("small", { children: def.hint })
2014
+ h.lines.map((l) => /* @__PURE__ */ jsxs("span", { children: [
2015
+ /* @__PURE__ */ jsx("b", {
2016
+ className: "lm-key",
2017
+ style: { background: scenarioColor(model, l.label) }
2018
+ }),
2019
+ /* @__PURE__ */ jsx("strong", { children: l.envelope[hover][1] == null ? "off" : pct(l.envelope[hover][1]) }),
2020
+ " ",
2021
+ lineName(l)
2022
+ ] }, lineName(l))),
2023
+ selected?.components.map((c) => /* @__PURE__ */ jsxs("span", {
2024
+ className: "lm-sub",
2025
+ children: [
2026
+ /* @__PURE__ */ jsx("strong", { children: c.points[hover][1] == null ? "off" : pct(c.points[hover][1]) }),
2027
+ " ",
2028
+ c.name
2029
+ ]
2030
+ }, c.id))
2096
2031
  ]
2097
- }, id);
2032
+ })]
2098
2033
  })
2099
2034
  ]
2100
2035
  });
2101
2036
  }
2102
- /** What the model assumes: every capacity with its provenance, every fit, and anything the page adds. */
2103
- function Assumptions({ lm, extra = [] }) {
2104
- return /* @__PURE__ */ jsxs("div", {
2105
- className: "lm-card",
2106
- children: [/* @__PURE__ */ jsx("h3", { children: "What this assumes" }), /* @__PURE__ */ jsxs("ul", {
2107
- className: "lm-facts",
2108
- 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}`))]
2109
- })]
2110
- });
2111
- }
2112
- function describe(a) {
2113
- if (a.kind === "capacity") {
2114
- const c = a.capacity;
2115
- return /* @__PURE__ */ jsxs(Fragment, { children: [
2116
- /* @__PURE__ */ jsxs("b", { children: [a.name, ":"] }),
2117
- " ",
2118
- fmt(c.value),
2119
- " ",
2120
- c.unit,
2121
- c.within ? ` ${plusMinus(c)}` : "",
2122
- ",",
2123
- " ",
2124
- /* @__PURE__ */ jsx("span", {
2125
- className: "lm-prov",
2126
- "data-kind": c.provenance,
2127
- children: c.provenance
2128
- }),
2129
- c.source ? ` (${c.source})` : "",
2130
- "."
2131
- ] });
2132
- }
2133
- const f = a.fit;
2134
- return /* @__PURE__ */ jsxs(Fragment, { children: [
2135
- /* @__PURE__ */ jsxs("b", { children: [a.name, ":"] }),
2136
- " ",
2137
- f.y,
2138
- " = ",
2139
- sig(f.a),
2140
- " + ",
2141
- sig(f.b),
2142
- " × ",
2143
- f.x,
2144
- ", r² ",
2145
- f.r2.toFixed(3),
2146
- " over ",
2147
- f.n,
2148
- " points,",
2149
- " ",
2150
- /* @__PURE__ */ jsx("span", {
2151
- className: "lm-prov",
2152
- "data-kind": "measured",
2153
- children: "measured"
2154
- }),
2155
- f.source ? ` (${f.source})` : "",
2156
- "."
2157
- ] });
2158
- }
2159
- /** Exact below 1,000 (3.9 cores), compact above (12k req/s). */
2160
- const num = (x) => Math.abs(x) >= 1e3 ? compact(x) : fmt(x);
2161
- const sig = (x) => Number(x.toPrecision(3)).toString();
2162
- // src/compact.tsx
2163
- /** The names a reader sees for the panels, on the tabs and the buttons that open them. */
2164
- const NAMES = {
2165
- verdict: "Verdict",
2166
- live: "Live",
2167
- limits: "Limits",
2168
- controls: "Load",
2169
- headroom: "Headroom",
2170
- compare: "Compare",
2171
- assumptions: "Assumptions"
2172
- };
2173
- /**
2174
- * The verdict in one line, from the same evaluation as the sentence: the load, how far the target holds, the first
2175
- * limit and how sure its capacity is, what is past capacity. The sentence is its tooltip and opens under "Why".
2176
- */
2177
- function VerdictLine({ lm, verdict = true, extra = 0, open, assumptions }) {
2178
- const { ev, model, values } = lm;
2179
- const first = ev.firstLimit;
2180
- const range = ev.target;
2181
- const target = `${pct(model.thresholds.target)} target`;
2182
- const c = first?.capacity;
2183
- const sure = !c ? "" : c.provenance === "estimated" ? `est${c.within ? ` ${plusMinus(c)}` : ""}` : plusMinus(c);
2184
- const over = ev.ranked.filter((x) => (x.util ?? 0) > model.thresholds.full);
2185
- const when = range ? whenRange(model, range) : "";
2186
- const estimated = ev.assumptions.filter((a) => a.kind === "capacity" && a.capacity.provenance === "estimated").length;
2187
- return /* @__PURE__ */ jsxs(Fragment, { children: [
2188
- verdict && /* @__PURE__ */ jsx("p", {
2189
- className: "lm-headline",
2190
- title: ev.verdict.text,
2191
- "aria-live": "polite",
2192
- children: !first || !range ? ev.verdict.text : /* @__PURE__ */ jsxs(Fragment, { children: [
2193
- /* @__PURE__ */ jsxs("b", {
2194
- className: "lm-num",
2195
- children: [fmt(values.load), "×"]
2196
- }),
2197
- " ·",
2198
- " ",
2199
- values.load < range.low ? /* @__PURE__ */ jsxs(Fragment, { children: [
2200
- "the ",
2201
- target,
2202
- " holds to ",
2203
- /* @__PURE__ */ jsx("b", {
2204
- className: "lm-num",
2205
- children: multiples(range, model.searchMax, true)
2206
- }),
2207
- when && ` (${when})`
2208
- ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
2209
- "past the ",
2210
- target,
2211
- " from ",
2212
- /* @__PURE__ */ jsx("b", {
2213
- className: "lm-num",
2214
- children: multiple(range.low, model.searchMax)
2215
- })
2216
- ] }),
2217
- " ",
2218
- "· limited by ",
2219
- /* @__PURE__ */ jsx("b", { children: first.name }),
2220
- sure && /* @__PURE__ */ jsx("span", {
2221
- className: "lm-tag",
2222
- "data-kind": c?.provenance === "estimated" ? "estimated" : "range",
2223
- children: sure
2224
- }),
2225
- over.length > 0 && /* @__PURE__ */ jsxs(Fragment, { children: [
2226
- " ",
2227
- "· ",
2228
- /* @__PURE__ */ jsx("b", { children: over.map((x) => x.name).join(", ") }),
2229
- " past capacity"
2230
- ] })
2231
- ] })
2232
- }),
2233
- open && verdict && /* @__PURE__ */ jsx("button", {
2234
- type: "button",
2235
- className: "lm-link",
2236
- onClick: (e) => open("verdict", e.currentTarget),
2237
- children: "Why ›"
2238
- }),
2239
- open && assumptions && /* @__PURE__ */ jsxs("button", {
2240
- type: "button",
2241
- className: "lm-link",
2242
- onClick: (e) => open("assumptions", e.currentTarget),
2243
- children: [
2244
- "What this assumes · ",
2245
- ev.assumptions.length + extra,
2246
- estimated > 0 && ` (${estimated} estimated)`,
2247
- " ›"
2248
- ]
2249
- })
2250
- ] });
2251
- }
2252
- /** The order of the cards in the dock: what the reader changes first, what it changes next to it. */
2253
- const DOCK = [
2254
- "controls",
2255
- "live",
2256
- "limits",
2257
- "headroom",
2258
- "compare"
2259
- ];
2260
- /**
2261
- * Full screen's panels, compact, side by side in a box the screen sizes: what does not fit is left out whole, and
2262
- * each card opens its panel whole. A phone shows one at a time, under tabs.
2263
- */
2264
- function Dock({ lm, panels, open }) {
2265
- const shown = DOCK.filter((p) => panels.includes(p));
2266
- const [tab, setTab] = useState(null);
2267
- if (!shown.length) return null;
2268
- const active = tab && shown.includes(tab) ? tab : shown[0];
2269
- return /* @__PURE__ */ jsxs("div", {
2270
- className: "lm-dock",
2271
- children: [/* @__PURE__ */ jsx("fieldset", {
2272
- className: "lm-tabs",
2273
- "aria-label": "Panels",
2274
- children: shown.map((p) => /* @__PURE__ */ jsx("button", {
2275
- type: "button",
2276
- "aria-pressed": p === active,
2277
- onClick: () => setTab(p),
2278
- children: NAMES[p]
2279
- }, p))
2280
- }), shown.map((p) => /* @__PURE__ */ jsx(Card, {
2281
- lm,
2282
- panel: p,
2283
- open,
2284
- active: p === active
2285
- }, p))]
2286
- });
2287
- }
2288
- function Card({ lm, panel, open, active }) {
2289
- const box = useRef(null);
2290
- const more = useRef(null);
2291
- useClip(box, more);
2292
- return /* @__PURE__ */ jsxs("div", {
2293
- className: "lm-mini",
2294
- "data-mini": panel,
2295
- "data-active": active || void 0,
2296
- ref: box,
2297
- children: [panel === "controls" ? /* @__PURE__ */ jsx(Controls, { lm }) : panel === "compare" ? /* @__PURE__ */ jsx(Compare, { lm }) : /* @__PURE__ */ jsx("div", {
2298
- className: "lm-card",
2299
- 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 })] })
2300
- }), /* @__PURE__ */ jsx("button", {
2301
- type: "button",
2302
- className: "lm-more",
2303
- ref: more,
2304
- "aria-label": `${NAMES[panel]}, all of it`,
2305
- onClick: (e) => open(panel, e.currentTarget),
2306
- children: "›"
2307
- })]
2308
- });
2309
- }
2310
- /** The rows a card leaves out whole when they do not fit. */
2311
- const ROWS = ".lm-meter, .lm-mini-lim, .lm-controls > *, .lm-table tbody tr";
2312
- /**
2313
- * Hides the rows that cross the bottom of the card, and counts them on its button. Runs again when the card's size
2314
- * or its rows change: the meters come and go with the load, and the order of the limits with it.
2315
- */
2316
- function useClip(box, more) {
2317
- useEffect(() => {
2318
- const card = box.current?.querySelector(".lm-card");
2319
- if (!card) return;
2320
- const clip = () => {
2321
- const r = card.getBoundingClientRect();
2322
- const bottom = r.bottom - Number.parseFloat(getComputedStyle(card).paddingBottom || "0");
2323
- let n = 0;
2324
- for (const row of card.querySelectorAll(ROWS)) {
2325
- const out = r.height > 0 && row.getBoundingClientRect().bottom > bottom + .5;
2326
- row.toggleAttribute("data-clip", out);
2327
- if (out && !row.matches("h3")) n++;
2328
- }
2329
- if (more.current) more.current.dataset.more = n ? `+${n}` : "";
2330
- };
2331
- const ro = new ResizeObserver(clip);
2332
- ro.observe(card);
2333
- const mo = new MutationObserver(clip);
2334
- mo.observe(card, {
2335
- childList: true,
2336
- subtree: true
2337
- });
2338
- clip();
2339
- return () => {
2340
- ro.disconnect();
2341
- mo.disconnect();
2342
- };
2343
- }, [box, more]);
2344
- }
2345
- /**
2346
- * The limits in their order, a line each: the name and how sure its capacity is, the bar, the utilization, where it
2347
- * is full. The first is the first limit: the verdict line names it.
2348
- */
2349
- function MiniLimits({ lm }) {
2350
- const { ev, model } = lm;
2351
- const top = Math.max(1.5, model.thresholds.full * 1.5);
2352
- const at = (u) => `${u / top * 100}%`;
2353
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("h3", { children: "Where it runs out" }), /* @__PURE__ */ jsx("div", {
2354
- className: "lm-mini-limits",
2355
- children: ev.ranked.map((c) => /* @__PURE__ */ jsxs("div", {
2356
- className: "lm-mini-lim",
2357
- "data-component": c.id,
2358
- children: [
2359
- /* @__PURE__ */ jsxs("span", {
2360
- className: "lm-name",
2361
- title: c.name,
2362
- children: [c.name, c.capacity?.provenance === "estimated" ? /* @__PURE__ */ jsx("span", {
2363
- className: "lm-tag",
2364
- "data-kind": "estimated",
2365
- children: "est"
2366
- }) : !!c.capacity?.within && /* @__PURE__ */ jsx("span", {
2367
- className: "lm-tag",
2368
- "data-kind": "range",
2369
- children: "±"
2370
- })]
2371
- }),
2372
- /* @__PURE__ */ jsxs("span", {
2373
- className: "lm-track",
2374
- role: "img",
2375
- "aria-label": `${c.name} at ${c.util == null ? "off" : pct(c.util)}`,
2376
- children: [
2377
- /* @__PURE__ */ jsx("span", {
2378
- className: "lm-fill",
2379
- "data-state": c.state,
2380
- style: { width: `${Math.min(100, (c.util ?? 0) / top * 100)}%` }
2381
- }),
2382
- /* @__PURE__ */ jsx("span", {
2383
- className: "lm-tick",
2384
- style: { left: at(model.thresholds.target) }
2385
- }),
2386
- /* @__PURE__ */ jsx("span", {
2387
- className: "lm-tick",
2388
- style: { left: at(model.thresholds.full) }
2389
- })
2390
- ]
2391
- }),
2392
- /* @__PURE__ */ jsx("span", {
2393
- className: "lm-val",
2394
- children: c.util == null ? "—" : pct(c.util)
2395
- }),
2396
- /* @__PURE__ */ jsx("span", {
2397
- className: "lm-val lm-sub",
2398
- 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)}`
2399
- })
2400
- ]
2401
- }, c.id))
2402
- })] });
2403
- }
2404
- /** The headroom chart as a sparkline: each scenario's line, the target, the load; where the shown one crosses it. */
2405
- function Sparkline({ lm }) {
2406
- const { model, values } = lm;
2407
- const h = useHeadroom(lm);
2408
- const [box, { width: W, height: H }] = useSize(240);
2409
- const top = Math.max(1.5, model.thresholds.full * 1.5);
2410
- const lx = (x) => W * Math.log(x / h.from) / Math.log(h.to / h.from);
2411
- const ly = (u) => 8 + (H - 10) * (1 - Math.min(u, top * 1.2) / top);
2412
- const path = (s) => {
2413
- let d = "";
2414
- let pen = false;
2415
- for (const [x, u] of s) {
2416
- if (u == null) {
2417
- pen = false;
2418
- continue;
2419
- }
2420
- d += `${pen ? "L" : "M"}${lx(x).toFixed(1)} ${ly(u).toFixed(1)}`;
2421
- pen = true;
2422
- }
2423
- return d;
2424
- };
2425
- const line = h.lines.find((l) => l.selected) ?? h.lines[0];
2426
- const target = pct(model.thresholds.target);
2427
- const reaches = line ? `${line.targetRange ? multiples(line.targetRange, model.searchMax, true) : multiple(line.target, model.searchMax)}` : "";
2428
- const when = line ? whenRange(model, line.targetRange) : "";
2429
- const loadX = lx(Math.min(h.to, Math.max(h.from, values.load)));
2430
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("div", {
2431
- className: "lm-spark",
2432
- ref: box,
2433
- children: H > 0 && /* @__PURE__ */ jsxs("svg", {
2434
- width: W,
2435
- height: H,
2436
- "aria-hidden": "true",
2437
- children: [
2438
- /* @__PURE__ */ jsx("line", {
2439
- className: "lm-spark-th",
2440
- x1: 0,
2441
- x2: W,
2442
- y1: ly(model.thresholds.target),
2443
- y2: ly(model.thresholds.target)
2444
- }),
2445
- h.lines.map((l) => /* @__PURE__ */ jsx("path", {
2446
- d: path(l.envelope),
2447
- fill: "none",
2448
- stroke: scenarioColor(model, l.label),
2449
- strokeWidth: l.selected ? 2 : 1.25
2450
- }, l.label ?? "")),
2451
- /* @__PURE__ */ jsx("line", {
2452
- className: "lm-spark-load",
2453
- x1: loadX,
2454
- x2: loadX,
2455
- y1: 0,
2456
- y2: H
2457
- })
2458
- ]
2459
- })
2460
- }), line && /* @__PURE__ */ jsxs("p", {
2461
- className: "lm-spark-text",
2462
- title: `${line.label ?? "It"} reaches the ${target} target at ${reaches}`,
2463
- children: [
2464
- line.label ?? "It",
2465
- " reaches the ",
2466
- target,
2467
- " target at ",
2468
- reaches,
2469
- when && ` (${when})`,
2470
- "."
2471
- ]
2472
- })] });
2473
- }
2474
2037
  // src/story.tsx
2475
2038
  /**
2476
2039
  * The model's story, a step at a time: the step's text, where it is, play, back and next. ← and → move through it
@@ -2935,6 +2498,10 @@ var Engine = class {
2935
2498
  reducedMotion = false;
2936
2499
  /** The part of the scene the board shows while the story plays; null for all of it. */
2937
2500
  camera = null;
2501
+ /** The reader's view of a board they pan and zoom; null where the board only shows what the camera frames. */
2502
+ viewer = null;
2503
+ /** Changes with what the board shows: the zoom controls and a box's detail follow it. */
2504
+ viewId = 0;
2938
2505
  /** What the diagram says about the step the story plays; null when it does not play. */
2939
2506
  cue = null;
2940
2507
  host = null;
@@ -3121,6 +2688,7 @@ var Engine = class {
3121
2688
  */
3122
2689
  playStory(from) {
3123
2690
  if (!this.frame || !this.model.story[from]) return false;
2691
+ const lead = this.viewer?.lead();
3124
2692
  this.#story = {
3125
2693
  i: from - 1,
3126
2694
  shot: "establish",
@@ -3132,9 +2700,10 @@ var Engine = class {
3132
2700
  components: [],
3133
2701
  before: this.ev,
3134
2702
  waiting: false,
3135
- hand: null
2703
+ hand: null,
2704
+ lead
3136
2705
  };
3137
- this.#setCamera(null);
2706
+ this.#setCamera(lead ?? null);
3138
2707
  this.host?.playing(true);
3139
2708
  return true;
3140
2709
  }
@@ -3200,6 +2769,7 @@ var Engine = class {
3200
2769
  const to = framing(frame, this.#boxesOf(s.hand?.to));
3201
2770
  cam = cut ? to : between(s.from, to, s.t / 1);
3202
2771
  } else if (s.shot === "out" || s.shot === "back") cam = cut ? all : between(s.from, all, p);
2772
+ else if (s.shot === "establish" && s.lead && !cut && s.t < SHOTS.back) cam = between(s.lead, all, s.t / SHOTS.back);
3203
2773
  else cam = all;
3204
2774
  this.#setCamera(cam);
3205
2775
  const h = this.#hand;
@@ -3303,13 +2873,23 @@ var Engine = class {
3303
2873
  this.camera = !cam || all ? null : cam;
3304
2874
  this.applyCamera();
3305
2875
  }
3306
- /** Points the SVG at the camera: React draws the whole scene's viewBox, the camera replaces it after each render. */
2876
+ /**
2877
+ * Points the SVG at what the board shows: the camera, under the reader's view where they pan and zoom. React draws the
2878
+ * whole scene's viewBox; this replaces it after each render.
2879
+ */
3307
2880
  applyCamera() {
3308
2881
  const f = this.frame;
3309
2882
  if (!this.svg || !f) return;
3310
- const c = this.camera ?? whole(f);
2883
+ const c = this.viewer?.box() ?? this.camera ?? whole(f);
3311
2884
  const box = `${c.x} ${c.y} ${c.w} ${c.h}`;
3312
- if (this.svg.getAttribute("viewBox") !== box) this.svg.setAttribute("viewBox", box);
2885
+ if (this.svg.getAttribute("viewBox") === box) return;
2886
+ this.svg.setAttribute("viewBox", box);
2887
+ if (this.viewer) this.changed();
2888
+ }
2889
+ /** What the board shows changed: the zoom controls and a box's detail follow. */
2890
+ changed() {
2891
+ this.viewId++;
2892
+ for (const l of this.#listeners) l();
3313
2893
  }
3314
2894
  /** Draws the dots on the overlay canvas and the worker fills in the SVG. */
3315
2895
  draw(o = {}) {
@@ -3320,6 +2900,10 @@ var Engine = class {
3320
2900
  ctx.setTransform(1, 0, 0, 1, 0, 0);
3321
2901
  ctx.clearRect(0, 0, c.width, c.height);
3322
2902
  if (o.particles === false) return;
2903
+ if (this.viewer) {
2904
+ this.viewer.paint(ctx, c);
2905
+ return;
2906
+ }
3323
2907
  this.paintParticles(ctx, c.width / this.frame.width);
3324
2908
  }
3325
2909
  drawFills() {
@@ -3394,6 +2978,11 @@ var Engine = class {
3394
2978
  const k = Math.min(bw / c.w, bh / c.h);
3395
2979
  ctx.save();
3396
2980
  ctx.transform(k, 0, 0, k, (bw - c.w * k) / 2 - c.x * k, (bh - c.h * k) / 2 - c.y * k);
2981
+ this.paintDots(ctx);
2982
+ ctx.restore();
2983
+ }
2984
+ /** The dots in scene units, on a context already transformed to the scene. */
2985
+ paintDots(ctx) {
3397
2986
  for (const d of this.dots()) {
3398
2987
  ctx.globalAlpha = d.alpha;
3399
2988
  ctx.beginPath();
@@ -3408,7 +2997,7 @@ var Engine = class {
3408
2997
  ctx.fill();
3409
2998
  }
3410
2999
  }
3411
- ctx.restore();
3000
+ ctx.globalAlpha = 1;
3412
3001
  }
3413
3002
  #position(scene, d) {
3414
3003
  if (d.phase !== "move") return anchor(scene, d.to, d.flow);
@@ -3719,6 +3308,7 @@ function useLoadmap(model, view, o = {}) {
3719
3308
  cue: storyPlaying ? cue : null,
3720
3309
  fullScreen,
3721
3310
  fill,
3311
+ zoom: !!o.zoom,
3722
3312
  toggleFullScreen,
3723
3313
  fullScreenMode,
3724
3314
  setFullScreenMode,
@@ -3753,6 +3343,8 @@ function canvasMeasure(fontFamily) {
3753
3343
  };
3754
3344
  }
3755
3345
  // src/Loadmap.tsx
3346
+ const Dock = lazy(() => import("./later-ChRpEoLJ.js").then((m) => ({ default: m.Dock })));
3347
+ const VerdictLine = lazy(() => import("./later-ChRpEoLJ.js").then((m) => ({ default: m.VerdictLine })));
3756
3348
  /** What the page's own switch says, on `<html>`: `data-theme`, or a `dark` or `light` class; null when it says nothing. */
3757
3349
  function pageTheme() {
3758
3350
  if (typeof document === "undefined") return null;
@@ -3892,18 +3484,24 @@ function Loadmap({ model, view, theme, title, assumptions, headroom = true, comp
3892
3484
  full && line && /* @__PURE__ */ jsxs("div", {
3893
3485
  className: "lm-line",
3894
3486
  "data-tier": lm.ev.verdict.tier,
3895
- children: [/* @__PURE__ */ jsx(VerdictLine, {
3896
- lm,
3897
- verdict,
3898
- extra: assumptions?.length,
3899
- open,
3900
- assumptions: !focus && listed("assumptions")
3487
+ children: [/* @__PURE__ */ jsx(Suspense, {
3488
+ fallback: null,
3489
+ children: /* @__PURE__ */ jsx(VerdictLine, {
3490
+ lm,
3491
+ verdict,
3492
+ extra: assumptions?.length,
3493
+ open,
3494
+ assumptions: !focus && listed("assumptions")
3495
+ })
3901
3496
  }), focus && listed("controls") && /* @__PURE__ */ jsx(LoadRange, { lm })]
3902
3497
  }),
3903
- full && !focus && /* @__PURE__ */ jsx(Dock, {
3904
- lm,
3905
- panels: LOADMAP_PANELS.filter(listed),
3906
- open
3498
+ full && !focus && /* @__PURE__ */ jsx(Suspense, {
3499
+ fallback: null,
3500
+ children: /* @__PURE__ */ jsx(Dock, {
3501
+ lm,
3502
+ panels: LOADMAP_PANELS.filter(listed),
3503
+ open
3504
+ })
3907
3505
  }),
3908
3506
  /* @__PURE__ */ jsxs("div", {
3909
3507
  className: "lm-side lm-drawer",
@@ -3991,4 +3589,4 @@ function handleOf(lm) {
3991
3589
  } : null
3992
3590
  };
3993
3591
  }
3994
- 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 };
3592
+ export { plusMinus as C, rankLabels as D, boxComponent as E, Verdict as S, Diagram as T, whenRange as _, usePageTheme as a, Limits as b, injectStyles as c, HeadroomChart as d, Scenarios as f, useSize as g, useHeadroom as h, handleOf as i, Story as l, useComparison as m, Loadmap as n, useLoadmap as o, scenarioColor as p, LoadmapRoot as r, LOADMAP_CSS as s, LOADMAP_PANELS as t, Compare as u, Assumptions as v, workerElk as w, Meters as x, Controls as y };