documentation/components/source/layout-examples.ts

1import { revision as componentRevision } from "axiomatic:revision";
2import styles from "./example.css";
3import inspectionStyles from "./inspection.css";
4import { inlineObservation } from "./inline-observation.ts";
5import { ExampleReadouts } from "./example-readouts.ts";
6import {
7  widthControl,
8  clampWidth,
9  minimumWidth,
10  maximumWidth,
11  type WidthControl,
12} from "./width-control.ts";
13import {
14  updateInspection,
15  prepareInspection,
16  highlightSource,
17  describeSelection,
18  currentArrangement,
19} from "./inspection.ts";
20import { example, exampleNames, declaration } from "./composition.ts";
21import primitiveStyles from "./primitives.css";
22import { mountComposition, type MountedComposition } from "./primitives.ts";
23import { arrangementAttribute } from "./switcher-coordinator.ts";
24import type { Composition, ExampleName } from "./composition.ts";
25import {
26  atPath,
27  parentPath,
28  groupingReason,
29  neighboringMembers,
30  groupMembers,
31  ungroupMembers,
32  restoreGrouping,
33} from "./grouping.ts";
34import {
35  arrangements,
36  arrangementContracts,
37  isArrangement,
38  arrangementTarget,
39  arrangeGroup,
40  changedArrangements,
41  restoreArrangement,
42} from "./arrangement.ts";
43import {
44  restoreComposition,
45  restoreSelection,
46  chooseMember,
47  selectionOf,
48} from "./composition-editing.ts";
49import palette from "./composition-palette.generated.css";
50import "./playground.ts";
51import "./playground-page.ts";
52
53let sharedWidth = 600;
54let sharedStructure = false;
55try {
56  const saved = Number(sessionStorage.getItem("axiomatic-example-width"));
57  if (saved >= minimumWidth && saved <= maximumWidth) sharedWidth = saved;
58} catch {}
59const linkedExamples = new Set<AxiomaticExample>();
60/** What an exercise lets its reader change. Each is an explicit opt-in. */
61type Editing = "grouping" | "arrangement" | "composition";
62interface UndoEntry {
63  readonly model: Composition;
64  readonly chosen: readonly string[];
65}
66const statusMarkup =
67  '<span class="author-status" role="status" aria-live="polite"></span>';
68const historyMarkup =
69  '<span class="history"><button class="undo-action" type="button" hidden>Undo</button><button class="reset-action" type="button" hidden>Start over</button></span>';
70const arrangementMarkup = `<div class="arrangement" role="radiogroup" aria-labelledby="arrangement-label"><span class="arrangement-label" id="arrangement-label"></span><span class="arrangement-options">${arrangements.map((kind) => `<label><input type="radio" name="arrangement" value="${kind}">${kind}</label>`).join("")}</span></div>`;
71const groupingMarkup =
72  '<button class="group-action" type="button">Group</button><button class="ungroup-action" type="button" hidden>Ungroup</button>';
73const authoringMarkup: Record<Editing, string> = {
74  grouping: `<div class="authoring" role="group" aria-label="Edit grouping">${statusMarkup}${groupingMarkup}${historyMarkup}</div>`,
75  arrangement: `<div class="authoring" role="group" aria-label="Edit arrangement">${arrangementMarkup}${statusMarkup}${historyMarkup}</div>`,
76  composition: `<div class="authoring combined" role="group" aria-label="Edit composition">${arrangementMarkup}<div class="composition-actions">${groupingMarkup}<button class="clear-action" type="button" hidden>Clear selection</button></div>${statusMarkup}${historyMarkup}</div>`,
77};
78function saveWidth() {
79  try {
80    sessionStorage.setItem("axiomatic-example-width", String(sharedWidth));
81  } catch {}
82}
83function publishWidth(width: number, persist = true) {
84  sharedWidth = width;
85  if (persist) saveWidth();
86  for (const example of linkedExamples) example.receiveWidth(width);
87}
88/** What follows a tree edit in an exercise. */
89interface AppliedEdit {
90  /** Replaces the default status once. */
91  readonly message?: string;
92  /** The selection after the edit. */
93  readonly chosen?: readonly string[];
94  /** A code name to focus. Without one, focus stays where the reader put it. */
95  readonly focus?: string;
96}
97class AxiomaticExample extends HTMLElement {
98  readonly root = this.attachShadow({ mode: "open" });
99  private name: ExampleName = "flat";
100  private model: Composition = example("flat");
101  /** Names this exercise's saved state. */
102  private exercise: string | undefined;
103  private editing: Editing | undefined;
104  private chosen: string[] = [];
105  private undo: UndoEntry[] = [];
106  private width = sharedWidth;
107  private linked = true;
108  private structure = false;
109  private selected: string | undefined;
110  private pinned: string | undefined;
111  private sourceColumns = 80;
112  private characterWidth = 7.2;
113  private sourceInlineSize = 0;
114  private mounted: MountedComposition | undefined;
115  private readonly modes = new Map<string, string>();
116  private readonly modeObserver = new MutationObserver(() =>
117    this.refreshModes(),
118  );
119  private observer?: ResizeObserver;
120  private sourceObservation?: ReturnType<typeof inlineObservation>;
121  private readouts: ExampleReadouts | undefined;
122  private frame!: HTMLDivElement;
123  private viewport!: HTMLDivElement;
124  private input!: HTMLInputElement;
125  private handle!: HTMLDivElement;
126  private code!: HTMLElement;
127  private inspected: HTMLElement | undefined;
128  private captionObserver = new ResizeObserver(() => this.refreshCaption());
129  private abort?: AbortController;
130  private widthControl: WidthControl | undefined;
131  connectedCallback() {
132    const name = this.getAttribute("example");
133    const known = exampleNames.find((candidate) => candidate === name);
134    if (!known) throw new Error(`Unknown example ${name}`);
135    this.name = known;
136    this.model = example(this.name);
137    this.exercise = this.getAttribute("exercise") || undefined;
138    const edits = this.getAttribute("edits") ?? "grouping";
139    if (
140      edits !== "grouping" &&
141      edits !== "arrangement" &&
142      edits !== "composition"
143    )
144      throw new Error(`Unknown edits ${edits}`);
145    if (!this.exercise && this.hasAttribute("edits"))
146      throw new Error("An example with edits needs an exercise name");
147    this.editing = this.exercise ? edits : undefined;
148    if (this.exercise) {
149      // Saved state may contain only the edits this exercise offers.
150      const restore =
151        this.editing === "arrangement"
152          ? restoreArrangement
153          : this.editing === "composition"
154            ? restoreComposition
155            : restoreGrouping;
156      const initial = this.model;
157      try {
158        const saved = JSON.parse(
159          sessionStorage.getItem(`axiomatic-exercise:v1:${this.exercise}`) ||
160            "null",
161        );
162        this.model = restore(saved?.model, initial) ?? initial;
163        this.undo = Array.isArray(saved?.undo)
164          ? saved.undo
165              .slice(-25)
166              .map((value: unknown): UndoEntry | undefined => {
167                // Accept the earlier tree-only history as well as snapshots.
168                const entry =
169                  value && typeof value === "object" && "model" in value
170                    ? value
171                    : { model: value, chosen: [] };
172                const model = restore(entry.model, initial);
173                return model
174                  ? {
175                      model,
176                      chosen: restoreSelection(
177                        "chosen" in entry ? entry.chosen : [],
178                        model,
179                      ),
180                    }
181                  : undefined;
182              })
183              .filter(
184                (value: UndoEntry | undefined): value is UndoEntry => !!value,
185              )
186          : [];
187        if (this.editing === "composition")
188          this.chosen = [...restoreSelection(saved?.chosen, this.model)];
189      } catch {
190        /* A fresh exercise also works without storage. */
191      }
192    }
193    // The arrangement experiment opens with a group that has a parent selected,
194    // so the first choice needs no selection gesture.
195    if (this.editing === "arrangement" && "children" in this.model) {
196      const inner = this.model.children.findIndex(
197        (member) => "children" in member,
198      );
199      this.chosen = [inner < 0 ? "0" : `0.${inner}`];
200    }
201    this.abort = new AbortController();
202    const signal = this.abort.signal;
203    this.root.innerHTML = `<style>${styles}${primitiveStyles}${palette}${inspectionStyles}</style><div class="stage"><div class="viewport"><div class="bar"><button class="structure" type="button" aria-pressed="false">Show structure</button><div class="tools"><button class="link" type="button" aria-pressed="true" title="Resize linked examples together">Linked</button><label class="width"><span class="sr-only">Example width</span><input type="number" min="${minimumWidth}" max="${maximumWidth}" step="1"><span aria-hidden="true">px</span></label></div></div><div class="frame"><div class="rendered"></div><div class="resize" aria-hidden="true" title="Drag to resize. Edit the width field for keyboard control."></div></div></div></div><div class="caption"><span class="selection"></span><span class="note"></span></div>${this.name === "switcher" ? '<label class="edit">Second item label<input value="Run lasted 4m 1s" maxlength="90"></label>' : ""}${this.editing ? authoringMarkup[this.editing] : ""}<pre aria-label="Composition"><code></code></pre>`;
204    this.frame = this.get<HTMLDivElement>(".frame");
205    this.viewport = this.get<HTMLDivElement>(".viewport");
206    this.input = this.get<HTMLInputElement>(".width input");
207    this.handle = this.get<HTMLDivElement>(".resize");
208    this.code = this.get("code");
209    this.readouts = new ExampleReadouts(
210      this.get(".stage"),
211      this.viewport,
212      this.input,
213      this.get(".note"),
214      () => [...this.modes.values()],
215    );
216    if (this.editing) {
217      this.root.host.classList.add("editable");
218      for (const [selector, act] of [
219        [".undo-action", () => this.undoEdit()],
220        [".reset-action", () => this.startOver()],
221      ] as const) {
222        const button = this.get(selector);
223        button.addEventListener(
224          "click",
225          () => {
226            const focused = this.root.activeElement === button;
227            act();
228            // History becomes unavailable when nothing is left to do. Keep
229            // the reader in the editor when that happens to its focused button.
230            if (
231              this.editing !== "grouping" &&
232              focused &&
233              (button.hidden ||
234                (button instanceof HTMLButtonElement && button.disabled))
235            )
236              this.focusArrangement();
237          },
238          { signal },
239        );
240      }
241    }
242    if (this.editing === "arrangement" || this.editing === "composition")
243      this.get(".arrangement").addEventListener(
244        "change",
245        (event) => {
246          const target = arrangementTarget(this.model, this.chosen);
247          const kind = (event.target as HTMLInputElement).value;
248          if (!target || !isArrangement(kind)) return;
249          const next = arrangeGroup(this.model, target.path, kind);
250          // The strip is not rerendered, so focus stays on the chosen radio.
251          if (next !== this.model) this.commit(next, { chosen: [target.path] });
252        },
253        { signal },
254      );
255    if (this.editing === "composition") {
256      this.get(".clear-action").addEventListener(
257        "click",
258        () => {
259          const path = this.chosen[0] ?? "0";
260          this.chosen = [];
261          this.select(undefined);
262          this.updateAuthoring(
263            "Selection cleared. Choose a member or a group.",
264          );
265          this.code
266            .querySelector<HTMLElement>(`.code-name[data-path="${path}"]`)
267            ?.focus({ preventScroll: true });
268        },
269        { signal },
270      );
271    }
272    if (this.editing === "grouping" || this.editing === "composition") {
273      this.get(".group-action").addEventListener(
274        "click",
275        () => {
276          if (groupingReason(this.model, this.chosen)) return;
277          const paths = [...this.chosen];
278          const first = Math.min(
279            ...paths.map((path) => Number(path.split(".").at(-1))),
280          );
281          const group = `${parentPath(paths[0]!)}.${first}`;
282          this.commit(groupMembers(this.model, paths), {
283            message:
284              "Grouped. Neighbors outside this group remain separate members.",
285            focus: group,
286            chosen: [group],
287          });
288        },
289        { signal },
290      );
291      this.get(".ungroup-action").addEventListener(
292        "click",
293        () => {
294          const path = this.chosen[0];
295          if (!path || !this.canUngroup()) return;
296          const node = atPath(this.model, path)!;
297          if (!("children" in node)) return;
298          const first = Number(path.split(".").at(-1));
299          this.commit(ungroupMembers(this.model, path), {
300            message: "Ungrouped. The members keep their reading order.",
301            focus: path,
302            chosen: node.children.map(
303              (_, i) => `${parentPath(path)}.${first + i}`,
304            ),
305          });
306        },
307        { signal },
308      );
309    }
310    this.get(".link").addEventListener(
311      "click",
312      () => {
313        this.linked = !this.linked;
314        this.get(".link").setAttribute("aria-pressed", String(this.linked));
315        this.get(".link").textContent = this.linked ? "Linked" : "Independent";
316        if (this.linked) {
317          linkedExamples.add(this);
318          this.receiveWidth(sharedWidth);
319          this.setStructure(sharedStructure);
320        } else linkedExamples.delete(this);
321      },
322      { signal },
323    );
324    this.get(".structure").addEventListener(
325      "click",
326      () => {
327        const next = !this.structure;
328        if (this.linked) {
329          sharedStructure = next;
330          for (const example of linkedExamples) example.setStructure(next);
331        } else this.setStructure(next);
332      },
333      { signal },
334    );
335    this.widthControl = widthControl({
336      handle: this.handle,
337      viewport: this.viewport,
338      input: this.input,
339      limit: () => this.limit(),
340      request: (width, settled, maximum) =>
341        this.setWidth(width, settled, maximum),
342      restore: () => this.readouts?.refreshWidth(),
343      signal,
344    });
345    this.root.querySelector<HTMLInputElement>(".edit input")?.addEventListener(
346      "input",
347      (event) => {
348        this.model = example(
349          this.name,
350          (event.target as HTMLInputElement).value,
351        );
352        this.render();
353      },
354      { signal },
355    );
356    this.frame.addEventListener(
357      "pointermove",
358      (event) => {
359        if (
360          this.widthControl?.dragging ||
361          !this.structure ||
362          !(event.target instanceof Element)
363        )
364          return;
365        const node = event.target.closest<HTMLElement>(".node,.leaf");
366        if (node?.dataset.path) this.select(node.dataset.path);
367      },
368      { signal },
369    );
370    this.code.addEventListener(
371      "pointerover",
372      (event) => {
373        if (this.structure && event.target instanceof Element) {
374          const path =
375            event.target.closest<HTMLElement>("[data-path]")?.dataset.path;
376          if (path) this.select(path);
377        }
378      },
379      { signal },
380    );
381    this.code.addEventListener(
382      "focusin",
383      (event) => {
384        if (
385          this.structure &&
386          event.target instanceof HTMLElement &&
387          event.target.dataset.path
388        )
389          this.select(event.target.dataset.path);
390        if (
391          event.target instanceof HTMLElement &&
392          event.target.classList.contains("code-name")
393        )
394          this.rove(event.target.dataset.path!);
395      },
396      { signal },
397    );
398    this.code.addEventListener(
399      "click",
400      (event) => {
401        if (event.target instanceof Element) {
402          const path =
403            event.target.closest<HTMLElement>("[data-path]")?.dataset.path;
404          if (path && this.exercise) {
405            this.choose(path);
406            return;
407          }
408          if (path) {
409            this.setStructure(true);
410            this.pinned = path;
411            this.select(path);
412          }
413        }
414      },
415      { signal },
416    );
417    this.frame.addEventListener(
418      "click",
419      (event) => {
420        if (
421          (this.structure || this.exercise) &&
422          event.target instanceof Element
423        ) {
424          const path =
425            event.target.closest<HTMLElement>(".node,.leaf")?.dataset.path;
426          if (path && this.exercise) {
427            this.choose(path);
428            return;
429          }
430          if (path) {
431            this.pinned = path;
432            this.select(path);
433          }
434        }
435      },
436      { signal },
437    );
438    this.frame.addEventListener(
439      "pointerleave",
440      () => this.select(this.inspectionFallback()),
441      { signal },
442    );
443    this.code.addEventListener(
444      "pointerleave",
445      () => this.select(this.inspectionFallback()),
446      {
447        signal,
448      },
449    );
450    this.code.addEventListener(
451      "focusout",
452      (event) => {
453        if (
454          !(event.relatedTarget instanceof Node) ||
455          !this.code.contains(event.relatedTarget)
456        )
457          this.select(this.inspectionFallback());
458      },
459      { signal },
460    );
461    this.root.addEventListener(
462      "keydown",
463      (event) => {
464        const key = event as KeyboardEvent;
465        if (key.key === "Escape") {
466          this.pinned = undefined;
467          this.select(undefined);
468          if (this.editing) {
469            const choosing =
470              this.root.activeElement?.closest(
471                this.editing === "composition" ? ".authoring" : ".arrangement",
472              ) != null;
473            this.chosen = [];
474            this.updateAuthoring(
475              this.editing === "grouping" ? "Selection cleared." : undefined,
476            );
477            // With no group selected the choice is disabled; continue from
478            // the code, where a group can be selected.
479            if (choosing) this.focusArrangement();
480          }
481        }
482        if (
483          (this.structure || this.exercise) &&
484          (key.key === "ArrowUp" || key.key === "ArrowDown") &&
485          event.target instanceof HTMLElement &&
486          event.target.classList.contains("code-name")
487        ) {
488          const names = [
489            ...this.code.querySelectorAll<HTMLButtonElement>(".code-name"),
490          ];
491          const index = names.indexOf(event.target as HTMLButtonElement);
492          const next = names[index + (key.key === "ArrowDown" ? 1 : -1)];
493          key.preventDefault();
494          if (next) {
495            next.focus();
496          }
497        }
498      },
499      { signal },
500    );
501    this.sourceObservation = inlineObservation(this.get("pre"));
502    this.observer = new ResizeObserver((entries) => {
503      for (const entry of entries) {
504        if (entry.target === this.sourceObservation?.target) {
505          this.sourceInlineSize = entry.contentBoxSize[0]!.inlineSize;
506          this.fitSource();
507        }
508      }
509    });
510    this.observer.observe(this.sourceObservation.target);
511    this.modeObserver.observe(this.get(".rendered"), {
512      attributes: true,
513      subtree: true,
514      attributeFilter: [arrangementAttribute],
515    });
516    if (this.linked) {
517      linkedExamples.add(this);
518      this.width = sharedWidth;
519      this.structure = sharedStructure;
520    }
521    this.render();
522    this.setStructure(this.structure);
523    const refreshSourceFont = () => {
524      if (signal.aborted) return;
525      const context = document.createElement("canvas").getContext("2d");
526      if (context) {
527        context.font = getComputedStyle(this.get("pre")).font;
528        this.characterWidth = context.measureText("0").width || 7.2;
529      }
530      this.fitSource();
531    };
532    document.fonts.addEventListener("loadingdone", refreshSourceFont, {
533      signal,
534    });
535    void document.fonts.ready.then(refreshSourceFont);
536  }
537
538  disconnectedCallback() {
539    this.abort?.abort();
540    this.observer?.disconnect();
541    this.sourceObservation?.dispose();
542    this.readouts?.disconnect();
543    this.modeObserver.disconnect();
544    this.mounted?.dispose();
545    this.mounted = undefined;
546    this.captionObserver.disconnect();
547    this.inspected = undefined;
548    linkedExamples.delete(this);
549    this.widthControl?.cancel();
550    this.widthControl = undefined;
551  }
552  private get<T extends Element = HTMLElement>(selector: string): T {
553    const element = this.root.querySelector<T>(selector);
554    if (!element) throw new Error(`Missing ${selector}`);
555    return element;
556  }
557  /**
558   * The composition this example shows now, including its reader's edits.
559   * A composition is an immutable value, so a caller may keep it: later
560   * edits here produce a new one. A working copy starts from this.
561   */
562  snapshot(): Composition {
563    return this.model;
564  }
565  receiveWidth(width: number) {
566    this.width = width;
567    this.viewport.style.inlineSize = `${width}px`;
568  }
569  private limit() {
570    return this.readouts?.maximum ?? maximumWidth;
571  }
572  private setWidth(width: number, persist = true, maximum = this.limit()) {
573    if (!Number.isFinite(width)) {
574      this.readouts?.refreshWidth();
575      return;
576    }
577    this.width = clampWidth(width, maximum);
578    if (this.linked) publishWidth(this.width, persist);
579    else this.receiveWidth(this.width);
580  }
581  private render() {
582    const rendered = this.get(".rendered");
583    if (this.mounted) this.mounted.update(this.model);
584    else this.mounted = mountComposition(rendered, this.model);
585    prepareInspection(rendered);
586    this.renderCode();
587    this.refreshModes();
588    this.readouts?.observeComposition(rendered);
589    if (this.exercise) this.updateAuthoring();
590    else this.updateInspection();
591    this.receiveWidth(this.width);
592  }
593  private fitSource() {
594    if (!this.sourceInlineSize) return;
595    const columns = Math.max(
596      16,
597      Math.min(80, Math.floor(this.sourceInlineSize / this.characterWidth)),
598    );
599    if (columns === this.sourceColumns) return;
600    this.sourceColumns = columns;
601    const active = this.root.activeElement;
602    const focused =
603      active instanceof HTMLElement && active.classList.contains("code-name")
604        ? active.dataset.path
605        : undefined;
606    this.renderCode();
607    if (this.exercise) this.updateAuthoring();
608    if (focused) {
609      this.rove(focused);
610      this.code
611        .querySelector<HTMLElement>(`.code-name[data-path="${focused}"]`)
612        ?.focus({ preventScroll: true });
613    }
614  }
615  private renderCode() {
616    const lines = declaration(this.model, "0", 0, this.sourceColumns);
617    const fragment = document.createDocumentFragment();
618    for (const line of lines) {
619      const row = document.createElement("span");
620      row.className = "code-line";
621      row.style.setProperty("--continuation", `${(line.depth + 1) * 2}ch`);
622      if (line.path) row.dataset.path = line.path;
623      for (const token of line.tokens) {
624        const span = document.createElement(token.kind ? "button" : "span");
625        span.className = `token ${token.tone ?? "plain"}${token.kind ? " code-name" : ""}`;
626        span.textContent = token.text;
627        if (token.path) span.dataset.path = token.path;
628        if (token.kind) {
629          span.setAttribute("type", "button");
630          const node = atPath(this.model, token.path!);
631          span.setAttribute(
632            "aria-label",
633            node && !("children" in node)
634              ? `${this.exercise ? "Select" : "Inspect"} ${node.kind}: ${node.text}`
635              : `${this.exercise ? "Select" : "Inspect"} ${token.kind} group`,
636          );
637          span.tabIndex = this.structure || this.exercise ? 0 : -1;
638        }
639        row.append(span);
640      }
641      fragment.append(row);
642    }
643    this.code.replaceChildren(fragment);
644    if (this.exercise) this.rove("0");
645    highlightSource(this.code, this.structure, this.selected);
646    this.refreshAccessibleNames();
647  }
648  private canUngroup() {
649    const node =
650      this.chosen.length === 1
651        ? atPath(this.model, this.chosen[0]!)
652        : undefined;
653    return !!node && "children" in node && this.chosen[0] !== "0";
654  }
655  private inspectionFallback() {
656    return this.exercise
657      ? this.chosen.length === 1
658        ? this.chosen[0]
659        : undefined
660      : this.pinned;
661  }
662  private rove(path: string) {
663    for (const name of this.code.querySelectorAll<HTMLElement>(".code-name"))
664      name.tabIndex = name.dataset.path === path ? 0 : -1;
665  }
666  private choose(path: string) {
667    if (!atPath(this.model, path)) return;
668    let notice: string | undefined;
669    if (this.editing === "composition") {
670      this.chosen = [...chooseMember(this.model, this.chosen, path)];
671    } else if (this.editing === "arrangement") {
672      // One node at a time, at any level; Escape clears it. A fact can be
673      // selected, and then there is no group to arrange: it never stands for
674      // its parent.
675      this.chosen = [path];
676    } else if (path === "0") {
677      this.chosen = [];
678      notice =
679        "This Stack holds the whole example. Choose members inside it to make a group.";
680    } else if (this.chosen.includes(path)) {
681      this.chosen = this.chosen.filter((value) => value !== path);
682      // Removing the middle of a run starts a fresh selection as well.
683      if (
684        this.chosen.length > 1 &&
685        !neighboringMembers(this.model, this.chosen)
686      )
687        this.chosen = [this.chosen[0]!];
688    } else {
689      const next = [...this.chosen, path];
690      if (this.chosen.length && !neighboringMembers(this.model, next)) {
691        this.chosen = [path];
692        notice = "Only neighbors can be grouped here. Order stays as written.";
693      } else this.chosen = next;
694    }
695    this.rove(path);
696    this.select(this.inspectionFallback());
697    this.updateAuthoring(notice);
698  }
699  /** Shows the grouping actions the selection permits; returns its status. */
700  private updateGrouping(): string {
701    const reason = groupingReason(this.model, this.chosen);
702    const group = this.get<HTMLButtonElement>(".group-action");
703    group.hidden = !!reason;
704    group.textContent = `Group ${this.chosen.length} members`;
705    this.get<HTMLButtonElement>(".ungroup-action").hidden = !this.canUngroup();
706    return this.canUngroup()
707      ? "Add a neighbor to compose a larger group."
708      : this.chosen.length === 1
709        ? "1 member selected. Select a neighbor to group them."
710        : this.chosen.length >= 2
711          ? reason || `${this.chosen.length} members selected. Ready to group.`
712          : "Choose two neighboring facts.";
713  }
714  /** Points the arrangement choice at the selected group; returns its status. */
715  private updateArrangement(): string {
716    const target = arrangementTarget(this.model, this.chosen);
717    const choice = this.get(".arrangement");
718    choice.setAttribute("aria-disabled", String(!target));
719    const count = target?.group.children.length;
720    this.get(".arrangement-label").textContent = !target
721      ? "Arrange a group as"
722      : count === 1
723        ? "Arrange this member as"
724        : `Arrange these ${count} members as`;
725    for (const input of choice.querySelectorAll("input")) {
726      input.disabled = !target;
727      input.checked = input.value === target?.group.kind;
728    }
729    if (target) return arrangementContracts[target.group.kind];
730    const [path] = this.chosen;
731    const selected = path === undefined ? undefined : atPath(this.model, path);
732    return selected
733      ? `${selected.kind} is content, with no members to arrange. Select a group's name in the code.`
734      : "Select a group's name in the code to arrange its members.";
735  }
736  /** Returns focus to the arrangement choice, or to the code when no group
737   * is selected and the choice is disabled. */
738  private focusArrangement() {
739    (
740      this.root.querySelector<HTMLElement>(".arrangement input:checked") ??
741      this.code.querySelector<HTMLElement>('.code-name[tabindex="0"]')
742    )?.focus({ preventScroll: true });
743  }
744  private updateAuthoring(message?: string) {
745    let status: string;
746    if (this.editing === "composition") {
747      const arrangement = this.updateArrangement();
748      const selected = selectionOf(this.model, this.chosen);
749      const group = this.get<HTMLButtonElement>(".group-action");
750      group.hidden = false;
751      group.disabled = selected.selected !== "members" || !selected.canGroup;
752      group.textContent = "Group";
753      const ungroup = this.get<HTMLButtonElement>(".ungroup-action");
754      ungroup.hidden = false;
755      ungroup.disabled = selected.selected !== "group" || !selected.canUngroup;
756      const clear = this.get<HTMLButtonElement>(".clear-action");
757      clear.hidden = false;
758      clear.disabled = !this.chosen.length;
759      switch (selected.selected) {
760        case "group":
761          status = arrangement;
762          break;
763        case "members":
764          status = selected.canGroup
765            ? `${this.chosen.length} members selected. Group them, or select one again to leave it out.`
766            : "These are all the members of one group. Select that group's name to arrange it.";
767          break;
768        case "content":
769          status = "1 member selected. Select a neighbor to group them.";
770          break;
771        case "nothing":
772          status =
773            "Select neighboring facts to group them, or a group's name to arrange it.";
774      }
775    } else
776      status =
777        this.editing === "arrangement"
778          ? this.updateArrangement()
779          : this.updateGrouping();
780    const undo = this.get<HTMLButtonElement>(".undo-action");
781    const reset = this.get<HTMLButtonElement>(".reset-action");
782    const initial =
783      JSON.stringify(this.model) === JSON.stringify(example(this.name));
784    undo.hidden = this.editing !== "composition" && !this.undo.length;
785    reset.hidden = this.editing !== "composition" && initial;
786    undo.disabled = !this.undo.length;
787    reset.disabled = initial;
788    this.get(".author-status").textContent = message ?? status;
789    for (const element of this.frame.querySelectorAll<HTMLElement>(
790      ".node,.leaf",
791    )) {
792      const chosen = this.chosen.includes(element.dataset.path!);
793      element.dataset.chosen = String(chosen);
794    }
795    for (const element of this.code.querySelectorAll<HTMLElement>(
796      "[data-path]",
797    )) {
798      const path = element.dataset.path!;
799      element.dataset.chosen = String(
800        this.chosen.some(
801          (choice) => path === choice || path.startsWith(`${choice}.`),
802        ),
803      );
804      if (element.classList.contains("code-name"))
805        element.setAttribute(
806          "aria-pressed",
807          String(this.chosen.includes(path)),
808        );
809    }
810    this.updateInspection();
811  }
812  private undoEdit() {
813    const entry = this.undo.pop();
814    if (!entry) return;
815    const previous = entry.model;
816    if (this.editing === "composition") {
817      this.applyEdit(previous, {
818        message: "Undid the last change. Restored its selection.",
819        chosen: entry.chosen,
820      });
821      return;
822    }
823    if (this.editing !== "arrangement") {
824      this.applyEdit(previous, {
825        message: "Undid the last change.",
826        focus: "0",
827      });
828      return;
829    }
830    // Arrangement edits keep every path, so the group whose arrangement comes
831    // back can be selected to show what was undone.
832    const changed = changedArrangements(this.model, previous);
833    const restored =
834      changed.length === 1 ? arrangementTarget(previous, changed) : undefined;
835    this.applyEdit(previous, {
836      message: restored
837        ? `Undid the last change. This group is a ${restored.group.kind} again.`
838        : "Undid the last change.",
839      chosen: restored ? [restored.path] : this.chosen,
840    });
841  }
842  private startOver() {
843    if (this.editing === "composition") {
844      this.commit(example(this.name), {
845        message: "Returned to one sequence. Undo restores your composition.",
846        chosen: [],
847      });
848    } else if (this.editing === "arrangement")
849      this.commit(example(this.name), {
850        message:
851          "Returned to the starting arrangement. Undo restores your choices.",
852        chosen: this.chosen,
853      });
854    else
855      this.commit(example(this.name), {
856        message: "Returned to one sequence. Undo can restore your grouping.",
857        focus: "0",
858      });
859  }
860  private commit(next: Composition, edit: AppliedEdit) {
861    this.undo = [
862      ...this.undo.slice(-24),
863      { model: this.model, chosen: [...this.chosen] },
864    ];
865    this.applyEdit(next, edit);
866  }
867  private applyEdit(
868    next: Composition,
869    { message, chosen = [], focus }: AppliedEdit,
870  ) {
871    this.model = next;
872    this.chosen = [...chosen];
873    this.pinned = undefined;
874    this.selected = undefined;
875    this.render();
876    this.selected = this.inspectionFallback();
877    this.rove(focus ?? this.chosen[0] ?? "0");
878    this.updateAuthoring(message);
879    try {
880      sessionStorage.setItem(
881        `axiomatic-exercise:v1:${this.exercise}`,
882        JSON.stringify({
883          model: this.model,
884          undo: this.undo,
885          chosen: this.chosen,
886        }),
887      );
888    } catch {}
889    if (focus)
890      this.code
891        .querySelector<HTMLButtonElement>(`.code-name[data-path="${focus}"]`)
892        ?.focus({ preventScroll: true });
893  }
894  private setStructure(value: boolean) {
895    this.structure = value;
896    this.get(".structure").setAttribute("aria-pressed", String(value));
897    this.get(".structure").textContent = value
898      ? "Hide structure"
899      : "Show structure";
900    this.code.classList.toggle("inspecting", value);
901    if (!value) {
902      this.selected = undefined;
903      this.pinned = undefined;
904    }
905    for (const b of this.code.querySelectorAll<HTMLElement>(".code-name"))
906      b.tabIndex = value || this.exercise ? 0 : -1;
907    if (this.exercise) {
908      this.rove(this.chosen[0] ?? "0");
909      this.selected = this.inspectionFallback();
910    }
911    this.updateInspection();
912  }
913  private select(path: string | undefined) {
914    if (this.selected === path) return;
915    this.selected = path;
916    this.updateInspection();
917  }
918  /** Effective modes can be derived from an ancestor's published arrangement.
919   * Observe that semantic signal, then read CSS only for the teaching labels. */
920  private refreshModes() {
921    this.modes.clear();
922    for (const node of this.get(".rendered").querySelectorAll<HTMLElement>(
923      '[data-kind="Switcher"]',
924    )) {
925      this.modes.set(node.dataset.path!, getComputedStyle(node).flexDirection);
926    }
927    this.readouts?.refreshModes();
928    this.refreshAccessibleNames();
929    this.refreshCaption();
930  }
931  private refreshAccessibleNames() {
932    // Grouping exercises contain Stacks alone; their names say what a click does.
933    if (this.editing === "grouping") return;
934    for (const button of this.code.querySelectorAll<HTMLElement>(
935      ".code-name",
936    )) {
937      const path = button.dataset.path!;
938      const node = atPath(this.model, path);
939      if (!node || !("children" in node)) continue;
940      const direction =
941        node.kind === "Stack"
942          ? "column"
943          : node.kind === "Shelf"
944            ? "row"
945            : (this.modes.get(path) ?? "column");
946      const name = `${this.editing ? "Select" : "Inspect"} ${node.kind}, ${currentArrangement(node.kind, direction === "row")}, ${node.children.length} members`;
947      if (button.getAttribute("aria-label") !== name)
948        button.setAttribute("aria-label", name);
949    }
950  }
951  private updateInspection() {
952    highlightSource(this.code, this.structure, this.selected);
953    const selected = updateInspection(this.get(".rendered"), {
954      structure: this.structure,
955      selected:
956        this.structure || this.chosen.length ? this.selected : undefined,
957      preview:
958        this.editing === "grouping" && !groupingReason(this.model, this.chosen)
959          ? this.chosen
960          : [],
961    });
962    if (selected !== this.inspected) {
963      this.captionObserver.disconnect();
964      this.inspected = selected;
965      if (selected) {
966        // A primitive has one uniform gap: the first adjacent pair suffices.
967        for (const band of [
968          ...selected.querySelectorAll(
969            ':scope > [data-decoration="gap"] [data-observation="gap"]',
970          ),
971        ].slice(0, 2))
972          this.captionObserver.observe(band);
973      }
974    }
975    this.refreshCaption();
976  }
977  private refreshCaption() {
978    const caption = this.get(".selection");
979    const text = describeSelection(this.inspected);
980    if (caption.textContent !== text) caption.textContent = text;
981  }
982}
983if (!customElements.get("axiomatic-example"))
984  customElements.define("axiomatic-example", AxiomaticExample);
985
986// The pinned reader emits this event when source inputs change. Until it exposes
987// a component lifecycle hook, refresh only when this component's bundle changed.
988if (
989  document
990    .querySelector('meta[name="reader-sources"]')
991    ?.getAttribute("content") !== "fixed"
992) {
993  document.addEventListener("reader-sources-changed", () => {
994    void fetch(import.meta.url, { cache: "no-store" })
995      .then((response) => (response.ok ? response.text() : ""))
996      .then((source) => {
997        const revision = source.match(/axiomatic-revision:([a-f0-9]+)/)?.[1];
998        if (revision && `axiomatic-revision:${revision}` !== componentRevision)
999          location.reload();
1000      })
1001      .catch(() => {
1002        /* Preserve the live example if the local reader is restarting. */
1003      });
1004  });
1005}