documentation/components/source/inspection.ts

1import {
2  compositionMembers,
3  compositionAnchorName as anchorName,
4  compositionSelector,
5} from "./composition-elements.ts";
6
7export interface InspectionState {
8  readonly structure: boolean;
9  readonly selected: string | undefined;
10  readonly preview: readonly string[];
11}
12
13/** Structural decoration metadata changes with the composition, never on resize. */
14export function prepareInspection(rendered: HTMLElement) {
15  const nodes = [
16    ...rendered.querySelectorAll<HTMLElement>(compositionSelector),
17  ];
18  const maxDepth = Math.max(
19    1,
20    ...nodes.map((node) => node.dataset.path!.split(".").length),
21  );
22  rendered.style.setProperty(
23    "--inspection-fill",
24    `color-mix(in srgb, var(--ink) ${12 / maxDepth}%, transparent)`,
25  );
26  for (const node of nodes)
27    node.style.setProperty("anchor-name", anchorName(node.dataset.path!));
28  for (const old of rendered.querySelectorAll(
29    ':scope > [data-decoration="run-preview"]',
30  ))
31    old.remove();
32  const run = document.createElement("div");
33  run.className = "run-preview";
34  run.dataset.decoration = "run-preview";
35  run.setAttribute("aria-hidden", "true");
36  run.hidden = true;
37  rendered.append(run);
38}
39
40/** Selection updates attributes and sibling references; CSS follows layout. */
41export function updateInspection(
42  rendered: HTMLElement,
43  state: InspectionState,
44): HTMLElement | undefined {
45  const nodes = [
46    ...rendered.querySelectorAll<HTMLElement>(compositionSelector),
47  ];
48  rendered.dataset.structure = String(state.structure);
49  const previous = nodes.find((node) => node.dataset.inspected === "true");
50  const selected = nodes.find((node) => node.dataset.path === state.selected);
51  for (const node of nodes) {
52    const inspected = String(node === selected);
53    if (node.dataset.inspected !== inspected)
54      node.dataset.inspected = inspected;
55  }
56  if (previous !== selected) {
57    for (const band of rendered.querySelectorAll('[data-decoration="gap"]'))
58      band.remove();
59    if (selected?.classList.contains("node")) {
60      const children = compositionMembers(selected);
61      for (let index = 1; index < children.length; index++) {
62        for (const axis of ["block", "inline"]) {
63          const band = document.createElement("span");
64          band.className = "inspection-gap";
65          band.dataset.decoration = "gap";
66          band.dataset.axis = axis;
67          band.setAttribute("aria-hidden", "true");
68          band.style.setProperty(
69            "--before",
70            anchorName(children[index - 1]!.dataset.path!),
71          );
72          band.style.setProperty(
73            "--after",
74            anchorName(children[index]!.dataset.path!),
75          );
76          // Observe only the gap axis, below the Switcher's own targets.
77          // A member changing height must not invalidate an ancestor caption.
78          const wrapper = document.createElement("span");
79          const target = document.createElement("span");
80          target.dataset.observation = "gap";
81          wrapper.append(target);
82          band.append(wrapper);
83          selected.append(band);
84        }
85      }
86    }
87  }
88  const run = rendered.querySelector<HTMLElement>(
89    ':scope > [data-decoration="run-preview"]',
90  )!;
91  const preview = nodes.filter((node) =>
92    state.preview.includes(node.dataset.path!),
93  );
94  run.hidden = preview.length < 2;
95  if (preview.length > 1) {
96    run.style.setProperty("--run-first", anchorName(preview[0]!.dataset.path!));
97    run.style.setProperty(
98      "--run-last",
99      anchorName(preview.at(-1)!.dataset.path!),
100    );
101  }
102  return selected;
103}
104
105/** Source formatting changes only the source's selection marks. */
106export function highlightSource(
107  code: HTMLElement,
108  structure: boolean,
109  selected: string | undefined,
110) {
111  const includes = (path: string | undefined) =>
112    structure &&
113    selected !== undefined &&
114    (path === selected || path?.startsWith(`${selected}.`) === true);
115  for (const line of code.querySelectorAll<HTMLElement>(".code-line"))
116    line.dataset.selected = String(includes(line.dataset.path));
117  for (const token of code.querySelectorAll<HTMLElement>(".token[data-path]"))
118    token.dataset.selected = String(
119      includes(token.dataset.path) &&
120        token.closest<HTMLElement>(".code-line")?.dataset.selected !== "true",
121    );
122}
123
124/** Names the arrangement in effect. A Stack is always a column and a Shelf
125 * always a row; a Switcher's row or column is only what it is now, so the
126 * wording keeps the authored name apart from the current result. */
127export function currentArrangement(kind: string, row: boolean): string {
128  const direction = row ? "row" : "column";
129  return kind === "Switcher" ? `now a ${direction}` : direction;
130}
131
132/** A targeted style read for the numeric caption, never a rectangle overlay. */
133export function describeSelection(node: HTMLElement | undefined): string {
134  if (!node) return "";
135  if (node.classList.contains("leaf")) return `${node.dataset.kind} · leaf`;
136  const style = getComputedStyle(node);
137  const row = style.flexDirection === "row";
138  const members = compositionMembers(node);
139  const gap = row ? style.columnGap : style.rowGap;
140  return `${node.dataset.kind} · ${currentArrangement(node.dataset.kind!, row)} · ${members.length === 1 ? "1 member" : members.length ? `${members.length} members` : "no members"}${members.length > 1 ? ` · ${Math.round(Number.parseFloat(gap) || 0)} px between` : ""}`;
141}