documentation/components/source/composition-preview.ts

1/**
2 * One hosted view of a composition: a labeled slot, the rendered boxes, and
3 * a caption saying what happened in that slot.
4 *
5 * Several previews can show the same composition at once. Each mounts its
6 * own boxes, so each Switcher is decided from the space its own host gives
7 * it, and each keeps its inspection anchors inside its own `.rendered` scope.
8 * The host's size comes from CSS (`[data-preview]`); a preview with a
9 * `width` option also lets the reader request one.
10 *
11 * The owner supplies the composition and the selection. A preview reports
12 * the node a reader points at or chooses, by its authored path.
13 */
14import type { Composition } from "./composition.ts";
15import {
16  compositionMembers,
17  compositionSelector,
18} from "./composition-elements.ts";
19import { CompositionReadouts, ExampleReadouts } from "./example-readouts.ts";
20import {
21  describeSelection,
22  prepareInspection,
23  updateInspection,
24} from "./inspection.ts";
25import { mountComposition, type MountedComposition } from "./primitives.ts";
26import { arrangementAttribute } from "./switcher-coordinator.ts";
27import {
28  clampWidth,
29  maximumWidth,
30  minimumWidth,
31  widthControl,
32  type WidthControl,
33} from "./width-control.ts";
34
35export interface PreviewOptions {
36  /** Names the slot for a reader, such as "Wide card". */
37  readonly label: string;
38  /** Names the slot for CSS, which sizes `[data-preview="…"]`. */
39  readonly slot: string;
40  /** Present when the reader may request this host's width. */
41  readonly width?: {
42    readonly initial: number;
43    /** Independent space available for resizing when the preview itself
44     * shrink-wraps its requested width. Must establish a containing block. */
45    readonly availableSpace?: HTMLElement;
46    /** `settled` is false while a drag continues. */
47    changed(width: number, settled: boolean): void;
48  };
49  /** The reader clicked the node at `path`. */
50  choose(path: string): void;
51  /** The pointer is over the node at `path`, or has left the composition. */
52  attend(path: string | undefined): void;
53}
54
55/** What the owner's selection asks every preview to show. */
56export interface PreviewDecoration {
57  /** Tint every box so nesting is visible. */
58  readonly structure: boolean;
59  /** The node whose boundary, gaps and caption are shown. */
60  readonly inspected: string | undefined;
61  /** The selected nodes. */
62  readonly chosen: readonly string[];
63  /** A proposed move destination, distinct from the members being moved. */
64  readonly destination?: string | undefined;
65}
66
67export class CompositionPreview {
68  readonly element: HTMLElement;
69  readonly #rendered: HTMLElement;
70  readonly #caption: HTMLElement;
71  readonly #readouts: CompositionReadouts;
72  readonly #abort = new AbortController();
73  readonly #modeObserver = new MutationObserver(() => this.#refreshModes());
74  readonly #captionObserver = new ResizeObserver(() => this.#refreshCaption());
75  readonly #widthControl: WidthControl | undefined;
76  #mounted: MountedComposition | undefined;
77  #modes: string[] = [];
78  #inspected: HTMLElement | undefined;
79
80  constructor(document: Document, options: PreviewOptions) {
81    const { signal } = this.#abort;
82    const element = document.createElement("section");
83    element.className = "preview";
84    element.dataset.preview = options.slot;
85    const labelId = `preview-${options.slot}`;
86    element.setAttribute("aria-labelledby", labelId);
87    element.innerHTML = `<div class="stage"><div class="viewport"><div class="bar"><span class="preview-label" id="${labelId}"></span>${
88      options.width
89        ? `<label class="width"><span class="sr-only"></span><input type="number" min="${minimumWidth}" max="${maximumWidth}" step="1"><span aria-hidden="true">px</span></label>`
90        : ""
91    }</div><div class="frame"><div class="rendered"></div>${
92      options.width
93        ? '<div class="resize" aria-hidden="true" title="Drag to resize. Edit the width field for keyboard control."></div>'
94        : ""
95    }</div></div></div><div class="caption"><span class="selection"></span><span class="note"></span></div>`;
96    const get = <T extends HTMLElement = HTMLElement>(selector: string) =>
97      element.querySelector<T>(selector)!;
98    get(".preview-label").textContent = options.label;
99    this.element = element;
100    this.#rendered = get(".rendered");
101    this.#caption = get(".selection");
102    const viewport = get(".viewport");
103    const directions = () => this.#modes;
104
105    if (options.width) {
106      const { changed } = options.width;
107      const input = get<HTMLInputElement>(".width input");
108      get(".width .sr-only").textContent = `${options.label} width`;
109      const readouts = new ExampleReadouts(
110        options.width.availableSpace ?? get(".stage"),
111        viewport,
112        input,
113        get(".note"),
114        directions,
115      );
116      this.#readouts = readouts;
117      viewport.style.inlineSize = `${options.width.initial}px`;
118      this.#widthControl = widthControl({
119        handle: get(".resize"),
120        viewport,
121        input,
122        limit: () => readouts.maximum,
123        request: (width, settled, maximum = readouts.maximum) => {
124          if (!Number.isFinite(width)) {
125            readouts.refreshWidth();
126            return;
127          }
128          const next = clampWidth(width, maximum);
129          viewport.style.inlineSize = `${next}px`;
130          changed(next, settled);
131        },
132        restore: () => readouts.refreshWidth(),
133        signal,
134      });
135    } else this.#readouts = new CompositionReadouts(get(".note"), directions);
136
137    const frame = get(".frame");
138    const pathAt = (target: EventTarget | null) =>
139      target instanceof Element
140        ? target.closest<HTMLElement>(compositionSelector)?.dataset.path
141        : undefined;
142    frame.addEventListener(
143      "click",
144      (event) => {
145        const path = pathAt(event.target);
146        if (path) options.choose(path);
147      },
148      { signal },
149    );
150    frame.addEventListener(
151      "pointermove",
152      (event) => {
153        if (this.#widthControl?.dragging) return;
154        const path = pathAt(event.target);
155        if (path) options.attend(path);
156      },
157      { signal },
158    );
159    frame.addEventListener("pointerleave", () => options.attend(undefined), {
160      signal,
161    });
162    this.#modeObserver.observe(this.#rendered, {
163      attributes: true,
164      subtree: true,
165      attributeFilter: [arrangementAttribute],
166    });
167  }
168
169  /** Shows `model`. Call `decorate` afterwards: the boxes are new. */
170  render(model: Composition, preserveScroll = false) {
171    // A wording edit keeps authored paths intact. Native scroll offsets are
172    // view state that DOM replacement otherwise loses; CSS cannot transfer
173    // them to a replacement box. Capture only for that edit, never on resize
174    // or regrouping, and let the browser clamp to the new scrollable extent.
175    const scroll = preserveScroll
176      ? [
177          ...this.#rendered.querySelectorAll<HTMLElement>(
178            '[data-kind="Shelf"]',
179          ),
180        ].map((shelf) => [shelf.dataset.path!, shelf.scrollLeft] as const)
181      : [];
182    if (this.#mounted) this.#mounted.update(model);
183    else this.#mounted = mountComposition(this.#rendered, model);
184    for (const [path, offset] of scroll) {
185      const shelf = this.#rendered.querySelector<HTMLElement>(
186        `[data-kind="Shelf"][data-path="${path}"]`,
187      );
188      if (shelf) shelf.scrollLeft = offset;
189    }
190    prepareInspection(this.#rendered);
191    // A group with no members and a text with no characters render nothing.
192    // Naming them lets CSS mark their place without adding to the layout.
193    for (const node of this.#nodes()) {
194      const empty = node.classList.contains("leaf")
195        ? node.textContent === ""
196        : compositionMembers(node).length === 0;
197      if (empty) node.dataset.empty = "true";
198    }
199    this.#inspected = undefined;
200    this.#captionObserver.disconnect();
201    this.#readouts.observeComposition(this.#rendered);
202    this.#refreshModes();
203  }
204
205  /** Applies the owner's selection to the boxes shown now. */
206  decorate({ structure, inspected, chosen, destination }: PreviewDecoration) {
207    for (const node of this.#nodes()) {
208      const marked = String(chosen.includes(node.dataset.path!));
209      if (node.dataset.chosen !== marked) node.dataset.chosen = marked;
210      node.toggleAttribute(
211        "data-destination",
212        node.dataset.path === destination,
213      );
214    }
215    const selected = updateInspection(this.#rendered, {
216      structure,
217      selected: inspected,
218      preview: [],
219    });
220    if (selected !== this.#inspected) {
221      this.#captionObserver.disconnect();
222      this.#inspected = selected;
223      if (selected) {
224        // A primitive has one uniform gap: the first adjacent pair suffices.
225        for (const band of [
226          ...selected.querySelectorAll(
227            ':scope > [data-decoration="gap"] [data-observation="gap"]',
228          ),
229        ].slice(0, 2))
230          this.#captionObserver.observe(band);
231      }
232    }
233    this.#refreshCaption();
234  }
235
236  dispose() {
237    this.#abort.abort();
238    this.#widthControl?.cancel();
239    this.#modeObserver.disconnect();
240    this.#captionObserver.disconnect();
241    this.#readouts.disconnect();
242    this.#mounted?.dispose();
243    this.#mounted = undefined;
244    this.#inspected = undefined;
245    this.element.remove();
246  }
247
248  #nodes(): HTMLElement[] {
249    return [
250      ...this.#rendered.querySelectorAll<HTMLElement>(compositionSelector),
251    ];
252  }
253
254  /** Effective modes can be derived from an ancestor's published arrangement.
255   * Follow that signal, then read CSS for the labels alone. */
256  #refreshModes() {
257    this.#modes = [
258      ...this.#rendered.querySelectorAll<HTMLElement>('[data-kind="Switcher"]'),
259    ].map((node) => getComputedStyle(node).flexDirection);
260    this.#readouts.refreshModes();
261    this.#refreshCaption();
262  }
263
264  #refreshCaption() {
265    const text = describeSelection(this.#inspected);
266    if (this.#caption.textContent !== text) this.#caption.textContent = text;
267  }
268}