documentation/components/source/source-panel.ts

1/**
2 * A composition's declaration, printed to fit its own panel, with every node
3 * name a button.
4 *
5 * The declaration is where any node can always be reached: a group with no
6 * members renders nothing in a preview, and its name is still here.
7 *
8 * The panel responds to its own inputs: the composition, the panel's width
9 * and its font. It keeps keyboard focus on the same node when it reprints,
10 * and one name in the tab order, moved with the Up and Down keys.
11 */
12import { declaration, type Composition } from "./composition.ts";
13import { atPath } from "./grouping.ts";
14import { highlightSource } from "./inspection.ts";
15import { inlineObservation } from "./inline-observation.ts";
16
17export interface SourcePanelOptions {
18  /** The accessible name of a node's button. */
19  describe(path: string, node: Composition): string;
20  /**
21   * The reader activated a node's name. `extend` is true when Shift was
22   * held, which an owner may read as adding to the selection.
23   */
24  choose(path: string, extend: boolean): void;
25  /** The pointer or focus is on a node, or has left the declaration. */
26  attend(path: string | undefined): void;
27  /**
28   * Whether `focus` may scroll the name into view. A panel inside its own
29   * scrolling box needs this; a panel in the page's flow keeps the page
30   * where its reader left it.
31   */
32  readonly revealFocus?: boolean;
33  readonly signal: AbortSignal;
34}
35
36export class SourcePanel {
37  readonly code: HTMLElement;
38  readonly #options: SourcePanelOptions;
39  readonly #observer: ResizeObserver;
40  readonly #width: ReturnType<typeof inlineObservation>;
41  #model: Composition | undefined;
42  #columns = 80;
43  #characterWidth = 7.2;
44  #inlineSize = 0;
45  #roving = "0";
46  #chosen: readonly string[] = [];
47  #destination: string | undefined;
48  #moving = false;
49  #structure = false;
50  #inspected: string | undefined;
51
52  constructor(pre: HTMLElement, options: SourcePanelOptions) {
53    const code = pre.querySelector("code");
54    if (!code) throw new Error("A source panel needs a code element");
55    this.code = code;
56    this.#options = options;
57    const { signal } = options;
58    this.#width = inlineObservation(pre);
59    this.#observer = new ResizeObserver((entries) => {
60      const size = entries.at(-1)?.contentBoxSize[0];
61      if (!size) return;
62      this.#inlineSize = size.inlineSize;
63      this.#fit();
64    });
65    this.#observer.observe(this.#width.target);
66    const measureFont = () => {
67      if (signal.aborted) return;
68      const context = code.ownerDocument
69        .createElement("canvas")
70        .getContext("2d");
71      if (context) {
72        context.font = getComputedStyle(pre).font;
73        this.#characterWidth = context.measureText("0").width || 7.2;
74      }
75      this.#fit();
76    };
77    code.ownerDocument.fonts.addEventListener("loadingdone", measureFont, {
78      signal,
79    });
80    void code.ownerDocument.fonts.ready.then(measureFont);
81
82    const pathAt = (target: EventTarget | null) =>
83      target instanceof Element
84        ? target.closest<HTMLElement>("[data-path]")?.dataset.path
85        : undefined;
86    code.addEventListener(
87      "click",
88      (event) => {
89        const path = pathAt(event.target);
90        if (path) options.choose(path, event.shiftKey);
91      },
92      { signal },
93    );
94    code.addEventListener(
95      "pointerover",
96      (event) => {
97        const path = pathAt(event.target);
98        if (path) options.attend(path);
99      },
100      { signal },
101    );
102    code.addEventListener("pointerleave", () => options.attend(undefined), {
103      signal,
104    });
105    code.addEventListener(
106      "focusin",
107      (event) => {
108        const name = event.target;
109        if (!(name instanceof HTMLElement) || !name.dataset.path) return;
110        this.rove(name.dataset.path);
111        options.attend(name.dataset.path);
112      },
113      { signal },
114    );
115    code.addEventListener(
116      "focusout",
117      (event) => {
118        if (
119          !(event.relatedTarget instanceof Node) ||
120          !code.contains(event.relatedTarget)
121        )
122          options.attend(undefined);
123      },
124      { signal },
125    );
126    code.addEventListener(
127      "keydown",
128      (event) => {
129        if (
130          (event.key !== "ArrowUp" && event.key !== "ArrowDown") ||
131          !(event.target instanceof HTMLElement) ||
132          !event.target.classList.contains("code-name")
133        )
134          return;
135        const names = this.#names();
136        const next =
137          names[
138            names.indexOf(event.target) + (event.key === "ArrowDown" ? 1 : -1)
139          ];
140        event.preventDefault();
141        next?.focus();
142      },
143      { signal },
144    );
145  }
146
147  /** Prints `model`. Focus on a name stays with the node at the same path. */
148  show(model: Composition) {
149    this.#model = model;
150    this.#print();
151  }
152
153  /** Marks the selection: each selected node, and the lines it spans. */
154  mark(chosen: readonly string[]) {
155    this.#chosen = chosen;
156    for (const element of this.code.querySelectorAll<HTMLElement>(
157      "[data-path]",
158    )) {
159      const path = element.dataset.path!;
160      element.dataset.chosen = String(
161        chosen.some(
162          (choice) => path === choice || path.startsWith(`${choice}.`),
163        ),
164      );
165      if (element.classList.contains("code-name")) {
166        // In move mode these buttons choose a destination, not the moving
167        // selection. Their names describe sources; aria-current marks target.
168        if (this.#moving) element.removeAttribute("aria-pressed");
169        else
170          element.setAttribute("aria-pressed", String(chosen.includes(path)));
171      }
172    }
173  }
174
175  /** Marks a proposed move destination without changing the selection. */
176  destination(path: string | undefined, moving = false) {
177    this.#destination = path;
178    this.#moving = moving;
179    for (const name of this.#names()) {
180      name.toggleAttribute("data-destination", name.dataset.path === path);
181      if (name.dataset.path === path) name.setAttribute("aria-current", "true");
182      else name.removeAttribute("aria-current");
183      const member = this.#model && atPath(this.#model, name.dataset.path!);
184      if (member)
185        name.setAttribute(
186          "aria-label",
187          this.#options.describe(name.dataset.path!, member),
188        );
189    }
190  }
191
192  /** Marks the node whose boundary the previews are showing. */
193  inspect(structure: boolean, path: string | undefined) {
194    this.#structure = structure;
195    this.#inspected = path;
196    this.code.classList.toggle("inspecting", structure);
197    highlightSource(this.code, structure, path);
198  }
199
200  /** Puts the name at `path`, or the root's, in the tab order. */
201  rove(path: string) {
202    const names = this.#names();
203    const target = names.find((name) => name.dataset.path === path) ?? names[0];
204    this.#roving = target?.dataset.path ?? "0";
205    for (const name of names) name.tabIndex = name === target ? 0 : -1;
206  }
207
208  /** Moves keyboard focus to the name at `path`. */
209  focus(path: string) {
210    this.rove(path);
211    this.code
212      .querySelector<HTMLElement>('.code-name[tabindex="0"]')
213      ?.focus({ preventScroll: !this.#options.revealFocus });
214  }
215
216  dispose() {
217    this.#observer.disconnect();
218    this.#width.dispose();
219  }
220
221  #names(): HTMLElement[] {
222    return [...this.code.querySelectorAll<HTMLElement>(".code-name")];
223  }
224
225  #fit() {
226    if (!this.#inlineSize) return;
227    const columns = Math.max(
228      16,
229      Math.min(80, Math.floor(this.#inlineSize / this.#characterWidth)),
230    );
231    if (columns === this.#columns) return;
232    this.#columns = columns;
233    this.#print();
234  }
235
236  #print() {
237    const model = this.#model;
238    if (!model) return;
239    const root = this.code.getRootNode() as Document | ShadowRoot;
240    const active = root.activeElement;
241    const focused =
242      active instanceof HTMLElement && this.code.contains(active)
243        ? active.dataset.path
244        : undefined;
245    const fragment = this.code.ownerDocument.createDocumentFragment();
246    for (const line of declaration(model, "0", 0, this.#columns)) {
247      const row = this.code.ownerDocument.createElement("span");
248      row.className = "code-line";
249      row.style.setProperty("--continuation", `${(line.depth + 1) * 2}ch`);
250      if (line.path) row.dataset.path = line.path;
251      for (const token of line.tokens) {
252        const span = this.code.ownerDocument.createElement(
253          token.kind ? "button" : "span",
254        );
255        span.className = `token ${token.tone ?? "plain"}${token.kind ? " code-name" : ""}`;
256        span.textContent = token.text;
257        if (token.path) span.dataset.path = token.path;
258        if (token.kind && token.path) {
259          span.setAttribute("type", "button");
260          const node = atPath(model, token.path);
261          if (node)
262            span.setAttribute(
263              "aria-label",
264              this.#options.describe(token.path, node),
265            );
266        }
267        row.append(span);
268      }
269      fragment.append(row);
270    }
271    this.code.replaceChildren(fragment);
272    this.mark(this.#chosen);
273    this.destination(this.#destination, this.#moving);
274    this.inspect(this.#structure, this.#inspected);
275    if (focused) this.focus(focused);
276    else this.rove(this.#roving);
277  }
278}