@tinyactors/scxmljs 0.1.0 → 0.2.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.
Files changed (51) hide show
  1. package/README.md +11 -4
  2. package/dist/explorer/element.d.ts +5 -3
  3. package/dist/explorer/element.js +523 -262
  4. package/dist/explorer/element.js.map +1 -1
  5. package/dist/explorer/strings.d.ts +41 -23
  6. package/dist/explorer/strings.js +24 -15
  7. package/dist/explorer/strings.js.map +1 -1
  8. package/dist/explorer/styles.d.ts +9 -1
  9. package/dist/explorer/styles.js +291 -150
  10. package/dist/explorer/styles.js.map +1 -1
  11. package/dist/explorer.d.ts +1 -0
  12. package/dist/index.d.ts +1 -0
  13. package/dist/model.d.ts +4 -1
  14. package/dist/model.js +7 -1
  15. package/dist/model.js.map +1 -1
  16. package/dist/session.d.ts +22 -9
  17. package/dist/session.js +53 -13
  18. package/dist/session.js.map +1 -1
  19. package/dist/themes/tinyactors.css +1 -0
  20. package/dist/trusted.d.ts +1 -0
  21. package/dist/ui/icons.d.ts +31 -0
  22. package/dist/ui/icons.js +186 -0
  23. package/dist/ui/icons.js.map +1 -0
  24. package/dist/ui/notation.d.ts +53 -0
  25. package/dist/ui/notation.js +117 -0
  26. package/dist/ui/notation.js.map +1 -0
  27. package/dist/ui/svg.d.ts +4 -0
  28. package/dist/ui/svg.js +26 -0
  29. package/dist/ui/svg.js.map +1 -1
  30. package/dist/ui/theme.d.ts +1 -1
  31. package/dist/ui/theme.js +6 -0
  32. package/dist/ui/theme.js.map +1 -1
  33. package/dist/view/describe.d.ts +17 -0
  34. package/dist/view/describe.js +49 -0
  35. package/dist/view/describe.js.map +1 -0
  36. package/dist/view/element.d.ts +39 -9
  37. package/dist/view/element.js +723 -86
  38. package/dist/view/element.js.map +1 -1
  39. package/dist/view/layout.d.ts +20 -0
  40. package/dist/view/layout.js +205 -29
  41. package/dist/view/layout.js.map +1 -1
  42. package/dist/view/strings.d.ts +34 -8
  43. package/dist/view/strings.js +19 -6
  44. package/dist/view/strings.js.map +1 -1
  45. package/dist/view/styles.d.ts +1 -1
  46. package/dist/view/styles.js +107 -21
  47. package/dist/view/styles.js.map +1 -1
  48. package/dist/view.d.ts +8 -4
  49. package/dist/view.js +6 -3
  50. package/dist/view.js.map +1 -1
  51. package/package.json +2 -2
@@ -19,16 +19,24 @@
19
19
  *
20
20
  * Attributes: `src`, `trusted`, `autostart` ("false" = draw without running),
21
21
  * `interactive` ("false" = labels aren't buttons), `data` (JSON initial values
22
- * for `<data>`), `direction` ("auto" | "right" | "down"), `max-states` (fold
22
+ * for `<data>`), `direction` ("down" (default) | "right" | "auto"), `max-states` (fold
23
23
  * large charts beyond this many boxes, default 150), `announce`
