documentation/components/source/playground.ts

1/**
2 * "Compose your own": an empty composition or a working copy of an exercise
3 * that its author can rewrite, add to, rearrange and move members within.
4 *
5 * There is one composition, one selection, one declaration and one history.
6 * Two previews show that composition at once, each in a host of its own
7 * size. The hosts are demonstration slots sized by CSS; nothing in the
8 * composition knows their widths.
9 *
10 * The editor has two faces over that one working copy. The same edits,
11 * rewording and moves are behind both.
12 *
13 * - In a lesson (`source-exercise`) it is the strip the lesson teaches. Every
14 *   control stays in place, each click builds on the selection, and the
15 *   declaration is where a group is chosen. The first composition is empty
16 *   or copied, on request, from the live exercise. After that it is saved on
17 *   its own and is replaced only when its author asks, as one undoable edit.
18 * - On its own page (`standalone`) it is a workbench for someone who has not
19 *   read the lesson. A click selects one thing. An outline, or the
20 *   declaration in its place, lists every node. An inspector names the
21 *   selection and offers what applies to it. The page supplies the working
22 *   copy and saves it.
23 */
24import styles from "./example.css";
25import { encodeSnapshot } from "./snapshot.ts";
26import { playgroundURL } from "./playground-link.ts";
27import primitiveStyles from "./primitives.css";
28import inspectionStyles from "./inspection.css";
29import palette from "./composition-palette.generated.css";
30import playgroundStyles from "./playground.css";
31import outlineStyles from "./outline-panel.css";
32import {
33  arrangeGroup,
34  arrangementContracts,
35  arrangements,
36  isArrangement,
37} from "./arrangement.ts";
38import {
39  example,
40  exampleNames,
41  Stack,
42  type Composition,
43  type Primitive,
44} from "./composition.ts";
45import { chooseMember } from "./composition-editing.ts";
46import { CompositionPreview } from "./composition-preview.ts";
47import { atPath, parentPath } from "./grouping.ts";
48import { OutlinePanel } from "./outline-panel.ts";
49import { SourcePanel } from "./source-panel.ts";
50import { selectionAfter, subjectOf } from "./workbench-selection.ts";
51import {
52  moveMembers,
53  moveObstacle,
54  moveObstacles,
55  movesFor,
56  placeBefore,
57  placeAfter,
58  placeAtEnd,
59} from "./movement.ts";
60import { clampWidth, maximumWidth } from "./width-control.ts";
61import {
62  addText,
63  addGroup,
64  blankComposition,
65  contentKinds,
66  editContentKind,
67  isContentKind,
68  beginTextEdit,
69  cancelTextEdit,
70  commitEdit,
71  editsFor,
72  finishTextEdit,
73  releaseGroup,
74  removeMember,
75  restoreWorkingCopy,
76  restoreWorkingTree,
77  startWorkingCopy,
78  typeText,
79  undoEdit,
80  wrapMembers,
81  type Edited,
82  type Insertion,
83  type TextEdit,
84  type WorkingCopy,
85  type WorkingEdits,
86} from "./working-copy.ts";
87
88const members = (count: number) =>
89  count === 1 ? "1 member" : `${count} members`;
90
91type Placement = "before" | "inside" | "after";
92const placements: readonly Placement[] = ["before", "inside", "after"];
93const placementLabels = {
94  before: "Before",
95  inside: "Inside at end",
96  after: "After",
97};
98
99const roleDescriptions = {
100  Text: "Text carries the main wording.",
101  Heading: "Heading names a section of the composition.",
102  Meta: "Meta supplies supporting context, such as an update time.",
103};
104
105/** What each arrangement does, in a few words beside its name. */
106const arrangementHints: Record<Primitive, string> = {
107  Stack: "one column",
108  Shelf: "one row",
109  Switcher: "a row when it fits",
110};
111
112/** A name grounded in the content, while the highlighted box/code gives its location. */
113function describeMember(node: Composition): string {
114  const short = (text: string) => {
115    const words = text.replace(/\s+/g, " ").trim();
116    return words.length > 64 ? `${words.slice(0, 63)}…` : words;
117  };
118  if (!("children" in node))
119    return `${node.kind}: “${short(node.text) || "empty text"}”`;
120  if (!node.children.length) return `empty ${node.kind}`;
121  const firstText = (member: Composition): string =>
122    "children" in member
123      ? (member.children.map(firstText).find(Boolean) ?? "")
124      : short(member.text);
125  const text = firstText(node);
126  return `${node.kind}, ${members(node.children.length)}${text ? `, starting with “${short(text)}”` : ""}`;
127}
128
129/** Choosing where a move goes. Both faces show it in place of their controls. */
130const moveMarkup = `<div class="move-controls" hidden><span class="move-source"></span><span class="move-destination"></span><div class="move-placements" role="group" aria-label="Place the moving members">${placements.map((placement) => `<button class="place-${placement}" type="button">${placementLabels[placement]}</button>`).join("")}<button class="cancel-move" type="button">Cancel</button></div></div>`;
131
132/** The lesson's strip: every control in its place, enabled when it applies. */
133const stripMarkup = `
134<div class="starter">
135  <button class="start-action" type="button">Copy investigation</button>
136  <button class="start-blank" type="button">Start blank</button>
137  <span class="starter-note"></span>
138</div>
139<div class="workspace" hidden>
140  <div class="bar"><button class="structure" type="button" aria-pressed="false">Show structure</button><button class="open-playground" type="button">Open in playground ↗</button></div>
141  <div class="previews"></div>
142  <div class="editor-panel">
143  <div class="authoring combined working" role="group" aria-label="Edit your composition">
144    <label class="edit text-edit">Wording<input class="text-field" type="text" autocomplete="off" spellcheck="true" disabled></label>
145    <div class="content-role arrangement" role="radiogroup" aria-labelledby="role-label" aria-describedby="author-status" hidden>
146      <span class="arrangement-label" id="role-label">Content role</span>
147      <span class="arrangement-options">${contentKinds.map((kind) => `<label><input type="radio" name="content-role" value="${kind}">${kind}</label>`).join("")}</span>
148    </div>
149    <div class="group-arrangement arrangement" role="radiogroup" aria-labelledby="arrangement-label">
150      <span class="arrangement-label" id="arrangement-label"></span>
151      <span class="arrangement-options">${arrangements.map((kind) => `<label><input type="radio" name="arrangement" value="${kind}">${kind}</label>`).join("")}</span>
152    </div>
153    <div class="creation">
154      <label>Add <select class="new-member" aria-label="Kind of new member"><option value="Text">Text</option>${arrangements.map((kind) => `<option value="${kind}">Empty ${kind}</option>`).join("")}</select></label>
155      <button class="inside-action" type="button"></button>
156      <button class="after-action" type="button"></button>
157    </div>
158    <div class="composition-actions">
159      <button class="group-action" type="button">Group</button><button class="ungroup-action" type="button">Ungroup</button><button class="move-action" type="button">Move</button><button class="remove-action" type="button">Remove</button><button class="clear-action" type="button">Clear selection</button>
160    </div>
161    ${moveMarkup}
162    <span class="author-status" id="author-status" role="status" aria-live="polite"></span>
163    <span class="history"><button class="undo-action" type="button">Undo</button><button class="blank-action" type="button">Start blank</button><button class="copy-action" type="button"></button></span>
164  </div>
165  <pre aria-label="Your composition"><code></code></pre>
166  </div>
167</div>`;
168
169/**
170 * The workbench: the result in two spaces above; below, the hierarchy beside
171 * an inspector for whatever is selected in it. Undo and the blank start act
172 * on the whole composition, so they sit apart from the inspector.
173 */
174const workbenchMarkup = `
175<div class="workspace workbench" hidden>
176  <section class="results" aria-labelledby="results-title">
177    <div class="results-head">
178      <div><h2 id="results-title">One composition, two spaces</h2><p class="results-hint">Select a part in either view. Drag the wide card’s edge to change its space.</p></div>
179      <div class="document-actions"><button class="undo-action" type="button">Undo</button><button class="blank-action" type="button" title="Replace this composition with an empty one. Undo restores it.">Start blank</button><button class="structure" type="button" aria-pressed="false">Show structure</button></div>
180    </div>
181    <div class="result-views" role="group" aria-label="Wide card and narrow rail" tabindex="0">
182      <div class="preview-limit" aria-hidden="true"></div>
183      <div class="previews"></div>
184      <p class="empty-hint" hidden>This composition is empty. Add text or an empty group below.</p>
185    </div>
186  </section>
187  <div class="editing" role="group" aria-label="Edit your composition">
188    <section class="hierarchy" aria-labelledby="hierarchy-title">
189      <div class="hierarchy-head"><h2 id="hierarchy-title">Composition</h2><button class="several" type="button" aria-pressed="false">Select several</button></div>
190      <div class="view-choice" role="group" aria-label="Show the composition as"><button class="show-outline" type="button" aria-pressed="true">Outline</button><button class="show-code" type="button" aria-pressed="false">Code</button></div>
191      <p class="select-help" hidden>Choose neighboring members to group or move them together.</p>
192      <div class="outline" role="group" aria-label="Composition outline"></div>
193      <div class="source" hidden><pre aria-label="Composition code"><code></code></pre></div>
194    </section>
195    <section class="inspector" aria-label="Selected part">
196      <div class="inspector-body">
197        <div class="selection-context"><button class="parent" type="button" hidden></button><h2 class="selected-title"></h2><span class="selected-detail"></span></div>
198        <label class="wording">Wording<input class="text-field" type="text" autocomplete="off" spellcheck="true" disabled></label>
199        <fieldset class="content-role choice" aria-describedby="role-purpose" hidden>
200          <legend>Content role</legend>
201          ${contentKinds.map((kind) => `<label><input type="radio" name="content-role" value="${kind}">${kind}</label>`).join("")}
202          <p class="role-purpose" id="role-purpose"></p>
203        </fieldset>
204        <fieldset class="group-arrangement choice" aria-describedby="arrangement-purpose" hidden>
205          <legend>Arrangement</legend>
206          ${arrangements.map((kind) => `<label><input type="radio" name="arrangement" value="${kind}"><span>${kind} <small>${arrangementHints[kind]}</small></span></label>`).join("")}
207          <p class="arrangement-purpose" id="arrangement-purpose"></p>
208        </fieldset>
209        <div class="add-area">
210          <span class="insertion-context"></span><button class="place-toggle" type="button" hidden></button>
211          <div class="add-actions"><button class="add-text" type="button">Add text</button><span class="add-groups" role="group" aria-label="Add an empty group"><span>or an empty group</span>${arrangements.map((kind) => `<button type="button" data-add="${kind}" title="Arranged as ${arrangementHints[kind]}">${kind}</button>`).join("")}</span></div>
212        </div>
213        <div class="selection-actions"><button class="group-action" type="button">Group in a Stack</button><button class="ungroup-action" type="button">Ungroup</button><button class="move-action" type="button">Move</button><button class="remove-action" type="button">Remove</button></div>
214      </div>
215      ${moveMarkup}
216      <p class="author-status" id="author-status" role="status" aria-live="polite"></p>
217    </section>
218  </div>
219</div>`;
220
221/** Where keyboard focus belongs after an edit. */
222type Focus =
223  /** The name of the node at this path in the hierarchy. */
224  | { readonly name: string }
225  /** The text field, with its text selected for replacement. */
226  | "text"
227  /** Ready to fill a just-created empty group. */
228  | "inside"
229  /** A completed move returns directly to its controls. */
230  | "move"
231  /** Where the author put it, unless that control is now unavailable. */
232  | "stay";
233
234/**
235 * A view of the hierarchy in which any node can be chosen, including a group
236 * with no members: the declaration, or the outline.
237 */
238interface HierarchyView {
239  show(model: Composition): void;
240  mark(chosen: readonly string[]): void;
241  destination(path: string | undefined, moving: boolean): void;
242  inspect(structure: boolean, path: string | undefined): void;
243  rove(path: string): void;
244  focus(path: string): void;
245}
246
247/** Which hierarchy a workbench shows. It outlasts one draft's editor. */
248let preferredHierarchy: "outline" | "code" = "outline";
249
250export interface PlaygroundState {
251  readonly copy: WorkingCopy;
252  readonly width: number;
253}
254
255export class AxiomaticPlayground extends HTMLElement {
256  /** The standalone host supplies and persists editor state. */
257  initialState: PlaygroundState | undefined;
258  get isMoving(): boolean {
259    return !!this.moving;
260  }
261  finishEditing(): PlaygroundState | undefined {
262    this.finishText();
263    return this.workingState;
264  }
265  prepareToLeave(): PlaygroundState | undefined {
266    if (this.moving) this.cancelMove(false);
267    if (this.several) {
268      this.several = false;
269      this.refresh();
270    }
271    return this.finishEditing();
272  }
273  get workingState(): PlaygroundState | undefined {
274    if (!this.copy) return undefined;
275    return {
276      copy: this.textEdit
277        ? finishTextEdit(this.copy, this.textEdit)
278        : this.copy,
279      width: this.width,
280    };
281  }
282  readonly root = this.attachShadow({ mode: "open" });
283  /** The exercise whose composition this working copy starts from. */
284  private source = "";
285  /** On its own page: the workbench, with state held by the page. */
286  private standalone = false;
287  private copy: WorkingCopy | undefined;
288  /** The rewording in progress. Typing changes the copy; history waits. */
289  private textEdit: TextEdit | undefined;
290  /** A proposed destination; the authored model and source selection stay put. */
291  private moving:
292    { readonly members: readonly string[]; target?: string } | undefined;
293  /** Workbench: the author asked for clicks to build on the selection. */
294  private several = false;
295  /** Workbench: add after the selected group, where inside is the default. */
296  private addAfter = false;
297  private structure = false;
298  /** The node under the pointer or focus, shown while structure is on. */
299  private attended: string | undefined;
300  private width = 600;
301  private previews: CompositionPreview[] = [];
302  private code: SourcePanel | undefined;
303  private outline: OutlinePanel | undefined;
304  private abort: AbortController | undefined;
305
306  connectedCallback() {
307    const source = this.getAttribute("source-exercise");
308    this.standalone = this.hasAttribute("standalone");
309    if (!source && !this.standalone)
310      throw new Error("A playground needs a source-exercise");
311    this.source = source ?? "investigation";
312    this.abort = new AbortController();
313    const signal = this.abort.signal;
314    this.root.innerHTML = `<style>${styles}${primitiveStyles}${palette}${inspectionStyles}${playgroundStyles}${this.standalone ? outlineStyles : ""}</style>${this.standalone ? workbenchMarkup : stripMarkup}`;
315    this.classList.add("editable");
316    this.wireEditing(signal);
317    if (this.standalone) this.wireWorkbench(signal);
318    else this.wireStrip(signal);
319
320    if (this.standalone) {
321      this.copy = this.withSubject(
322        this.initialState?.copy ?? startWorkingCopy(Stack()),
323      );
324      this.width = this.initialState?.width ?? 600;
325    } else this.copy = this.load();
326    this.previews = [
327      new CompositionPreview(this.ownerDocument, {
328        label: "Wide card",
329        slot: "wide",
330        width: {
331          initial: this.width,
332          // The workbench's card is as wide as it was asked to be, so it
333          // cannot say how wide it may become. An independent box does.
334          ...(this.standalone
335            ? { availableSpace: this.get(".preview-limit") }
336            : {}),
337          changed: (width, settled) => {
338            this.width = width;
339            if (settled) this.save();
340          },
341        },
342        choose: (path) => this.choose(path),
343        attend: (path) => this.attend(path),
344      }),
345      new CompositionPreview(this.ownerDocument, {
346        label: "Narrow rail",
347        slot: "rail",
348        choose: (path) => this.choose(path),
349        attend: (path) => this.attend(path),
350      }),
351    ];
352    this.get(".previews").append(
353      ...this.previews.map((preview) => preview.element),
354    );
355    this.code = new SourcePanel(this.get("pre"), {
356      describe: (path, node) => this.describe(path, node),
357      choose: (path, extend) => this.choose(path, extend),
358      attend: (path) => this.attend(path),
359      // The workbench's declaration scrolls in a box of its own.
360      revealFocus: this.standalone,
361      signal,
362    });
363
364    if (this.copy) this.open();
365  }
366
367  disconnectedCallback() {
368    this.finishText();
369    this.abort?.abort();
370    this.abort = undefined;
371    for (const preview of this.previews) preview.dispose();
372    this.previews = [];
373    this.code?.dispose();
374    this.code = undefined;
375    this.outline = undefined;
376    this.copy = undefined;
377    this.moving = undefined;
378    this.several = false;
379    this.addAfter = false;
380    this.attended = undefined;
381  }
382
383  private get<T extends Element = HTMLElement>(selector: string): T {
384    const element = this.root.querySelector<T>(selector);
385    if (!element) throw new Error(`Missing ${selector}`);
386    return element;
387  }
388  private on(selector: string, type: string, listener: () => void) {
389    this.get(selector).addEventListener(type, listener, {
390      signal: this.abort!.signal,
391    });
392  }
393  private get storageKey() {
394    return `axiomatic-playground:v1:${this.source}`;
395  }
396
397  /** The hierarchy on screen: the declaration, or the workbench's outline. */
398  private get hierarchy(): HierarchyView | undefined {
399    return this.standalone && preferredHierarchy === "outline"
400      ? this.outline
401      : this.code;
402  }
403
404  /** A working copy as this face shows it. The workbench always has a
405   * subject; a lesson's strip may have nothing selected. */
406  private withSubject(copy: WorkingCopy): WorkingCopy {
407    return this.standalone ? { ...copy, chosen: subjectOf(copy.chosen) } : copy;
408  }
409
410  /** The accessible name of a node in the hierarchy. */
411  private describe(path: string, node: Composition): string {
412    if (this.moving)
413      return `${this.moving.members.includes(path) ? (path === this.moving.target ? "Moving member, chosen as destination" : "Moving member") : path === this.moving.target ? "Destination" : "Choose destination"}: ${describeMember(node)}`;
414    if (this.standalone)
415      return `${path === "0" ? "Whole composition: " : ""}${describeMember(node)}`;
416    return "children" in node
417      ? `Select ${node.kind} group, ${node.children.length ? members(node.children.length) : "empty"}`
418      : `Select ${node.kind}: ${node.text || "empty"}`;
419  }
420
421  /** The controls both faces have: one composition, edited the same way. */
422  private wireEditing(signal: AbortSignal) {
423    this.on(".blank-action", "click", () => this.startBlank());
424    this.on(".structure", "click", () => {
425      this.structure = !this.structure;
426      if (!this.structure) this.attended = undefined;
427      this.refresh();
428    });
429    this.on(".text-field", "input", () => this.typeText());
430    this.on(".text-field", "blur", () => {
431      if (this.finishText()) this.refresh();
432    });
433    this.get(".text-field").addEventListener(
434      "keydown",
435      (event) => {
436        // Enter and Escape that confirm or cancel an input method's
437        // composition belong to it, not to this edit.
438        if (event.isComposing || event.keyCode === 229) {
439          event.stopPropagation();
440          return;
441        }
442        if (event.key === "Enter") {
443          if (this.finishText()) this.refresh();
444        } else if (event.key === "Escape" && this.textEdit) {
445          // The first Escape abandons the rewording; the selection stays.
446          event.stopPropagation();
447          this.cancelText();
448        }
449      },
450      { signal },
451    );
452    this.get(".group-arrangement").addEventListener(
453      "change",
454      (event) => {
455        if (this.moving) return;
456        const kind = (event.target as HTMLInputElement).value;
457        const target = this.edits()?.arrange;
458        if (!this.copy || !target || !isArrangement(kind)) return;
459        const tree = arrangeGroup(this.copy.model, target.path, kind);
460        // The controls are not rerendered, so focus stays on the chosen radio.
461        if (tree !== this.copy.model)
462          this.apply({ tree, chosen: [target.path] });
463      },
464      { signal },
465    );
466    this.get(".content-role").addEventListener(
467      "change",
468      (event) => {
469        if (this.moving) return;
470        this.finishText();
471        const kind = (event.target as HTMLInputElement).value;
472        const target = this.edits()?.text;
473        if (!this.copy || !target || !isContentKind(kind)) return;
474        const tree = editContentKind(this.copy.model, target.path, kind);
475        // The workbench keeps each role's purpose beside the choice.
476        if (tree !== this.copy.model)
477          this.apply(
478            { tree, chosen: [target.path] },
479            this.standalone ? undefined : roleDescriptions[kind],
480          );
481      },
482      { signal },
483    );
484    this.act(".group-action", (model, edits) => {
485      if (!edits.wrap) return undefined;
486      const edited = wrapMembers(model, edits.wrap);
487      return [
488        edited,
489        `Grouped ${members(edits.wrap.length)} in a new Stack.`,
490        { name: edited.chosen[0]! },
491      ];
492    });
493    this.act(".ungroup-action", (model, edits) => {
494      if (!edits.release) return undefined;
495      const edited = releaseGroup(model, edits.release);
496      return [
497        edited,
498        "Ungrouped. The members keep their reading order.",
499        { name: edited.chosen[0]! },
500      ];
501    });
502    this.act(".remove-action", (model, edits) => {
503      if (!edits.remove) return undefined;
504      const removed = atPath(model, edits.remove)!;
505      const edited = removeMember(model, edits.remove);
506      const parent = atPath(edited.tree, parentPath(edits.remove))!;
507      const left =
508        "children" in parent && !parent.children.length
509          ? `This ${parent.kind} is now empty and keeps its place.`
510          : "Undo restores it.";
511      return [
512        edited,
513        "children" in removed
514          ? `Removed the ${removed.kind} and its ${members(removed.children.length)}. ${left}`
515          : `Removed. ${left}`,
516        "stay",
517      ];
518    });
519    this.on(".move-action", "click", () => this.beginMove());
520    this.on(".cancel-move", "click", () => this.cancelMove());
521    for (const placement of placements)
522      this.on(`.place-${placement}`, "click", () => this.placeMove(placement));
523    this.on(".undo-action", "click", () => {
524      if (this.moving) return;
525      this.finishText();
526      const before = this.copy && undoEdit(this.copy);
527      if (!before) return;
528      this.copy = this.withSubject(before);
529      this.show("Undid the last change. Restored its selection.", "stay");
530    });
531    this.root.addEventListener(
532      "keydown",
533      (event) => {
534        if ((event as KeyboardEvent).key !== "Escape" || !this.copy) return;
535        if (this.moving) {
536          event.preventDefault();
537          this.cancelMove();
538          return;
539        }
540        if (this.standalone) {
541          // Something is always selected here; Escape only ends a mode.
542          if (this.several) {
543            this.several = false;
544            this.refresh();
545          }
546          return;
547        }
548        const editing = this.root.activeElement?.closest(".authoring") != null;
549        const path = this.copy.chosen[0] ?? "0";
550        this.finishText();
551        this.attended = undefined;
552        this.select([]);
553        // The controls for a selection are now unavailable; continue from
554        // the declaration, where something can be selected.
555        if (editing) this.hierarchy?.focus(path);
556      },
557      { signal },
558    );
559  }
560
561  /** The strip's own controls: its starting choices, its kind-and-place
562   * additions, and clearing the selection its clicks build up. */
563  private wireStrip(signal: AbortSignal) {
564    this.get(".starter-note").textContent =
565      `Starts from the ${this.source} composition as it is now.`;
566    this.get(".copy-action").textContent = `Copy ${this.source}`;
567    this.get(".start-action").textContent = `Copy ${this.source}`;
568    this.on(".open-playground", "click", () => {
569      if (!this.copy || this.moving) return;
570      this.finishText();
571      try {
572        location.assign(
573          playgroundURL("edit", encodeSnapshot(this.copy.model)).href,
574        );
575      } catch (error) {
576        this.status(
577          error instanceof Error
578            ? error.message
579            : "This composition could not be opened.",
580        );
581      }
582    });
583    this.on(".start-action", "click", () => this.start());
584    this.on(".start-blank", "click", () => this.startBlank());
585    this.get(".new-member").addEventListener(
586      "keydown",
587      (event) => {
588        // Dismissing the native picker should preserve the insertion target.
589        if (event.key === "Escape") event.stopPropagation();
590      },
591      { signal },
592    );
593    this.act(".inside-action", (model, edits) =>
594      edits.inside ? this.createMember(model, edits.inside) : undefined,
595    );
596    this.act(".after-action", (model, edits) =>
597      edits.after ? this.createMember(model, edits.after) : undefined,
598    );
599    this.on(".clear-action", "click", () => {
600      if (!this.copy || this.moving) return;
601      const path = this.copy.chosen[0] ?? "0";
602      this.finishText();
603      this.select([]);
604      this.status("Selection cleared. Choose a member or a group.");
605      this.hierarchy?.focus(path);
606    });
607    this.on(".copy-action", "click", () => {
608      if (this.moving) return;
609      const tree = this.sourceComposition();
610      if (!tree) {
611        this.status(`The ${this.source} exercise is not on this page.`);
612        return;
613      }
614      this.apply(
615        { tree, chosen: [] },
616        `Copied the ${this.source} composition as it is now. Undo restores your working copy.`,
617        "stay",
618      );
619    });
620  }
621
622  /** The workbench's own controls: the outline, the choice of hierarchy,
623   * asking for several, the way to a parent, and adding by name. */
624  private wireWorkbench(signal: AbortSignal) {
625    this.outline = new OutlinePanel(this.get(".outline"), {
626      describe: (path, node) => this.describe(path, node),
627      choose: (path, extend) => this.choose(path, extend),
628      attend: (path) => this.attend(path),
629      signal,
630    });
631    this.showHierarchy(preferredHierarchy);
632    this.on(".show-outline", "click", () => this.showHierarchy("outline"));
633    this.on(".show-code", "click", () => this.showHierarchy("code"));
634    this.on(".several", "click", () => {
635      if (this.moving) return;
636      this.several = !this.several;
637      this.refresh();
638    });
639    this.on(".parent", "click", () => {
640      const path = parentPath(this.copy?.chosen[0] ?? "0");
641      if (!path || this.moving) return;
642      this.finishText();
643      this.several = false;
644      this.select([path]);
645      this.hierarchy?.focus(path);
646    });
647    this.on(".place-toggle", "click", () => {
648      this.addAfter = !this.addAfter;
649      this.refresh();
650    });
651    this.act(".add-text", (model, edits) => {
652      const at = this.insertion(edits);
653      return (
654        at && [
655          addText(model, at),
656          "Added text. Type to replace its wording.",
657          "text",
658        ]
659      );
660    });
661    for (const kind of arrangements)
662      this.act(`[data-add="${kind}"]`, (model, edits) => {
663        const at = this.insertion(edits);
664        if (!at) return;
665        const added = addGroup(model, at, kind);
666        const canFill = !!editsFor(added.tree, added.chosen).inside;
667        return [
668          added,
669          canFill
670            ? `Added an empty ${kind}. Add text inside it to begin filling it.`
671            : `Added an empty ${kind} at the nesting limit. You can change its arrangement or move it to a shallower group.`,
672          "inside",
673        ];
674      });
675  }
676
677  /** Shows the composition as an outline or as its declaration. Focus stays
678   * on the choice; the hierarchy that appears is brought up to date. */
679  private showHierarchy(view: "outline" | "code") {
680    preferredHierarchy = view;
681    this.get(".outline").hidden = view !== "outline";
682    this.get(".source").hidden = view !== "code";
683    for (const name of ["outline", "code"])
684      this.get(`.show-${name}`).setAttribute(
685        "aria-pressed",
686        String(name === view),
687      );
688    if (!this.copy) return;
689    this.hierarchy?.show(this.copy.model);
690    this.hierarchy?.rove(this.moving?.target ?? this.copy.chosen[0] ?? "0");
691    this.decorate();
692  }
693
694  /** The source exercise's composition now, or its starting composition when
695   * that exercise is not on the page. */
696  private sourceComposition(): Composition | undefined {
697    const scope = this.getRootNode() as Document | ShadowRoot;
698    const live: unknown = scope.querySelector(
699      `axiomatic-example[exercise="${CSS.escape(this.source)}"]`,
700    );
701    if (
702      live &&
703      typeof live === "object" &&
704      "snapshot" in live &&
705      typeof live.snapshot === "function"
706    )
707      return restoreWorkingTree(live.snapshot());
708    const known = exampleNames.find((name) => name === this.source);
709    return known ? restoreWorkingTree(example(known)) : undefined;
710  }
711
712  private load(): WorkingCopy | undefined {
713    try {
714      const saved: unknown = JSON.parse(
715        sessionStorage.getItem(this.storageKey) || "null",
716      );
717      const copy = restoreWorkingCopy(saved);
718      const width =
719        saved && typeof saved === "object" && "width" in saved
720          ? saved.width
721          : undefined;
722      if (copy && typeof width === "number" && Number.isFinite(width))
723        this.width = clampWidth(width, maximumWidth);
724      return copy;
725    } catch {
726      /* A working copy also starts without storage. */
727      return undefined;
728    }
729  }
730  /** Saves the working copy. A rewording in progress is saved as finished,
731   * so reopening mid-edit keeps the words and can still undo them. */
732  private save() {
733    if (!this.copy) return;
734    if (this.standalone) {
735      this.dispatchEvent(
736        new CustomEvent<PlaygroundState>("composition-change", {
737          detail: this.workingState!,
738        }),
739      );
740      return;
741    }
742    const copy = this.textEdit
743      ? finishTextEdit(this.copy, this.textEdit)
744      : this.copy;
745    try {
746      sessionStorage.setItem(
747        this.storageKey,
748        JSON.stringify({ ...copy, width: this.width }),
749      );
750    } catch {}
751  }
752
753  private start() {
754    const tree = this.sourceComposition();
755    if (!tree) {
756      this.get(".starter-note").textContent =
757        `The ${this.source} exercise is not on this page.`;
758      return;
759    }
760    this.copy = startWorkingCopy(tree);
761    this.save();
762    this.open();
763    this.status(
764      "This copy is yours. Select a fact to reword it, or a group to add to it.",
765    );
766    this.hierarchy?.focus("0");
767  }
768  /** An empty root is a place to compose; replacing work is one Undo step. */
769  private startBlank() {
770    if (this.moving) return;
771    this.finishText();
772    this.several = false;
773    let replaced = false;
774    if (!this.copy) {
775      this.copy = { ...startWorkingCopy(Stack()), chosen: ["0"] };
776      this.open();
777    } else {
778      const edited = blankComposition(this.copy.model);
779      if (edited.tree !== this.copy.model) {
780        replaced = true;
781        this.apply(edited);
782      } else this.select(["0"]);
783    }
784    this.status(
785      `An empty Stack. Add content or an empty group inside it.${replaced ? " Undo restores your previous composition." : ""}`,
786    );
787    this.get<HTMLElement>(
788      this.standalone ? ".add-text" : ".new-member",
789    ).focus();
790  }
791
792  /** The strip's addition: the kind its picker shows, at the place asked for. */
793  private createMember(
794    model: Composition,
795    at: Insertion,
796  ): [Edited, string, Focus] {
797    const kind = this.get<HTMLSelectElement>(".new-member").value;
798    if (isArrangement(kind)) {
799      const edited = addGroup(model, at, kind);
800      this.get<HTMLSelectElement>(".new-member").value = "Text";
801      return [
802        edited,
803        `Added an empty ${kind}. Add Text inside it to begin filling the group.`,
804        "inside",
805      ];
806    }
807    return [
808      addText(model, at),
809      "Added Text. Type to replace its wording, then choose its content role.",
810      "text",
811    ];
812  }
813
814  /**
815   * Where the workbench's additions go. A selected group takes them inside
816   * unless its author asked for after it; anything else takes them after.
817   */
818  private insertion(edits: WorkingEdits): Insertion | undefined {
819    return this.addAfter ? edits.after : (edits.inside ?? edits.after);
820  }
821
822  private open() {
823    if (!this.standalone) this.get(".starter").hidden = true;
824    this.get(".workspace").hidden = false;
825    this.show();
826  }
827
828  private edits(): WorkingEdits | undefined {
829    return this.copy && editsFor(this.copy.model, this.copy.chosen);
830  }
831
832  /** Wires an edit button: the edit its selection permits, a message, and
833   * where focus goes. */
834  private act(
835    selector: string,
836    edit: (
837      model: Composition,
838      edits: WorkingEdits,
839    ) => [Edited, string, Focus] | undefined,
840  ) {
841    this.on(selector, "click", () => {
842      if (this.moving) return;
843      // A click may not blur the text field, so end its edit here.
844      this.finishText();
845      const edits = this.edits();
846      const applied = this.copy && edits && edit(this.copy.model, edits);
847      if (applied) this.apply(...applied);
848    });
849  }
850
851  /** Makes one undoable edit. */
852  private apply(edited: Edited, message?: string, focus: Focus = "stay") {
853    if (!this.copy) return;
854    this.finishText();
855    this.copy = commitEdit(this.copy, edited.tree, edited.chosen);
856    this.show(message, focus);
857  }
858
859  /** Shows a changed composition everywhere, then saves it. */
860  private show(
861    message?: string,
862    focus: Focus = "stay",
863    preserveScroll = false,
864  ) {
865    if (!this.copy) return;
866    // Read before the controls change: one that disappears loses focus.
867    const focused = this.root.activeElement;
868    this.attended = undefined;
869    // A changed composition ends the modes that referred to the old one.
870    this.several = false;
871    this.addAfter = false;
872    for (const preview of this.previews)
873      preview.render(this.copy.model, preserveScroll);
874    this.hierarchy?.show(this.copy.model);
875    this.hierarchy?.rove(this.copy.chosen[0] ?? "0");
876    this.refresh(message);
877    this.save();
878    const field = this.get<HTMLInputElement>(".text-field");
879    if (focus === "text" && !field.disabled) {
880      field.focus({ preventScroll: true });
881      field.select();
882    } else if (focus === "inside") {
883      const fill = this.get<HTMLButtonElement>(
884        this.standalone ? ".add-text" : ".inside-action",
885      );
886      // At the node/depth limit the empty group is still authored and can
887      // change arrangement. Keep focus on a usable, visible control.
888      const next =
889        fill.disabled || !this.edits()?.inside
890          ? this.get<HTMLInputElement>(".group-arrangement input:checked")
891          : fill;
892      next.focus({ preventScroll: true });
893    } else if (focus === "move") {
894      const move = this.get<HTMLButtonElement>(".move-action");
895      const next = move.disabled
896        ? this.get<HTMLButtonElement>(".undo-action")
897        : move;
898      next.focus({ preventScroll: true });
899    } else if (typeof focus === "object") this.hierarchy?.focus(focus.name);
900    else this.keepFocus(focused);
901  }
902
903  /** A focused control that became unavailable hands focus to the selected
904   * node's name, so the keyboard stays inside the editor. */
905  private keepFocus(focused: Element | null) {
906    const unavailable =
907      ((focused instanceof HTMLButtonElement ||
908        focused instanceof HTMLInputElement) &&
909        focused.disabled) ||
910      focused?.closest("[hidden]") != null;
911    if (unavailable) this.hierarchy?.focus(this.copy?.chosen[0] ?? "0");
912  }
913
914  /**
915   * The author chose a node in a preview or the hierarchy. A lesson teaches
916   * that each choice builds on the selection, so there it always does. The
917   * workbench selects the one thing chosen unless its author asked for
918   * several, by mode or, with `extend`, for this one choice.
919   */
920  private choose(path: string, extend = false) {
921    if (!this.copy) return;
922    if (this.moving) {
923      this.moving = { ...this.moving, target: path };
924      this.attended = undefined;
925      this.refresh();
926      this.hierarchy?.rove(path);
927      return;
928    }
929    this.finishText();
930    const { model, chosen } = this.copy;
931    this.select(
932      this.standalone
933        ? selectionAfter(model, chosen, path, this.several || extend)
934        : chooseMember(model, chosen, path),
935    );
936    this.hierarchy?.rove(path);
937  }
938  private select(chosen: readonly string[]) {
939    if (!this.copy) return;
940    this.copy = { ...this.copy, chosen };
941    this.addAfter = false;
942    this.refresh();
943    this.save();
944  }
945  private attend(path: string | undefined) {
946    const next = this.structure && !this.moving ? path : undefined;
947    if (next === this.attended) return;
948    this.attended = next;
949    this.decorate();
950  }
951
952  private typeText() {
953    if (this.moving) return;
954    const target = this.edits()?.text;
955    if (!this.copy || !target) return;
956    this.textEdit ??= beginTextEdit(this.copy, target.path);
957    this.copy = typeText(
958      this.copy,
959      this.textEdit,
960      this.get<HTMLInputElement>(".text-field").value,
961    );
962    // The field is outside everything this replaces, so the caret stays.
963    for (const preview of this.previews) preview.render(this.copy.model, true);
964    this.hierarchy?.show(this.copy.model);
965    this.refresh();
966    this.save();
967  }
968  /** Ends a rewording in progress as one undoable step. Returns whether
969   * there was one. */
970  private finishText(): boolean {
971    if (!this.copy || !this.textEdit) return false;
972    this.copy = finishTextEdit(this.copy, this.textEdit);
973    this.textEdit = undefined;
974    this.save();
975    return true;
976  }
977  private cancelText() {
978    if (!this.copy || !this.textEdit) return;
979    this.copy = cancelTextEdit(this.copy, this.textEdit);
980    this.textEdit = undefined;
981    this.show("Restored the text from before this edit.", "stay", true);
982  }
983
984  private beginMove() {
985    if (!this.copy || this.moving) return;
986    this.finishText();
987    const moves = movesFor(this.copy.model, this.copy.chosen);
988    if (!moves?.places.length) return;
989    this.moving = { members: moves.members };
990    this.several = false;
991    this.attended = undefined;
992    this.refresh();
993    // A visible escape route keeps focus with the controls. Names in the
994    // hierarchy keep their keyboard order for choosing a destination.
995    this.get<HTMLButtonElement>(".cancel-move").focus({ preventScroll: true });
996  }
997
998  private cancelMove(restoreFocus = true) {
999    if (!this.moving) return;
1000    this.moving = undefined;
1001    this.attended = undefined;
1002    this.hierarchy?.rove(this.copy?.chosen[0] ?? "0");
1003    this.refresh("Move cancelled. Your composition is unchanged.");
1004    // Escape may come from far down a long declaration. Native focus scrolling
1005    // brings the controls back into view without measuring their rectangles.
1006    if (restoreFocus) this.get<HTMLButtonElement>(".move-action").focus();
1007  }
1008
1009  private movePlace(placement: Placement): Insertion | undefined {
1010    if (!this.copy || !this.moving?.target) return undefined;
1011    const target = this.moving.target;
1012    const node = atPath(this.copy.model, target);
1013    if (!node) return undefined;
1014    if (placement === "inside")
1015      return "children" in node
1016        ? placeAtEnd(this.copy.model, target)
1017        : undefined;
1018    if (target === "0") return undefined;
1019    return placement === "before" ? placeBefore(target) : placeAfter(target);
1020  }
1021
1022  private movingName(): string {
1023    const moving = this.moving;
1024    if (!moving || !this.copy) return "";
1025    return moving.members.length === 1
1026      ? describeMember(atPath(this.copy.model, moving.members[0]!)!)
1027      : `${members(moving.members.length)} together`;
1028  }
1029
1030  private refreshMove() {
1031    if (!this.copy || !this.moving) return;
1032    const { model } = this.copy;
1033    const target = this.moving.target && atPath(model, this.moving.target);
1034    this.get(".move-source").textContent = `Moving ${this.movingName()}`;
1035    const parent =
1036      this.moving.target && this.moving.target !== "0"
1037        ? atPath(model, parentPath(this.moving.target))
1038        : undefined;
1039    const context = parent
1040      ? ` in the surrounding ${parent.kind}`
1041      : " in the whole composition";
1042    this.get(".move-destination").textContent = target
1043      ? `Destination: ${describeMember(target)}${parent ? ` · inside ${parent.kind}` : " · whole composition"}`
1044      : "Choose a destination in either view or the composition.";
1045    const reasons = new Set<string>();
1046    const available: Placement[] = [];
1047    for (const placement of placements) {
1048      const button = this.get<HTMLButtonElement>(`.place-${placement}`);
1049      const place = this.movePlace(placement);
1050      const obstacle = place && moveObstacle(model, this.moving.members, place);
1051      const unavailable = !place || !!obstacle;
1052      button.disabled = unavailable;
1053      button.setAttribute(
1054        "aria-label",
1055        target
1056          ? `Move ${placement === "inside" ? "inside at end of" : placement} ${describeMember(target)}`
1057          : placementLabels[placement],
1058      );
1059      const reason = obstacle
1060        ? moveObstacles[obstacle]
1061        : !place
1062          ? placement === "inside"
1063            ? "Choose a group to move inside."
1064            : "The whole composition has no surrounding group."
1065          : "";
1066      button.title = target ? reason : "Choose a destination first.";
1067      if (obstacle) reasons.add(moveObstacles[obstacle]);
1068      if (!unavailable) available.push(placement);
1069    }
1070    const beside = available.filter((placement) => placement !== "inside");
1071    const guidance = [
1072      beside.length && target
1073        ? `${beside.map((placement) => placementLabels[placement]).join(" or ")} places the moving members${context}, alongside this ${target.kind}.`
1074        : "",
1075      available.includes("inside") && target
1076        ? `Inside at end adds them to ${this.moving.target === "0" ? "the whole composition" : `this ${target.kind}`}.`
1077        : "",
1078    ]
1079      .filter(Boolean)
1080      .join(" ");
1081    this.status(
1082      !target
1083        ? "The solid selection is what travels. Choosing a destination does not move it yet."
1084        : guidance || [...reasons].join(" ") || "Choose another destination.",
1085    );
1086  }
1087
1088  private placeMove(placement: Placement) {
1089    if (!this.copy || !this.moving?.target) return;
1090    const place = this.movePlace(placement);
1091    if (!place || moveObstacle(this.copy.model, this.moving.members, place))
1092      return;
1093    const name = this.movingName();
1094    const target = describeMember(atPath(this.copy.model, this.moving.target)!);
1095    const edited = moveMembers(this.copy.model, this.moving.members, place);
1096    if (edited.tree === this.copy.model) return;
1097    const former = atPath(edited.tree, edited.from);
1098    const emptied =
1099      former && "children" in former && !former.children.length
1100        ? ` The ${former.kind} it left is empty and keeps its arrangement.`
1101        : "";
1102    this.moving = undefined;
1103    this.apply(
1104      edited,
1105      `Moved ${name} ${placement === "inside" ? "inside, at the end of" : placement} ${target}.${emptied} Undo restores the previous composition.`,
1106      "move",
1107    );
1108  }
1109
1110  private status(message: string) {
1111    this.get(".author-status").textContent = message;
1112  }
1113
1114  /** Shows the selection in every view. */
1115  private decorate() {
1116    if (!this.copy) return;
1117    const { chosen } = this.copy;
1118    const inspected =
1119      this.attended ?? (chosen.length === 1 ? chosen[0] : undefined);
1120    for (const preview of this.previews)
1121      preview.decorate({
1122        structure: this.structure,
1123        inspected,
1124        chosen,
1125        destination: this.moving?.target,
1126      });
1127    this.hierarchy?.destination(this.moving?.target, !!this.moving);
1128    this.hierarchy?.mark(chosen);
1129    this.hierarchy?.inspect(this.structure, inspected);
1130  }
1131
1132  /** Brings the controls and every view up to date with the selection. */
1133  private refresh(message?: string) {
1134    const edits = this.edits();
1135    if (!this.copy || !edits) return;
1136    if (this.standalone)
1137      this.dispatchEvent(
1138        new CustomEvent("composition-interaction", {
1139          detail: { moving: !!this.moving },
1140        }),
1141      );
1142    const { model, chosen } = this.copy;
1143    const structure = this.get(".structure");
1144    structure.setAttribute("aria-pressed", String(this.structure));
1145    structure.textContent = this.structure
1146      ? "Hide structure"
1147      : "Show structure";
1148
1149    const field = this.get<HTMLInputElement>(".text-field");
1150    field.disabled = !edits.text;
1151    // Writing an unchanged value would move the caret while typing.
1152    const text = edits.text?.content.text ?? "";
1153    if (field.value !== text) field.value = text;
1154    for (const input of this.root.querySelectorAll<HTMLInputElement>(
1155      ".content-role input",
1156    )) {
1157      input.disabled = !edits.text;
1158      input.checked = input.value === edits.text?.content.kind;
1159    }
1160    for (const input of this.root.querySelectorAll<HTMLInputElement>(
1161      ".group-arrangement input",
1162    )) {
1163      input.disabled = !edits.arrange;
1164      input.checked = input.value === edits.arrange?.group.kind;
1165    }
1166    this.enable(".group-action", !!edits.wrap);
1167    this.enable(".ungroup-action", !!edits.release);
1168    this.enable(".move-action", !!movesFor(model, chosen)?.places.length);
1169    this.enable(".remove-action", !!edits.remove);
1170    // A rewording in progress is undone as the step it is about to become.
1171    this.enable(
1172      ".undo-action",
1173      !this.moving && (this.copy.undo.length > 0 || !!this.textEdit),
1174    );
1175    this.enable(".blank-action", !this.moving);
1176
1177    const status = this.standalone
1178      ? this.refreshInspector(edits, message)
1179      : this.refreshStrip(edits, message);
1180    this.get(".workspace").toggleAttribute("data-moving", !!this.moving);
1181    this.get(".move-controls").hidden = !this.moving;
1182    if (this.moving) this.refreshMove();
1183    else this.status(status);
1184    this.decorate();
1185  }
1186
1187  private enable(selector: string, available: boolean, label?: string) {
1188    const button = this.get<HTMLButtonElement>(selector);
1189    button.disabled = !available;
1190    if (label !== undefined) button.textContent = label;
1191  }
1192
1193  /** The strip keeps every control in place and says what each needs.
1194   * Returns what its status line should say. */
1195  private refreshStrip(edits: WorkingEdits, message?: string): string {
1196    const { model, chosen } = this.copy!;
1197    this.get<HTMLInputElement>(".text-field").placeholder = edits.text
1198      ? ""
1199      : "Select one fact to edit its text";
1200    this.get(".content-role").hidden = !edits.text;
1201    const choice = this.get(".group-arrangement");
1202    choice.hidden = !!edits.text;
1203    const target = edits.arrange;
1204    choice.setAttribute("aria-disabled", String(!target));
1205    const count = target?.group.children.length;
1206    this.get(".group-arrangement .arrangement-label").textContent = !target
1207      ? "Arrange a group as"
1208      : count === 0
1209        ? "Arrange this empty group as"
1210        : count === 1
1211          ? "Arrange this group as"
1212          : `Arrange these ${count} members as`;
1213
1214    const selected =
1215      chosen[0] === undefined ? undefined : atPath(model, chosen[0]);
1216    this.enable(
1217      ".inside-action",
1218      !!edits.inside,
1219      edits.arrange
1220        ? `Inside ${edits.arrange.group.kind}`
1221        : edits.inside
1222          ? "Inside composition"
1223          : "Inside group",
1224    );
1225    this.enable(
1226      ".after-action",
1227      !!edits.after,
1228      chosen.length > 1
1229        ? "After selection"
1230        : `After ${edits.remove && selected ? selected.kind : "member"}`,
1231    );
1232    this.enable(".open-playground", !this.moving);
1233    this.enable(".clear-action", chosen.length > 0);
1234
1235    if (edits.full)
1236      return "This selection reaches a size or nesting limit. You can still use the enabled actions.";
1237    if (message !== undefined) return message;
1238    if (target)
1239      return target.group.children.length
1240        ? arrangementContracts[target.group.kind]
1241        : `This ${target.group.kind} is empty and keeps its arrangement. Add a member inside it${edits.remove ? ", or remove it" : ""}.`;
1242    if (edits.text)
1243      return `${roleDescriptions[edits.text.content.kind]} Changing its role keeps its wording and membership.`;
1244    if (chosen.length > 1)
1245      return `${members(chosen.length)} selected. Group them, move them, or add a member after them.`;
1246    return "Select a fact to reword it, or a group's name in the code to arrange or add to it.";
1247  }
1248
1249  /** The inspector names what is selected and shows what applies to it.
1250   * Returns what its status line should say. */
1251  private refreshInspector(edits: WorkingEdits, message?: string): string {
1252    const { model, chosen } = this.copy!;
1253    const path = chosen[0] ?? "0";
1254    const node = atPath(model, path) ?? model;
1255    const single = chosen.length < 2;
1256    this.get(".inspector").toggleAttribute("data-multiple", !single);
1257    this.get(".selected-title").textContent = single
1258      ? node.kind
1259      : `${chosen.length} members selected`;
1260    this.get(".selected-detail").textContent =
1261      single && "children" in node
1262        ? `${path === "0" ? "the whole composition · " : ""}${node.children.length ? members(node.children.length) : "empty"}`
1263        : "";
1264    const parent = path === "0" ? undefined : atPath(model, parentPath(path));
1265    const up = this.get<HTMLButtonElement>(".parent");
1266    up.hidden = !parent;
1267    if (parent) {
1268      up.textContent = `↑ In ${parent.kind}`;
1269      up.setAttribute(
1270        "aria-label",
1271        `Select the ${parent.kind} ${single ? "this is" : "these are"} in`,
1272      );
1273    }
1274
1275    this.get(".wording").hidden = !edits.text;
1276    this.get(".content-role").hidden = !edits.text;
1277    this.get(".role-purpose").textContent = edits.text
1278      ? roleDescriptions[edits.text.content.kind]
1279      : "";
1280    this.get(".group-arrangement").hidden = !edits.arrange;
1281    this.get(".arrangement-purpose").textContent = edits.arrange
1282      ? arrangementContracts[edits.arrange.group.kind]
1283      : "";
1284
1285    const place = this.insertion(edits);
1286    const inside = edits.inside && place === edits.inside ? edits.inside : null;
1287    this.get(".insertion-context").textContent = !place
1288      ? "Nothing more can be added here."
1289      : inside
1290        ? `Add inside this ${inside.group.kind}`
1291        : single
1292          ? `Add after this ${node.kind}`
1293          : "Add after these members";
1294    const toggle = this.get<HTMLButtonElement>(".place-toggle");
1295    toggle.hidden = !(edits.inside && edits.after);
1296    toggle.textContent = inside
1297      ? "Add after it instead"
1298      : "Add inside it instead";
1299    for (const button of this.root.querySelectorAll<HTMLButtonElement>(
1300      ".add-text, [data-add]",
1301    ))
1302      button.disabled = !place;
1303
1304    const several = this.get<HTMLButtonElement>(".several");
1305    several.disabled = !!this.moving;
1306    several.setAttribute("aria-pressed", String(this.several));
1307    several.textContent = this.several ? "Done selecting" : "Select several";
1308    this.get(".select-help").hidden = !this.several;
1309    this.get(".empty-hint").hidden =
1310      !("children" in model) || model.children.length > 0;
1311
1312    return [
1313      message,
1314      edits.full
1315        ? "This selection is at a size or nesting limit, so some actions are unavailable."
1316        : "",
1317    ]
1318      .filter(Boolean)
1319      .join(" ");
1320  }
1321}
1322
1323if (!customElements.get("axiomatic-playground"))
1324  customElements.define("axiomatic-playground", AxiomaticPlayground);