documentation/components/source/outline-panel.ts

1/**
2 * A composition as an outline: one row for each node, indented by nesting.
3 *
4 * This is the hierarchy for an author who has not learned to read the
5 * declaration. Every node has a row, so a group can be chosen whether or not
6 * it has members, and each row says in words what it is.
7 *
8 * It shows the same model and selection as `SourcePanel`, through the same
9 * calls, so an editor can offer either one as its view of the hierarchy.
10 */
11import type { Composition } from "./composition.ts";
12import { atPath } from "./grouping.ts";
13
14/** What a row says about its node, beside the node's kind. */
15export function outlineLabel(node: Composition, root: boolean): string {
16  if (!("children" in node)) return node.text || "Empty text";
17  const count = node.children.length;
18  if (root) return count ? "Whole composition" : "Whole composition, empty";
19  return count === 0
20    ? "Empty group"
21    : count === 1
22      ? "1 member"
23      : `${count} members`;
24}
25
26export interface OutlinePanelOptions {
27  /** The accessible name of a node's row. */
28  describe(path: string, node: Composition): string;
29  /**
30   * The author activated a node's row. `extend` is true when Shift was held,
31   * which an owner may read as adding to the selection.
32   */
33  choose(path: string, extend: boolean): void;
34  /** The pointer or focus is on a node, or has left the outline. */
35  attend(path: string | undefined): void;
36  readonly signal: AbortSignal;
37}
38
39export class OutlinePanel {
40  readonly #host: HTMLElement;
41  readonly #options: OutlinePanelOptions;
42  #model: Composition | undefined;
43  #roving = "0";
44  #chosen: readonly string[] = [];
45  #destination: string | undefined;
46  #moving = false;
47  #inspected: string | undefined;
48
49  constructor(host: HTMLElement, options: OutlinePanelOptions) {
50    this.#host = host;
51    this.#options = options;
52    const { signal } = options;
53    const pathAt = (target: EventTarget | null) =>
54      target instanceof Element
55        ? target.closest<HTMLElement>("[data-path]")?.dataset.path
56        : undefined;
57    host.addEventListener(
58      "click",
59      (event) => {
60        const path = pathAt(event.target);
61        if (path) options.choose(path, event.shiftKey);
62      },
63      { signal },
64    );
65    host.addEventListener(
66      "pointerover",
67      (event) => {
68        const path = pathAt(event.target);
69        if (path) options.attend(path);
70      },
71      { signal },
72    );
73    host.addEventListener("pointerleave", () => options.attend(undefined), {
74      signal,
75    });
76    host.addEventListener(
77      "focusin",
78      (event) => {
79        const path = pathAt(event.target);
80        if (!path) return;
81        this.rove(path);
82        options.attend(path);
83      },
84      { signal },
85    );
86    host.addEventListener(
87      "focusout",
88      (event) => {
89        if (
90          !(event.relatedTarget instanceof Node) ||
91          !host.contains(event.relatedTarget)
92        )
93          options.attend(undefined);
94      },
95      { signal },
96    );
97    host.addEventListener(
98      "keydown",
99      (event) => {
100        const rows = this.#rows();
101        const at = rows.indexOf(event.target as HTMLElement);
102        const to: Record<string, number> = {
103          ArrowDown: at + 1,
104          ArrowUp: at - 1,
105          Home: 0,
106          End: rows.length - 1,
107        };
108        const next = to[event.key];
109        if (at < 0 || next === undefined) return;
110        event.preventDefault();
111        rows[next]?.focus();
112      },
113      { signal },
114    );
115  }
116
117  /** Lists `model`. Focus on a row stays with the node at the same path. */
118  show(model: Composition) {
119    this.#model = model;
120    const document = this.#host.ownerDocument;
121    const root = this.#host.getRootNode() as Document | ShadowRoot;
122    const active = root.activeElement;
123    const focused =
124      active instanceof HTMLElement && this.#host.contains(active)
125        ? active.dataset.path
126        : undefined;
127    const item = (node: Composition, path: string, depth: number) => {
128      const row = document.createElement("button");
129      row.type = "button";
130      row.className = "outline-row";
131      row.dataset.path = path;
132      // CSS turns the depth into an indent.
133      row.style.setProperty("--depth", String(depth));
134      const empty = "children" in node ? !node.children.length : !node.text;
135      row.toggleAttribute("data-empty", empty);
136      for (const [name, text] of [
137        ["row-kind", node.kind],
138        ["row-label", outlineLabel(node, path === "0")],
139        ["row-state", ""],
140      ] as const) {
141        const part = document.createElement("span");
142        part.className = name;
143        part.textContent = text;
144        row.append(part);
145      }
146      const entry = document.createElement("li");
147      entry.append(row);
148      if ("children" in node && node.children.length) {
149        const members = document.createElement("ul");
150        node.children.forEach((child, index) =>
151          members.append(item(child, `${path}.${index}`, depth + 1)),
152        );
153        entry.append(members);
154      }
155      return entry;
156    };
157    const list = document.createElement("ul");
158    list.append(item(model, "0", 0));
159    this.#host.replaceChildren(list);
160    this.#decorate();
161    if (focused) this.focus(focused);
162    else this.rove(this.#roving);
163  }
164
165  /** Marks the selection. */
166  mark(chosen: readonly string[]) {
167    this.#chosen = chosen;
168    this.#decorate();
169  }
170
171  /** Marks a proposed move destination without changing the selection. */
172  destination(path: string | undefined, moving = false) {
173    this.#destination = path;
174    this.#moving = moving;
175    this.#decorate();
176  }
177
178  /** Marks the node whose boundary the previews are showing. */
179  inspect(structure: boolean, path: string | undefined) {
180    this.#inspected = structure ? path : undefined;
181    this.#decorate();
182  }
183
184  /** Puts the row at `path`, or the root's, in the tab order. */
185  rove(path: string) {
186    const rows = this.#rows();
187    const target = rows.find((row) => row.dataset.path === path) ?? rows[0];
188    this.#roving = target?.dataset.path ?? "0";
189    for (const row of rows) row.tabIndex = row === target ? 0 : -1;
190  }
191
192  /** Moves keyboard focus to the row at `path`, scrolling it into view. */
193  focus(path: string) {
194    this.rove(path);
195    this.#host
196      .querySelector<HTMLElement>('.outline-row[tabindex="0"]')
197      ?.focus();
198  }
199
200  #rows(): HTMLElement[] {
201    return [...this.#host.querySelectorAll<HTMLElement>(".outline-row")];
202  }
203
204  #decorate() {
205    for (const row of this.#rows()) {
206      const path = row.dataset.path!;
207      const chosen = this.#chosen.includes(path);
208      const target = path === this.#destination;
209      row.dataset.chosen = String(chosen);
210      row.toggleAttribute("data-destination", target);
211      row.toggleAttribute("data-inspected", path === this.#inspected);
212      // While moving, a row chooses a destination. The selection is what
213      // moves, so it is named in words and is no longer a pressed choice.
214      if (this.#moving) row.removeAttribute("aria-pressed");
215      else row.setAttribute("aria-pressed", String(chosen));
216      if (target) row.setAttribute("aria-current", "true");
217      else row.removeAttribute("aria-current");
218      const state = target
219        ? "destination"
220        : this.#moving && chosen
221          ? "moving"
222          : "";
223      const note = row.querySelector(".row-state")!;
224      if (note.textContent !== state) note.textContent = state;
225      const node = this.#model && atPath(this.#model, path);
226      if (node)
227        row.setAttribute("aria-label", this.#options.describe(path, node));
228    }
229  }
230}