24
24
  * ("all" | "sends" | "off"), `fit` (scale down to the element's width),
25
- * `warnings` ("off" hides the list of authoring warnings — see `model.warnings`).
25
+ * `warnings` ("off" hides the list of authoring warnings — see `model.warnings`),
26
+ * `event-data` (JSON object from event names to the data a label click sends,
27
+ * e.g. `{"login": {"user": "ada"}}`).
26
28
  *
27
29
  * Properties: `session` (a host-created session; the element then creates,
28
30
  * starts and disposes nothing), `options` (extra SessionOptions for sessions
29
31
  * the element creates: I/O processors, invokers, loader…), `clock` (e.g. a
30
32
  * PlaybackClock: shows play / pause / step controls), `strings`, `source`
31
- * (SCXML text instead of `src`), `model`, and `reload()`.
33
+ * (SCXML text instead of `src`), `model`, `descriptions` (what each state is
34
+ * about, shown by its help button; XML comments in the source otherwise),
35
+ * `zoom`, and `reload()`.
36
+ *
37
+ * Navigation: the diagram zooms (the toolbar, Ctrl/⌘ + wheel, pinch, `+` `-`
38
+ * `0` while the canvas is focused) and pans (drag, or scroll); every compound
39
+ * and parallel state folds and unfolds with its chevron.
32
40
  *
33
41
  * Events (bubbling, composed): `scxml-load` { session, model },
34
42
  * `scxml-error` { message, problems?, error }, `scxml-send` { session, name }
@@ -38,22 +46,36 @@
38
46
  * `state` (+ `atomic` `compound` `parallel` `parallel-region` `final`
39
47
  * `history` `collapsed` `active`), `state-name`, `transition` / `edge-label`
40
48
  * (+ `live` `fired`), `event`, `cond`, `internal`, `edge` (+ `live` `fired`),
41
- * `initial`, `expand`, `collapse`, `notice`, `error`, `controls`, `play`,
42
- * `step`, `speeds`, `clock`, `warnings`, `warning`.
49
+ * `initial`, `expand`, `collapse`, `help`, `help-popover`, `zoom`, `notice`,
50
+ * `error`, `controls`, `play`, `step`, `speeds`, `clock`, `warnings`, `warning`.
43
51
  */
44
52
  import { PlaybackClock } from "../clock.js";
45
53
  import { compile, isCompound } from "../model.js";
46
54
  import { parseSCXML, SCXMLSession } from "../session.js";
47
55
  import { Announcer } from "../ui/announcer.js";
48
- import { arrowMarker } from "../ui/svg.js";
56
+ import * as icons from "../ui/icons.js";
57
+ import { eventName, NOTATION_CSS } from "../ui/notation.js";
58
+ import { arrowMarker, icon } from "../ui/svg.js";
49
59
  import { lazySheet, NARROW_WIDTH, themeSheet } from "../ui/theme.js";
50
- import { autoCollapse, layoutChart } from "./layout.js";
60
+ import { sourceDescription } from "./describe.js";
61
+ import { autoCollapse, layoutChart, portalTransitions } from "./layout.js";
51
62
  import { defaultViewStrings } from "./strings.js";
52
63
  import { VIEW_CSS } from "./styles.js";
53
64
  const SCXML_MIME = "application/scxml+xml";
54
65
  /** Default floor for scaling a too-wide diagram down (without `fit`); see `--scxml-min-scale`. */
55
66
  const DEFAULT_MIN_SCALE = 0.65;
67
+ const MIN_ZOOM = 0.15;
68
+ const MAX_ZOOM = 4;
69
+ const ZOOM_STEP = 1.25;
70
+ /** The diagram's margin inside the canvas, px (see `.diagram` in styles.ts). */
71
+ const MARGIN = 12;
56
72
  const FIRED_MS = 900;
73
+ /** How long the playback controls stay in full while playing and untouched. */
74
+ const IDLE_MS = 3000;
75
+ /** How long the zoom level stays up after zooming. */
76
+ const ZOOM_LEVEL_MS = 900;
77
+ /** Two taps within this long (ms) are a double tap. */
78
+ const DOUBLE_TAP_MS = 300;
57
79
  const DEFAULT_MAX_STATES = 150;
58
80
  const MAX_INTERNAL_SHOWN = 3;
59
81
  const SPEEDS = [
@@ -66,7 +88,7 @@ const SPEEDS = [
66
88
  // importing this module where there is no DOM (server-side rendering, Node) must work
67
89
  const ElementBase = typeof HTMLElement === "undefined" ? class {
68
90
  } : HTMLElement;
69
- const sheet = lazySheet(VIEW_CSS);
91
+ const sheet = lazySheet(VIEW_CSS + NOTATION_CSS);
70
92
  /** Load a data model engine on demand (dynamic import: never in the element's own bundle). */
71
93
  async function engine(trusted) {
72
94
  if (trusted)
@@ -98,6 +120,7 @@ export class ScxmlView extends ElementBase {
98
120
  #options = {};
99
121
  #clock;
100
122
  #strings = defaultViewStrings;
123
+ #descriptions;
101
124
  #generation = 0;
102
125
  #loadQueued = false;
103
126
  #loadForced = false;
@@ -105,11 +128,16 @@ export class ScxmlView extends ElementBase {
105
128
  #layout;
106
129
  #direction = "right";
107
130
  #collapsed = new Set();
131
+ /** The folds made for `max-states` and not touched since: what the "large chart" notice is about. */
132
+ #autoFolded = new Set();
108
133
  #foldsFor;
109
134
  #boxes = new Map();
110
135
  #labels = new Map();
111
136
  #paths = new Map();
112
137
  #chips = new Map();
138
+ /** Transitions listed in their source's box with their target instead of drawn, per box. */
139
+ #portals = new Map();
140
+ #portalChips = new Map();
113
141
  // live state
114
142
  #fired = new Map();
115
143
  #entered = [];
@@ -122,6 +150,16 @@ export class ScxmlView extends ElementBase {
122
150
  #raf = 0;
123
151
  #decayRaf = 0;
124
152
  #width = 0;
153
+ /** The width the last layout tried to stay within (px; 0: none). */
154
+ #budget = 0;
155
+ // navigation: an explicit zoom (null = automatic, see #applyFit) and the open help popover
156
+ #zoom = null;
157
+ #scale = 1;
158
+ #helpFor;
159
+ /** Keep the active states in view (until the user pans, scrolls or zooms; "fit to width" resumes). */
160
+ #follow = true;
161
+ /** The active states last revealed, so a step that changes nothing doesn't scroll. */
162
+ #revealed = "";
125
163
  constructor() {
126
164
  super();
127
165
  if (typeof document === "undefined")
@@ -163,10 +201,10 @@ export class ScxmlView extends ElementBase {
163
201
  set interactive(v) {
164
202
  this.setAttribute("interactive", String(v));
165
203
  }
166
- /** "right" (layers left to right), "down", or "auto" (down when narrower than the shared breakpoint). */
204
+ /** "down" (layers top to bottom, the default), "right", or "auto" (down when narrower than the shared breakpoint, right otherwise). */
167
205
  get direction() {
168
206
  const d = this.getAttribute("direction");
169
- return d === "right" || d === "down" ? d : "auto";
207
+ return d === "right" || d === "auto" ? d : "down";
170
208
  }
171
209
  /** Sets the `direction` attribute (re-lays out). */
172
210
  set direction(v) {
@@ -262,6 +300,30 @@ export class ScxmlView extends ElementBase {
262
300
  this.#strings = { ...defaultViewStrings, ...s, kinds: { ...defaultViewStrings.kinds, ...s?.kinds } };
263
301
  this.#relayout();
264
302
  }
303
+ /** What each state is about (its help popover): an object from state ids to text, or a function of the state. Overrides the chart's XML comments. */
304
+ get descriptions() {
305
+ return this.#descriptions;
306
+ }
307
+ /** Set what states are about; `undefined` goes back to the chart's XML comments only. */
308
+ set descriptions(d) {
309
+ this.#descriptions = d;
310
+ if (this.#helpFor)
311
+ this.#openHelp(this.#helpFor.state, this.#helpFor.button);
312
+ }
313
+ /** What a state's help popover explains: `descriptions` first, then the XML comments documenting it in the source. */
314
+ describe(state) {
315
+ const d = this.#descriptions;
316
+ const given = typeof d === "function" ? d(state) : d && Object.hasOwn(d, state.id) ? d[state.id] : undefined;
317
+ return given?.trim() ? given : sourceDescription(state);
318
+ }
319
+ /** The diagram's scale (1 = actual size). Reading it gives the scale in use; setting a number zooms, `null` goes back to automatic. */
320
+ get zoom() {
321
+ return this.#scale;
322
+ }
323
+ /** Zoom to this scale (clamped to 0.15–4), or `null` for the automatic scale (fitted to the element's width, see `fit`). */
324
+ set zoom(scale) {
325
+ this.#zoomTo(scale);
326
+ }
265
327
  /** Load the chart again (re-reading `src` / inline source) and start a fresh session. */
266
328
  reload() {
267
329
  this.#scheduleLoad(true);
@@ -478,29 +540,140 @@ export class ScxmlView extends ElementBase {
478
540
  });
479
541
  this.#announcer.say(text, urgent);
480
542
  }
543
+ /**
544
+ * Data for events sent by clicking a label: the `event-data` attribute is a
545
+ * JSON object from event names to data, e.g. `event-data='{"login": {"user": "ada"}}'`.
546
+ */
547
+ #eventData(name) {
548
+ const raw = this.getAttribute("event-data");
549
+ if (!raw)
550
+ return undefined;
551
+ try {
552
+ const map = JSON.parse(raw);
553
+ return map && typeof map === "object" ? map[name] : undefined;
554
+ }
555
+ catch {
556
+ console.warn(`scxml-view: the event-data attribute is not valid JSON: ${raw}`);
557
+ return undefined;
558
+ }
559
+ }
560
+ #sendStatusTimer;
561
+ /**
562
+ * After a label click: if the event takes no transition, or evaluating it
563
+ * raises an error (a condition that throws counts as false, spec §5.9.1),
564
+ * say so — otherwise the click looks like it did nothing at all.
565
+ */
566
+ #watchOutcome(session, name) {
567
+ const status = this.#el.sendStatus;
568
+ status.hidden = true;
569
+ clearTimeout(this.#sendStatusTimer);
570
+ let took = false;
571
+ let error;
572
+ const onMicro = (e) => {
573
+ const m = e;
574
+ if (m.event?.name === name)
575
+ took = true;
576
+ };
577
+ const onError = (e) => {
578
+ error ??= e.message;
579
+ };
580
+ const stop = () => {
581
+ session.removeEventListener("microstep", onMicro);
582
+ session.removeEventListener("error", onError);
583
+ session.removeEventListener("macrostep", onMacro);
584
+ };
585
+ const onMacro = (e) => {
586
+ const m = e;
587
+ if (m.event?.name !== name)
588
+ return;
589
+ stop();
590
+ if (took && !error)
591
+ return;
592
+ const t = this.#strings;
593
+ const text = error ? t.sentError(name, error) : t.sentNothing(name);
594
+ status.textContent = text;
595
+ status.hidden = false;
596
+ if (this.announce !== "off")
597
+ this.#say(text, true);
598
+ // a message, not state: real time is fine for hiding it
599
+ this.#sendStatusTimer = setTimeout(() => (status.hidden = true), 6000);
600
+ };
601
+ session.addEventListener("microstep", onMicro);
602
+ session.addEventListener("error", onError);
603
+ session.addEventListener("macrostep", onMacro);
604
+ session.signal.addEventListener("abort", stop, { once: true });
605
+ }
481
606
  #emit(type, detail, cancelable = false) {
482
607
  return this.dispatchEvent(new CustomEvent(type, { detail, bubbles: true, composed: true, cancelable }));
483
608
  }
484
609
  // ───────────────────────────────── shell ─────────────────────────────────
485
610
  #buildShell() {
486
611
  const t = this.#strings;
487
- const play = h("button", { class: "play", type: "button", part: "play", title: t.playHint });
488
- const step = h("button", { class: "step", type: "button", part: "step", title: t.stepHint }, t.step);
489
- const speeds = h("div", { class: "speeds", role: "group", part: "speeds", "aria-label": t.speedLabel });
612
+ const iconButton = (cls, part, label, glyph, onClick) => {
613
+ const b = h("button", { class: cls, type: "button", part, title: label, "aria-label": label }, glyph);
614
+ b.addEventListener("click", onClick);
615
+ return b;
616
+ };
617
+ // controls float over the diagram's bottom edge, both clusters on one line, inset like the diagram:
618
+ // [play] [step] [speed] t = … ········· [−] [level] [+] [fit]
619
+ // playback (a PlaybackClock) on the left: Step only while paused; while playing untouched it
620
+ // shrinks to the play button (#wake). Zoom on the right: fit, in the corner, once the view has
621
+ // left the automatic one; −/level/+ beside it on hover, keyboard focus, or while zooming
622
+ // (−/+ give way to pinch and double tap on touch screens)
623
+ const play = iconButton("play", "play", t.play, icon(icons.play, 16), () => this.#playback()?.toggle());
624
+ const step = iconButton("step", "step", t.stepHint, icon(icons.stepForward, 16), () => this.#step());
625
+ const speeds = h("button", { class: "speeds", type: "button", part: "speeds", title: t.speedLabel });
626
+ speeds.addEventListener("click", () => {
627
+ const clock = this.#playback();
628
+ if (!clock)
629
+ return;
630
+ const i = SPEEDS.findIndex(([v]) => v === clock.speed);
631
+ clock.speed = SPEEDS[(i + 1) % SPEEDS.length][0];
632
+ });
490
633
  const clock = h("span", { class: "clock", part: "clock" });
491
- play.addEventListener("click", () => this.#playback()?.toggle());
492
- step.addEventListener("click", () => this.#step());
493
- const controls = h("div", { class: "controls", part: "controls", hidden: "" }, play, step, speeds, clock);
634
+ const controls = h("div", { class: "controls", part: "controls", role: "group", "aria-label": t.playbackLabel, hidden: "" }, play, step, speeds, clock);
494
635
  const notice = h("div", { class: "notice", part: "notice", hidden: "" });
636
+ // what became of an event sent by clicking a label, when it wasn't the obvious (a transition fired)
637
+ const sendStatus = h("div", { class: "notice send-status", part: "send-status", hidden: "" });
495
638
  const warnings = h("details", { class: "warnings", part: "warnings", hidden: "" });
496
639
  const error = h("div", { class: "error", part: "error", role: "alert", hidden: "" });
497
640
  const diagram = h("div", { class: "diagram", role: "group" });
498
- // focusable: a scroll container must be keyboard-scrollable, and it takes the playback shortcuts
641
+ // focusable: a scroll container must be keyboard-scrollable, and it takes the playback and zoom shortcuts
499
642
  const canvas = h("div", { class: "canvas", part: "canvas", tabindex: "0" }, diagram);
643
+ const fit = iconButton("zoom-reset", "fit", t.zoomReset, icon(icons.scan, 16), () => this.#zoomTo(null));
644
+ fit.append(h("span", {}, t.fit));
645
+ const zoomLevel = iconButton("zoom-level", "zoom-level", t.zoomActual, document.createTextNode("100%"), () => this.#zoomTo(1));
646
+ const zoom = h("div", { class: "zoom", part: "zoom", role: "group", "aria-label": t.zoomToolbar }, iconButton("zoom-out", "zoom-out", t.zoomOut, icon(icons.minus, 16), () => this.#zoomBy(1 / ZOOM_STEP)), zoomLevel, iconButton("zoom-in", "zoom-in", t.zoomIn, icon(icons.plus, 16), () => this.#zoomBy(ZOOM_STEP)));
647
+ const nav = h("div", { class: "nav", hidden: "" }, zoom, fit);
648
+ const help = h("div", { class: "help-popover", part: "help-popover", role: "dialog", tabindex: "-1", id: "help-popover", hidden: "" });
649
+ const viewport = h("div", { class: "viewport" }, canvas, controls, nav, help);
500
650
  const live = h("div", { class: "sr-only", role: "status", "aria-live": "polite", "aria-atomic": "true" });
501
- const frame = h("div", { class: "frame", part: "frame" }, controls, notice, warnings, error, canvas, live);
651
+ const frame = h("div", { class: "frame", part: "frame" }, notice, sendStatus, warnings, error, viewport, live);
502
652
  this.#shadow.append(frame);
503
- this.#el = { frame, controls, play, step, speeds, clock, notice, warnings, error, canvas, diagram, live };
653
+ this.#el = {
654
+ frame,
655
+ controls,
656
+ play,
657
+ step,
658
+ speeds,
659
+ clock,
660
+ notice,
661
+ sendStatus,
662
+ warnings,
663
+ error,
664
+ canvas,
665
+ diagram,
666
+ live,
667
+ viewport,
668
+ nav,
669
+ fit,
670
+ zoom,
671
+ zoomLevel,
672
+ help,
673
+ };
674
+ for (const type of ["pointermove", "pointerdown", "keydown", "focusin", "wheel", "touchstart"])
675
+ viewport.addEventListener(type, () => this.#wake(), { passive: true });
676
+ this.#wireNavigation();
504
677
  this.addEventListener("keydown", (e) => {
505
678
  const clockNow = this.#playback();
506
679
  const target = e.composedPath()[0];
@@ -516,6 +689,332 @@ export class ScxmlView extends ElementBase {
516
689
  }
517
690
  });
518
691
  }
692
+ // ─────────────────────────────── navigation ───────────────────────────────
693
+ /** Zoom (Ctrl/⌘ + wheel, pinch, + − 0), pan (drag), and closing the help popover. */
694
+ #wireNavigation() {
695
+ const { canvas, help } = this.#el;
696
+ canvas.addEventListener("wheel", (e) => {
697
+ this.#takeOver();
698
+ // pinch-zoom on a trackpad arrives as a wheel event with ctrlKey
699
+ if (!(e.ctrlKey || e.metaKey) || !this.#layout)
700
+ return;
701
+ e.preventDefault();
702
+ // a wheel notch (~100px) zooms by about a fifth; a pinch sends many small deltas
703
+ const factor = Math.exp(-Math.max(-100, Math.min(100, e.deltaY * (e.deltaMode === 1 ? 20 : 1))) * 0.002);
704
+ this.#zoomTo(this.#scale * factor, { x: e.clientX, y: e.clientY });
705
+ }, { passive: false });
706
+ canvas.addEventListener("keydown", (e) => {
707
+ if (e.composedPath()[0] !== canvas || e.altKey || e.ctrlKey || e.metaKey)
708
+ return;
709
+ if (e.key === "+" || e.key === "=")
710
+ this.#zoomBy(ZOOM_STEP);
711
+ else if (e.key === "-" || e.key === "_")
712
+ this.#zoomBy(1 / ZOOM_STEP);
713
+ else if (e.key === "0")
714
+ this.#zoomTo(null);
715
+ else {
716
+ if (/^(Arrow|Page|Home$|End$)/.test(e.key) || e.key === " ")
717
+ this.#takeOver();
718
+ return;
719
+ }
720
+ e.preventDefault();
721
+ });
722
+ this.#wirePinch();
723
+ // drag to pan (mouse and pen; touch scrolls natively), starting anywhere but a control
724
+ let drag;
725
+ canvas.addEventListener("pointerdown", (e) => {
726
+ if (e.button !== 0 || e.pointerType === "touch")
727
+ return;
728
+ const target = e.composedPath()[0];
729
+ if (target?.closest?.("button, a, input, select, textarea, summary"))
730
+ return;
731
+ drag = { id: e.pointerId, x: e.clientX, y: e.clientY, left: canvas.scrollLeft, top: canvas.scrollTop, moved: false };
732
+ });
733
+ canvas.addEventListener("pointermove", (e) => {
734
+ if (!drag || e.pointerId !== drag.id)
735
+ return;
736
+ const dx = e.clientX - drag.x;
737
+ const dy = e.clientY - drag.y;
738
+ if (!drag.moved) {
739
+ if (Math.abs(dx) + Math.abs(dy) < 4)
740
+ return;
741
+ drag.moved = true;
742
+ this.#takeOver();
743
+ canvas.setPointerCapture?.(e.pointerId);
744
+ canvas.classList.add("panning");
745
+ }
746
+ e.preventDefault();
747
+ canvas.scrollLeft = drag.left - dx;
748
+ canvas.scrollTop = drag.top - dy;
749
+ });
750
+ const end = (e) => {
751
+ if (!drag || e.pointerId !== drag.id)
752
+ return;
753
+ drag = undefined;
754
+ canvas.classList.remove("panning");
755
+ if (canvas.hasPointerCapture?.(e.pointerId))
756
+ canvas.releasePointerCapture(e.pointerId);
757
+ };
758
+ canvas.addEventListener("pointerup", end);
759
+ canvas.addEventListener("pointercancel", end);
760
+ canvas.addEventListener("scroll", () => this.#placeHelp());
761
+ help.addEventListener("keydown", (e) => {
762
+ if (e.key !== "Escape")
763
+ return;
764
+ e.stopPropagation();
765
+ this.#closeHelp(true);
766
+ });
767
+ this.#shadow.addEventListener("pointerdown", (e) => {
768
+ if (!this.#helpFor)
769
+ return;
770
+ const path = e.composedPath();
771
+ if (!path.includes(help) && !path.includes(this.#helpFor.button))
772
+ this.#closeHelp(false);
773
+ });
774
+ }
775
+ /**
776
+ * Touch: one finger scrolls (natively), two pinch-zoom the diagram around their midpoint
777
+ * instead of the page (`touch-action: pan-x pan-y` on the canvas keeps the browser out of it).
778
+ * A double tap zooms in on that spot, or, when already zoomed in, back to fit (like Photos).
779
+ */
780
+ #wirePinch() {
781
+ const canvas = this.#el.canvas;
782
+ let pinch;
783
+ /** the last single-finger tap (no movement): where and when */
784
+ let tap;
785
+ let start;
786
+ const dist = (t) => Math.hypot(t[0].clientX - t[1].clientX, t[0].clientY - t[1].clientY);
787
+ const mid = (t) => ({ x: (t[0].clientX + t[1].clientX) / 2, y: (t[0].clientY + t[1].clientY) / 2 });
788
+ canvas.addEventListener("touchstart", (e) => {
789
+ if (e.touches.length === 2 && this.#layout) {
790
+ this.#takeOver();
791
+ pinch = { dist: dist(e.touches), scale: this.#scale };
792
+ start = undefined;
793
+ tap = undefined;
794
+ }
795
+ else if (e.touches.length === 1)
796
+ start = { x: e.touches[0].clientX, y: e.touches[0].clientY, moved: false };
797
+ }, { passive: true });
798
+ canvas.addEventListener("touchmove", (e) => {
799
+ if (start && e.touches.length === 1) {
800
+ const t = e.touches[0];
801
+ if (!start.moved && Math.abs(t.clientX - start.x) + Math.abs(t.clientY - start.y) > 8) {
802
+ start.moved = true;
803
+ this.#takeOver(); // scrolling by hand
804
+ }
805
+ }
806
+ if (!pinch || e.touches.length !== 2)
807
+ return;
808
+ e.preventDefault();
809
+ const d = dist(e.touches);
810
+ if (pinch.dist > 0 && d > 0)
811
+ this.#zoomTo(pinch.scale * (d / pinch.dist), mid(e.touches));
812
+ }, { passive: false });
813
+ const end = (e) => {
814
+ if (e.touches.length < 2)
815
+ pinch = undefined;
816
+ if (e.type !== "touchend" || e.touches.length || !start || start.moved) {
817
+ start = undefined;
818
+ return;
819
+ }
820
+ // a tap on a control is that control's
821
+ const target = e.composedPath()[0];
822
+ const s0 = start;
823
+ start = undefined;
824
+ if (target?.closest?.("button, a, input, select, textarea, summary") || !this.#layout)
825
+ return;
826
+ const now = e.timeStamp;
827
+ if (tap && now - tap.at < DOUBLE_TAP_MS && Math.hypot(s0.x - tap.x, s0.y - tap.y) < 30) {
828
+ tap = undefined;
829
+ e.preventDefault();
830
+ const anchor = { x: s0.x, y: s0.y };
831
+ if (this.#zoom != null && this.#zoom > this.#fitScale() + 0.01)
832
+ this.#zoomTo(null);
833
+ else
834
+ this.#zoomTo(Math.max(1, this.#scale * 2), anchor);
835
+ }
836
+ else
837
+ tap = { x: s0.x, y: s0.y, at: now };
838
+ };
839
+ canvas.addEventListener("touchend", end, { passive: false });
840
+ canvas.addEventListener("touchcancel", end);
841
+ // WebKit's own pinch gesture on the page
842
+ canvas.addEventListener("gesturestart", (e) => e.preventDefault());
843
+ }
844
+ /** The automatic scale (what "fit" goes back to). */
845
+ #fitScale() {
846
+ const layout = this.#layout;
847
+ const available = this.#el.canvas.clientWidth - 2 * MARGIN;
848
+ if (!layout || !(available > 0) || available >= layout.width)
849
+ return 1;
850
+ const floor = this.fit ? 0 : this.#minScale();
851
+ return Math.min(1, Math.max(floor, available / layout.width));
852
+ }
853
+ /**
854
+ * Scroll the active states into view when they aren't (the whole chart doesn't fit), unless the
855
+ * user has taken over the view. `smooth`: animate (not with reduced motion).
856
+ */
857
+ #revealActive(smooth) {
858
+ const session = this.#session;
859
+ const layout = this.#layout;
860
+ const canvas = this.#el.canvas;
861
+ if (!this.#follow || !session || !layout || session.status !== "running")
862
+ return;
863
+ const active = layout.boxes.filter((b) => b.kind !== "root" && session.isActiveNode(b.node) && !layout.boxes.some((k) => k.node.parent === b.node));
864
+ const key = active.map((b) => b.node.id).join(" ");
865
+ if (!active.length || key === this.#revealed)
866
+ return;
867
+ this.#revealed = key;
868
+ const s = this.#scale;
869
+ const x0 = Math.min(...active.map((b) => b.rect.x)) * s + MARGIN;
870
+ const y0 = Math.min(...active.map((b) => b.rect.y)) * s + MARGIN;
871
+ const x1 = Math.max(...active.map((b) => b.rect.x + b.rect.w)) * s + MARGIN;
872
+ const y1 = Math.max(...active.map((b) => b.rect.y + b.rect.h)) * s + MARGIN;
873
+ const w = canvas.clientWidth;
874
+ const h = canvas.clientHeight;
875
+ if (!(w > 0 && h > 0))
876
+ return;
877
+ const pad = 16;
878
+ const inView = x0 >= canvas.scrollLeft + pad &&
879
+ x1 <= canvas.scrollLeft + w - pad &&
880
+ y0 >= canvas.scrollTop + pad &&
881
+ y1 <= canvas.scrollTop + h - pad;
882
+ if (inView)
883
+ return;
884
+ // centre them; if they don't fit, show their top-left corner
885
+ const left = x1 - x0 + 2 * pad > w ? x0 - pad : (x0 + x1) / 2 - w / 2;
886
+ const top = y1 - y0 + 2 * pad > h ? y0 - pad : (y0 + y1) / 2 - h / 2;
887
+ const reduce = typeof matchMedia !== "undefined" && matchMedia("(prefers-reduced-motion: reduce)").matches;
888
+ const behavior = smooth && !reduce ? "smooth" : "auto";
889
+ if (typeof canvas.scrollTo === "function")
890
+ canvas.scrollTo({ left: Math.max(0, left), top: Math.max(0, top), behavior });
891
+ else {
892
+ canvas.scrollLeft = Math.max(0, left);
893
+ canvas.scrollTop = Math.max(0, top);
894
+ }
895
+ }
896
+ /** "Fit" shows once the view has left the default: zoomed by hand, or no longer following. */
897
+ #syncFit() {
898
+ this.#el.fit.hidden = this.#zoom == null && this.#follow;
899
+ }
900
+ #zoomLevelTimer;
901
+ /** Show the zoom level for a moment after zooming (on touch screens, where nothing hovers). */
902
+ #flashZoomLevel() {
903
+ const v = this.#el.viewport;
904
+ v.dataset.zooming = "";
905
+ clearTimeout(this.#zoomLevelTimer);
906
+ this.#zoomLevelTimer = setTimeout(() => delete v.dataset.zooming, ZOOM_LEVEL_MS);
907
+ }
908
+ /** Stop following the active states: the user has taken over the view. */
909
+ #takeOver() {
910
+ if (!this.#follow)
911
+ return;
912
+ this.#follow = false;
913
+ this.#syncFit();
914
+ }
915
+ #zoomBy(factor) {
916
+ this.#zoomTo(this.#scale * factor);
917
+ }
918
+ /**
919
+ * Set an explicit scale (`null`: back to automatic), keeping the diagram point under
920
+ * `anchor` (client coordinates; default: the middle of the canvas) where it is.
921
+ */
922
+ #zoomTo(scale, anchor) {
923
+ const canvas = this.#el.canvas;
924
+ const before = this.#scale;
925
+ if (scale != null && !Number.isFinite(scale))
926
+ return;
927
+ const next = scale == null ? null : Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, scale));
928
+ if (next != null && this.#zoom == null) {
929
+ // zooming by hand: the canvas keeps the height it has now, the diagram moves inside it
930
+ const h = canvas.clientHeight;
931
+ if (h > 0)
932
+ canvas.style.setProperty("height", `${h}px`);
933
+ }
934
+ if (next == null)
935
+ canvas.style.removeProperty("height");
936
+ const r = canvas.getBoundingClientRect();
937
+ const ax = (anchor?.x ?? r.left + canvas.clientWidth / 2) - r.left;
938
+ const ay = (anchor?.y ?? r.top + canvas.clientHeight / 2) - r.top;
939
+ // the diagram point under the anchor
940
+ const px = (canvas.scrollLeft + ax - MARGIN) / before;
941
+ const py = (canvas.scrollTop + ay - MARGIN) / before;
942
+ this.#zoom = next;
943
+ this.#follow = next == null;
944
+ this.#revealed = "";
945
+ if (next != null)
946
+ this.#flashZoomLevel();
947
+ this.#applyFit();
948
+ if (next == null) {
949
+ this.#revealActive(true);
950
+ return;
951
+ }
952
+ canvas.scrollLeft = px * this.#scale + MARGIN - ax;
953
+ canvas.scrollTop = py * this.#scale + MARGIN - ay;
954
+ }
955
+ /** Open the help popover of `state` next to its button. */
956
+ #openHelp(state, button) {
957
+ const t = this.#strings;
958
+ const pop = this.#el.help;
959
+ if (this.#helpFor && this.#helpFor.button !== button)
960
+ this.#helpFor.button.setAttribute("aria-expanded", "false");
961
+ this.#helpFor = { state, button };
962
+ button.setAttribute("aria-expanded", "true");
963
+ const kind = this.#kind(state);
964
+ const name = state.generatedId ? `(${t.kinds[kind]})` : state.id;
965
+ const text = this.describe(state);
966
+ const heading = h("div", { class: "help-head" }, h("strong", {}, name), h("span", { class: "help-kind" }, t.kinds[kind]));
967
+ const body = text
968
+ ? h("div", { class: "help-text" }, ...text.split(/\n{2,}/).map((para) => h("p", {}, para)))
969
+ : h("p", { class: "help-none" }, t.noDescription);
970
+ const shown = state.transitions.filter((tr) => tr.element);
971
+ const list = shown.length
972
+ ? [
973
+ h("div", { class: "help-sub" }, t.helpTransitions),
974
+ h("ul", { class: "help-transitions" }, ...shown.map((tr) => h("li", {}, [
975
+ tr.events.join(" ") || t.eventless,
976
+ tr.cond && `[${truncate(tr.cond, 40)}]`,
977
+ tr.targets.length ? `→ ${tr.targets.map((s) => s.id).join(", ")}` : "",
978
+ ]
979
+ .filter(Boolean)
980
+ .join(" ")))),
981
+ ]
982
+ : [];
983
+ pop.replaceChildren(heading, body, ...list);
984
+ pop.setAttribute("aria-label", t.helpLabel(name));
985
+ pop.hidden = false;
986
+ this.#placeHelp();
987
+ pop.focus({ preventScroll: true });
988
+ }
989
+ #closeHelp(refocus) {
990
+ const open = this.#helpFor;
991
+ this.#helpFor = undefined;
992
+ this.#el.help.hidden = true;
993
+ if (!open)
994
+ return;
995
+ open.button.setAttribute("aria-expanded", "false");
996
+ if (refocus && open.button.isConnected)
997
+ open.button.focus();
998
+ }
999
+ /** Keep the open popover under its button (it follows panning and zooming), inside the viewport. */
1000
+ #placeHelp() {
1001
+ const open = this.#helpFor;
1002
+ const pop = this.#el.help;
1003
+ if (!open || pop.hidden)
1004
+ return;
1005
+ if (!open.button.isConnected)
1006
+ return this.#closeHelp(false);
1007
+ const vp = pop.parentElement.getBoundingClientRect();
1008
+ const b = open.button.getBoundingClientRect();
1009
+ const w = pop.offsetWidth;
1010
+ const ph = pop.offsetHeight;
1011
+ const maxLeft = Math.max(4, vp.width - w - 4);
1012
+ pop.style.setProperty("left", `${Math.min(maxLeft, Math.max(4, b.left - vp.left + b.width / 2 - 20))}px`);
1013
+ // below the button, or above it when there's no room below
1014
+ const below = b.bottom - vp.top + 6;
1015
+ const above = b.top - vp.top - 6 - ph;
1016
+ pop.style.setProperty("top", `${below + ph > vp.height - 4 && above >= 4 ? above : Math.max(4, below)}px`);
1017
+ }
519
1018
  #playback() {
520
1019
  const c = this.#session?.clock;
521
1020
  return c instanceof PlaybackClock ? c : undefined;
@@ -535,11 +1034,19 @@ export class ScxmlView extends ElementBase {
535
1034
  if (!this.#layout)
536
1035
  return;
537
1036
  const crossed = was === 0 || was <= NARROW_WIDTH !== w <= NARROW_WIDTH;
538
- if (this.direction === "auto" && crossed)
1037
+ // the layout wraps parallel regions to the width: lay out again when it changed noticeably
1038
+ const budget = (this.#el.canvas.clientWidth - 2 * MARGIN) / this.#minScale();
1039
+ const moved = !this.#budget || Math.abs(budget - this.#budget) / this.#budget > 0.15;
1040
+ if ((this.direction === "auto" && crossed) || moved)
539
1041
  this.#relayout();
540
1042
  else
541
1043
  this.#applyFit();
542
1044
  }
1045
+ /** The automatic scale's floor: `--scxml-min-scale` (default 0.65); `fit` scales further, but wraps the same. */
1046
+ #minScale() {
1047
+ const raw = Number.parseFloat(getComputedStyle(this).getPropertyValue("--scxml-min-scale"));
1048
+ return Number.isFinite(raw) ? Math.min(1, Math.max(0.1, raw)) : DEFAULT_MIN_SCALE;
1049
+ }
543
1050
  // ──────────────────────────────── rendering ────────────────────────────────
544
1051
  #relayout() {
545
1052
  if (!this.#model || this.#raf)
@@ -568,12 +1075,25 @@ export class ScxmlView extends ElementBase {
568
1075
  const session = this.#session;
569
1076
  const active = new Set(session?.status === "running" ? model.states.filter((s) => session.isActiveNode(s)) : []);
570
1077
  this.#collapsed = autoCollapse(model.root, this.maxStates, active);
1078
+ this.#autoFolded = new Set(this.#collapsed);
571
1079
  this.#foldsFor = model;
572
1080
  }
1081
+ this.#closeHelp(false);
573
1082
  this.#boxes.clear();
574
1083
  this.#labels.clear();
575
1084
  this.#paths.clear();
576
1085
  this.#chips.clear();
1086
+ this.#portalChips.clear();
1087
+ // long-distance transitions: chips in their (drawn) source's box, not edges
1088
+ const portals = portalTransitions(model.root, this.#collapsed);
1089
+ this.#portals.clear();
1090
+ for (const tr of portals) {
1091
+ let box = tr.source;
1092
+ for (let n = box.parent; n; n = n.parent)
1093
+ if (this.#collapsed.has(n))
1094
+ box = n;
1095
+ (this.#portals.get(box) ?? this.#portals.set(box, []).get(box)).push(tr);
1096
+ }
577
1097
  e.diagram.replaceChildren();
578
1098
  e.diagram.setAttribute("aria-label", t.diagramLabel(model.name || "statechart"));
579
1099
  // 1. boxes, drawn parents first; hidden (folded) states get none
@@ -597,7 +1117,7 @@ export class ScxmlView extends ElementBase {
597
1117
  e.diagram.append(measureHost);
598
1118
  for (const s of visible) {
599
1119
  for (const tr of s.transitions) {
600
- if (!tr.targets.length || !labelText(tr))
1120
+ if (!tr.targets.length || !labelText(tr) || portals.has(tr))
601
1121
  continue;
602
1122
  const el = this.#label(tr);
603
1123
  measureHost.append(el);
@@ -606,9 +1126,14 @@ export class ScxmlView extends ElementBase {
606
1126
  }
607
1127
  measureHost.remove();
608
1128
  // 3. layout
1129
+ // the width that fits at the smallest automatic scale: parallel regions wrap to stay within it
1130
+ const available = e.canvas.clientWidth - 2 * MARGIN;
1131
+ this.#budget = available > 0 ? available / this.#minScale() : 0;
609
1132
  const layout = layoutChart(model.root, {
610
1133
  direction: this.#direction,
1134
+ maxWidth: this.#budget || undefined,
611
1135
  collapsed: this.#collapsed,
1136
+ portals,
612
1137
  labelSize: (tr) => labelSizes.get(tr) ?? { w: 0, h: 0 },
613
1138
  measure: (s, collapsed) => this.#measure(s, collapsed),
614
1139
  });
@@ -662,6 +1187,12 @@ export class ScxmlView extends ElementBase {
662
1187
  this.#renderNotice();
663
1188
  this.#renderWarnings();
664
1189
  this.#applyFit();
1190
+ // the width the element has NOW: when its width follows its content (inline-block, a flex
1191
+ // item…), drawing just changed it, and that resize mustn't count as a reason to lay out again
1192
+ const after = e.canvas.clientWidth - 2 * MARGIN;
1193
+ if (this.#budget && after > 0)
1194
+ this.#budget = after / this.#minScale();
1195
+ this.#revealed = "";
665
1196
  this.#renderState();
666
1197
  }
667
1198
  #kind(s) {
@@ -704,42 +1235,88 @@ export class ScxmlView extends ElementBase {
704
1235
  const name = h("div", { class: "name", part: "state-name", title: display }, h("span", { class: "dot", "aria-hidden": "true" }), display);
705
1236
  if (kind === "parallel")
706
1237
  name.append(h("span", { class: "kind" }, "∥"));
1238
+ // the title row: [fold toggle] name [help]
1239
+ const row = h("div", { class: "title" });
1240
+ if (container || collapsed) {
1241
+ const fold = h("button", {
1242
+ class: `toggle ${collapsed ? "expand" : "collapse"}`,
1243
+ type: "button",
1244
+ part: collapsed ? "expand" : "collapse",
1245
+ "aria-expanded": String(!collapsed),
1246
+ "aria-label": `${collapsed ? t.expand : t.collapse} ${display}`,
1247
+ title: collapsed ? t.expand : t.collapse,
1248
+ }, icon(collapsed ? icons.chevronRight : icons.chevronDown));
1249
+ fold.addEventListener("click", () => this.#toggleFold(s));
1250
+ row.append(fold);
1251
+ }
1252
+ row.append(name);
1253
+ const help = h("button", {
1254
+ class: "help",
1255
+ type: "button",
1256
+ part: "help",
1257
+ "aria-label": t.helpLabel(display),
1258
+ "aria-expanded": "false",
1259
+ "aria-controls": "help-popover",
1260
+ title: t.helpLabel(display),
1261
+ }, icon(icons.circleHelp));
1262
+ help.addEventListener("click", () => {
1263
+ if (this.#helpFor?.button === help)
1264
+ this.#closeHelp(false);
1265
+ else
1266
+ this.#openHelp(s, help);
1267
+ });
1268
+ row.append(help);
707
1269
  const internal = this.#internal(s);
708
1270
  if (container) {
709
- el.append(h("div", { class: "head" }, name, ...(internal ? [internal] : [])));
710
- if (this.#expandedFolds.has(s)) {
711
- const fold = h("button", { class: "collapse", type: "button", part: "collapse" }, t.collapse);
712
- fold.addEventListener("click", () => {
713
- this.#collapsed.add(s);
714
- this.#expandedFolds.delete(s);
715
- this.#renderAll();
716
- });
717
- el.append(fold);
718
- }
1271
+ el.append(h("div", { class: "head" }, row, ...(internal ? [internal] : [])));
719
1272
  return el;
720
1273
  }
721
- el.append(name);
1274
+ el.append(row);
722
1275
  if (internal)
723
1276
  el.append(internal);
724
- if (collapsed) {
725
- const inside = countInside(s);
726
- const expand = h("button", { class: "expand", type: "button", part: "expand" }, t.expand);
727
- expand.addEventListener("click", () => {
728
- this.#collapsed.delete(s);
729
- this.#expandedFolds.add(s);
730
- this.#renderAll();
731
- });
732
- el.append(h("span", { class: "badge-count" }, t.statesInside(inside)), expand);
733
- }
1277
+ if (collapsed)
1278
+ el.append(h("span", { class: "badge-count" }, t.statesInside(countInside(s))));
734
1279
  return el;
735
1280
  }
736
- #expandedFolds = new Set();
737
- /** Targetless transitions of a state, as chips inside its box. */
1281
+ /** Fold or unfold a container, keeping keyboard focus on its toggle. */
1282
+ #toggleFold(s) {
1283
+ this.#autoFolded.delete(s);
1284
+ if (this.#collapsed.has(s))
1285
+ this.#collapsed.delete(s);
1286
+ else
1287
+ this.#collapsed.add(s);
1288
+ this.#renderAll();
1289
+ const box = this.#boxes.get(s);
1290
+ box?.querySelector(".toggle")?.focus({ preventScroll: true });
1291
+ }
1292
+ /**
1293
+ * Chips inside a state's box: its long-distance transitions ("event → target", all of them;
1294
+ * hovering one marks its target), then its targetless ones (the first few).
1295
+ */
738
1296
  #internal(s) {
739
1297
  const list = s.transitions.filter((tr) => !tr.targets.length);
740
- if (!list.length)
1298
+ const far = this.#portals.get(s) ?? [];
1299
+ if (!list.length && !far.length)
741
1300
  return undefined;
742
1301
  const wrap = h("div", { class: "internal", part: "internal" });
1302
+ for (const tr of far) {
1303
+ const chip = this.#label(tr, true, true);
1304
+ const mark = (on) => {
1305
+ for (const target of tr.targets) {
1306
+ let box = target;
1307
+ for (let n = box.parent; n; n = n.parent)
1308
+ if (this.#collapsed.has(n))
1309
+ box = n;
1310
+ this.#boxes.get(box)?.classList.toggle("portal-target", on);
1311
+ }
1312
+ };
1313
+ chip.addEventListener("pointerenter", () => mark(true));
1314
+ chip.addEventListener("pointerleave", () => mark(false));
1315
+ chip.addEventListener("focus", () => mark(true));
1316
+ chip.addEventListener("blur", () => mark(false));
1317
+ wrap.append(chip);
1318
+ this.#portalChips.set(tr, chip);
1319
+ }
743
1320
  for (const tr of list.slice(0, MAX_INTERNAL_SHOWN)) {
744
1321
  const chip = this.#label(tr, true);
745
1322
  wrap.append(chip);
@@ -750,12 +1327,12 @@ export class ScxmlView extends ElementBase {
750
1327
  return wrap;
751
1328
  }
752
1329
  /** A transition's label: a button that sends its event (or a plain label). */
753
- #label(tr, chip = false) {
1330
+ #label(tr, chip = false, withTarget = false) {
754
1331
  const t = this.#strings;
755
1332
  const name = tr.events.map(sendableName).find((n) => !!n);
756
1333
  const interactive = this.interactive && !!name;
757
1334
  const el = h(interactive ? "button" : "span", {
758
- class: chip ? "chip" : "label",
1335
+ class: `${chip ? "chip" : "label"} ev-chip`,
759
1336
  part: parts("transition", "edge-label"),
760
1337
  ...(interactive ? { type: "button" } : {}),
761
1338
  });
@@ -763,11 +1340,16 @@ export class ScxmlView extends ElementBase {
763
1340
  events.forEach((ev, i) => {
764
1341
  if (i)
765
1342
  el.append(" ");
766
- el.append(h("span", { part: "event" }, ev));
1343
+ // the event's name as written: the namespace quieter, its kind in the state colours
1344
+ el.append(h("span", { part: "event" }, tr.events.length ? eventName(ev) : ev));
767
1345
  });
768
1346
  if (tr.cond)
769
1347
  el.append(h("span", { class: "cond", part: "cond" }, `[${truncate(tr.cond, 22)}]`));
770
1348
  const targets = tr.targets.map((s) => s.id).join(", ");
1349
+ if (withTarget) {
1350
+ el.classList.add("portal");
1351
+ el.append(h("span", { class: "to", part: "target" }, `→ ${targets}`));
1352
+ }
771
1353
  el.setAttribute("aria-label", t.transitionLabel(tr.events.join(" ") || t.eventless, targets));
772
1354
  el.title = [tr.events.join(" ") || t.eventless, tr.cond && `[${tr.cond}]`, targets && `→ ${targets}`].filter(Boolean).join(" ");
773
1355
  if (interactive)
@@ -775,9 +1357,11 @@ export class ScxmlView extends ElementBase {
775
1357
  const session = this.#session;
776
1358
  if (!session || !name)
777
1359
  return;
778
- if (!this.#emit("scxml-send", { session, name }, true))
1360
+ const detail = { session, name, data: this.#eventData(name) };
1361
+ if (!this.#emit("scxml-send", detail, true))
779
1362
  return;
780
- session.send(name);
1363
+ this.#watchOutcome(session, name);
1364
+ session.send(name, detail.data);
781
1365
  if (this.announce !== "off")
782
1366
  this.#say(t.announceSent(name), true);
783
1367
  });
@@ -791,14 +1375,20 @@ export class ScxmlView extends ElementBase {
791
1375
  if (kind === "history")
792
1376
  return { w: 26, h: 26 };
793
1377
  if (!el)
794
- return estimateBox(s, collapsed);
1378
+ return estimateBox(s, collapsed, this.#portals.get(s));
795
1379
  const container = !collapsed && (kind === "compound" || kind === "parallel");
796
1380
  if (container) {
797
1381
  const head = el.querySelector(".head");
798
- return head ? measured(head, estimateBox(s, false)) : estimateBox(s, false);
1382
+ if (!head)
1383
+ return estimateBox(s, false, this.#portals.get(s));
1384
+ // the box has no width yet: measure the header at its own width (its chips wrap at their max-width)
1385
+ head.style.width = "max-content";
1386
+ const size = measured(head, estimateBox(s, false, this.#portals.get(s)));
1387
+ head.style.width = "";
1388
+ return size;
799
1389
  }
800
1390
  el.style.width = "max-content";
801
- const size = measured(el, estimateBox(s, collapsed));
1391
+ const size = measured(el, estimateBox(s, collapsed, this.#portals.get(s)));
802
1392
  el.style.width = "";
803
1393
  // + the active dot, hidden while measuring (7px and a 6px gap), so an active box doesn't truncate its name
804
1394
  return { w: Math.max(size.w + 13, 64), h: Math.max(size.h, 34) };
@@ -806,21 +1396,21 @@ export class ScxmlView extends ElementBase {
806
1396
  #renderNotice() {
807
1397
  const e = this.#el;
808
1398
  const t = this.#strings;
809
- if (!this.#collapsed.size) {
1399
+ const auto = [...this.#autoFolded].filter((c) => this.#collapsed.has(c));
1400
+ if (!auto.length) {
810
1401
  e.notice.hidden = true;
811
1402
  return;
812
1403
  }
813
1404
  let hidden = 0;
814
- for (const c of this.#collapsed)
1405
+ for (const c of auto)
815
1406
  hidden += countInside(c);
816
1407
  const all = h("button", { type: "button" }, t.expandAll);
817
1408
  all.addEventListener("click", () => {
818
- for (const c of this.#collapsed)
819
- this.#expandedFolds.add(c);
820
1409
  this.#collapsed.clear();
1410
+ this.#autoFolded.clear();
821
1411
  this.#renderAll();
822
1412
  });
823
- e.notice.replaceChildren(h("span", {}, t.foldedNotice(hidden, this.#collapsed.size)), all);
1413
+ e.notice.replaceChildren(h("span", {}, t.foldedNotice(hidden, auto.length)), all);
824
1414
  e.notice.hidden = false;
825
1415
  }
826
1416
  /** The chart's authoring warnings, collapsed by default; each one focuses the state it's about. */
@@ -861,25 +1451,38 @@ export class ScxmlView extends ElementBase {
861
1451
  #applyFit() {
862
1452
  const d = this.#el.diagram;
863
1453
  const layout = this.#layout;
864
- const available = this.#el.canvas.clientWidth - 24;
1454
+ const available = this.#el.canvas.clientWidth - 2 * MARGIN;
865
1455
  let scale = 1;
866
- if (layout && available > 0 && available < layout.width) {
1456
+ if (this.#zoom != null)
1457
+ scale = this.#zoom;
1458
+ else if (layout && available > 0 && available < layout.width) {
867
1459
  const raw = Number.parseFloat(getComputedStyle(this).getPropertyValue("--scxml-min-scale"));
868
1460
  const floor = this.fit ? 0 : Number.isFinite(raw) ? Math.min(1, Math.max(0.1, raw)) : DEFAULT_MIN_SCALE;
869
1461
  scale = Math.min(1, Math.max(floor, available / layout.width));
870
1462
  }
1463
+ this.#scale = scale;
1464
+ this.#el.canvas.classList.toggle("zoomed", this.#zoom != null);
1465
+ const level = this.#strings.zoomLevel(Math.round(scale * 100));
1466
+ this.#el.zoomLevel.textContent = level;
1467
+ this.#el.zoomLevel.setAttribute("aria-label", `${level}: ${this.#strings.zoomActual}`);
1468
+ this.#syncFit();
1469
+ this.#el.nav.hidden = !layout;
1470
+ // narrow: Fit is its icon, so both clusters share the bottom edge
1471
+ this.#el.viewport.toggleAttribute("data-narrow", this.#el.canvas.clientWidth > 0 && this.#el.canvas.clientWidth < 420);
871
1472
  // transform, not `zoom`: WebKit's zoom shrinks the boxes but not their text. A transform
872
- // doesn't change the layout box, so negative margins give the scroll area the scaled size.
1473
+ // doesn't change the layout box, so margins give the scroll area the scaled size.
873
1474
  d.dataset.scale = String(scale);
874
- if (!layout || scale >= 1) {
1475
+ if (!layout || scale === 1) {
875
1476
  for (const p of ["transform", "transform-origin", "margin-right", "margin-bottom"])
876
1477
  d.style.removeProperty(p);
877
- return;
878
1478
  }
879
- d.style.setProperty("transform-origin", "0 0");
880
- d.style.setProperty("transform", `scale(${scale})`);
881
- d.style.setProperty("margin-right", `${12 - layout.width * (1 - scale)}px`);
882
- d.style.setProperty("margin-bottom", `${12 - layout.height * (1 - scale)}px`);
1479
+ else {
1480
+ d.style.setProperty("transform-origin", "0 0");
1481
+ d.style.setProperty("transform", `scale(${scale})`);
1482
+ d.style.setProperty("margin-right", `${MARGIN - layout.width * (1 - scale)}px`);
1483
+ d.style.setProperty("margin-bottom", `${MARGIN - layout.height * (1 - scale)}px`);
1484
+ }
1485
+ this.#placeHelp();
883
1486
  }
884
1487
  // ───────────────────────────── live state ─────────────────────────────
885
1488
  /** Classes, parts and accessible names that depend on the configuration and the clock. */
@@ -889,6 +1492,7 @@ export class ScxmlView extends ElementBase {
889
1492
  const e = this.#el;
890
1493
  const clock = this.#playback();
891
1494
  e.controls.hidden = !clock;
1495
+ e.viewport.classList.toggle("has-controls", !!clock);
892
1496
  if (clock)
893
1497
  this.#renderControls(clock);
894
1498
  if (!session || !this.#layout)
@@ -929,6 +1533,8 @@ export class ScxmlView extends ElementBase {
929
1533
  paint(tr, el, ["transition", "edge-label"]);
930
1534
  for (const [tr, el] of this.#chips)
931
1535
  paint(tr, el, ["transition", "edge-label", "internal"]);
1536
+ for (const [tr, el] of this.#portalChips)
1537
+ paint(tr, el, ["transition", "edge-label", "portal"]);
932
1538
  for (const [tr, list] of this.#paths)
933
1539
  for (const p of list)
934
1540
  paint(tr, p, ["edge"]);
@@ -941,30 +1547,57 @@ export class ScxmlView extends ElementBase {
941
1547
  cancelAnimationFrame(this.#decayRaf);
942
1548
  this.#decayRaf = requestAnimationFrame(() => this.#renderState());
943
1549
  }
944
- if (session.status === "done" && this.#collapsed.size === 0) {
1550
+ if (session.status === "done" && e.notice.hidden) {
945
1551
  e.notice.hidden = false;
946
1552
  e.notice.replaceChildren(h("span", {}, t.terminated));
947
1553
  }
1554
+ // the first reveal after a layout jumps, later ones (steps) glide
1555
+ this.#revealActive(this.#revealed !== "");
948
1556
  }
949
1557
  #renderControls(clock) {
950
1558
  const e = this.#el;
951
1559
  const t = this.#strings;
952
- e.play.textContent = clock.playing ? t.pause : t.play;
953
- e.play.setAttribute("aria-pressed", String(!clock.playing));
954
- e.step.textContent = t.step;
1560
+ const playing = clock.playing;
1561
+ if (e.play.dataset.playing !== String(playing)) {
1562
+ e.play.dataset.playing = String(playing);
1563
+ e.play.replaceChildren(icon(playing ? icons.pause : icons.play, 16));
1564
+ const label = playing ? t.pause : t.play;
1565
+ e.play.setAttribute("aria-label", label);
1566
+ e.play.title = `${label} (${t.playKey})`;
1567
+ this.#wake();
1568
+ }
1569
+ e.play.setAttribute("aria-pressed", String(!playing));
1570
+ // stepping only means something while paused
1571
+ e.step.hidden = playing;
955
1572
  e.step.disabled = clock.pending === 0;
956
- if (e.speeds.childElementCount !== SPEEDS.length)
957
- e.speeds.replaceChildren(...SPEEDS.map(([v, text]) => {
958
- const b = h("button", { type: "button", "data-speed": String(v) }, text);
959
- b.addEventListener("click", () => {
960
- clock.speed = v;
961
- });
962
- return b;
963
- }));
964
- for (const b of e.speeds.children)
965
- b.setAttribute("aria-pressed", String(Number(b.dataset.speed) === clock.speed));
1573
+ const speed = SPEEDS.find(([v]) => v === clock.speed)?.[1] ?? `${clock.speed}×`;
1574
+ e.speeds.textContent = speed;
1575
+ e.speeds.setAttribute("aria-label", t.speedButton(speed));
966
1576
  e.clock.textContent = t.clockTime(`${(clock.now() / 1000).toFixed(1)} s`);
967
1577
  }
1578
+ #idleTimer;
1579
+ /**
1580
+ * Show the playback controls in full; while the clock plays, shrink them to the play button
1581
+ * again after a few seconds untouched. Never while the pointer is on them or keyboard focus is
1582
+ * in them (a mouse click leaves focus behind; that doesn't count). Real time: this is about the
1583
+ * person, not the chart.
1584
+ */
1585
+ #wake() {
1586
+ const controls = this.#el.controls;
1587
+ controls.classList.remove("idle");
1588
+ clearTimeout(this.#idleTimer);
1589
+ if (!this.#playback()?.playing)
1590
+ return;
1591
+ const settle = () => {
1592
+ if (!this.#playback()?.playing)
1593
+ return;
1594
+ if (controls.matches(":hover") || controls.querySelector(":focus-visible"))
1595
+ this.#idleTimer = setTimeout(settle, IDLE_MS);
1596
+ else
1597
+ controls.classList.add("idle");
1598
+ };
1599
+ this.#idleTimer = setTimeout(settle, IDLE_MS);
1600
+ }
968
1601
  }
969
1602
  // ───────────────────────────────── helpers ─────────────────────────────────
970
1603
  /** Thrown when the element has nothing to show or its attributes are malformed. */
@@ -1008,13 +1641,17 @@ function estimateLabel(tr) {
1008
1641
  const text = labelText(tr);
1009
1642
  return text ? { w: Math.ceil(text.length * 6.8 + 18), h: 20 } : { w: 0, h: 0 };
1010
1643
  }
1011
- function estimateBox(s, collapsed) {
1644
+ /** `portals`: the state's long-distance transitions, listed as chips with their target. */
1645
+ function estimateBox(s, collapsed, portals = []) {
1012
1646
  const name = s.generatedId ? s.kind : s.id;
1013
- const internal = s.transitions.filter((t) => !t.targets.length);
1014
- const chipsW = internal.slice(0, MAX_INTERNAL_SHOWN).reduce((w, t) => w + estimateLabel(t).w + 4, 0);
1015
- const w = Math.max(64, name.length * 7.6 + 34 + (s.kind === "parallel" ? 16 : 0), Math.min(chipsW, 260) + 22);
1016
- const chipRows = internal.length ? Math.ceil(Math.max(chipsW, 1) / 260) : 0;
1647
+ const internal = [...portals, ...s.transitions.filter((t) => !t.targets.length).slice(0, MAX_INTERNAL_SHOWN)];
1648
+ const targetW = (t) => (portals.includes(t) ? t.targets.map((x) => x.id).join(", ").length * 6.8 + 16 : 0);
1649
+ const chipsW = internal.reduce((w, t) => w + estimateLabel(t).w + targetW(t) + 4, 0);
1017
1650
  const isContainer = !collapsed && (s.kind === "parallel" || s.children.length > 0);
1651
+ // the help button, and the fold toggle of containers
1652
+ const icons = 22 + (isContainer || collapsed ? 18 : 0);
1653
+ const w = Math.max(64, name.length * 7.6 + 34 + icons + (s.kind === "parallel" ? 16 : 0), Math.min(chipsW, 260) + 22);
1654
+ const chipRows = internal.length ? Math.ceil(Math.max(chipsW, 1) / 260) : 0;
1018
1655
  if (isContainer)
1019
1656
  return { w, h: 26 + chipRows * 24 };
1020
1657
  return { w: collapsed ? Math.max(w, 120) : w, h: 34 + chipRows * 24 + (collapsed ? 50 : 0) };