tests/primitives.test.ts

1import { test } from "node:test";
2import assert from "node:assert/strict";
3import {
4  example,
5  Stack,
6  Shelf,
7  Switcher,
8  type Composition,
9} from "../documentation/components/source/composition.ts";
10import {
11  mountComposition,
12  renderComposition,
13  spacingLevels,
14} from "../documentation/components/source/primitives.ts";
15import { SwitcherCoordinator } from "../documentation/components/source/switcher-coordinator.ts";
16
17/** The few DOM operations the renderer uses, with a tree tests can walk. */
18class FakeElement {
19  readonly tagName: string;
20  readonly ownerDocument: FakeDocument;
21  readonly attributes = new Map<string, string>();
22  readonly children: FakeElement[] = [];
23  parent: FakeElement | undefined;
24  textContent = "";
25  constructor(tagName: string, ownerDocument: FakeDocument) {
26    this.tagName = tagName;
27    this.ownerDocument = ownerDocument;
28  }
29  setAttribute(name: string, value: string) {
30    this.attributes.set(name, value);
31  }
32  getAttribute(name: string) {
33    return this.attributes.get(name) ?? null;
34  }
35  append(child: FakeElement) {
36    child.remove();
37    child.parent = this;
38    this.children.push(child);
39  }
40  remove() {
41    const siblings = this.parent?.children;
42    siblings?.splice(siblings.indexOf(this), 1);
43    this.parent = undefined;
44  }
45  replaceWith(next: FakeElement) {
46    const parent = this.parent!;
47    next.remove();
48    parent.children[parent.children.indexOf(this)] = next;
49    next.parent = parent;
50    this.parent = undefined;
51  }
52}
53class FakeDocument {
54  createElement(tagName: string) {
55    return new FakeElement(tagName, this);
56  }
57}
58class IdleObserver {
59  static observed = new Set<unknown>();
60  observe(target: unknown) {
61    IdleObserver.observed.add(target);
62  }
63  unobserve(target: unknown) {
64    IdleObserver.observed.delete(target);
65  }
66  disconnect() {}
67}
68
69const text = (value: string): Composition => ({ kind: "Text", text: value });
70const [a, b, c, d, e] = ["a", "b", "c", "d", "e"].map(text) as [
71  Composition,
72  Composition,
73  Composition,
74  Composition,
75  Composition,
76];
77
78function render(value: Composition) {
79  const rendered = renderComposition(
80    value,
81    new FakeDocument() as unknown as Document,
82  );
83  return {
84    root: rendered.element as unknown as FakeElement,
85    switchers: rendered.switchers as unknown as {
86      switcher: FakeElement;
87      slot: FakeElement;
88      requirement: FakeElement;
89    }[],
90  };
91}
92const mechanical = (element: FakeElement) =>
93  element.getAttribute("data-axiomatic-mechanical");
94const descendants = (element: FakeElement): FakeElement[] =>
95  element.children.flatMap((child) => [child, ...descendants(child)]);
96const depth = (element: FakeElement): number =>
97  element.parent ? depth(element.parent) + 1 : 0;
98const within = (element: FakeElement, ancestor: FakeElement): boolean =>
99  !!element.parent &&
100  (element.parent === ancestor || within(element.parent, ancestor));
101/** The composition a tree of boxes states, ignoring measurement boxes. */
102function stated(element: FakeElement): unknown {
103  const kind = element.getAttribute("data-axiomatic");
104  const members = element.children.filter((child) => !mechanical(child));
105  return element.getAttribute("data-axiomatic-level") === null
106    ? { kind, text: element.textContent }
107    : { kind, children: members.map(stated) };
108}
109
110test("structural spacing distinguishes nesting until the ceiling needs a cue", () => {
111  const one = Stack(a, b);
112  const two = Stack(one, c);
113  const three = Stack(two, d);
114  const four = Stack(three, e);
115  for (const [tree, level, cue] of [
116    [a, 0, false],
117    [Stack(), 1, false],
118    [one, 1, false],
119    [two, 2, false],
120    [three, 3, false],
121    [four, 3, true],
122    [example("article"), 3, true],
123  ] as const) {
124    const actual = spacingLevels(tree);
125    assert.equal(actual.level, level);
126    assert.equal(actual.cue, cue);
127  }
128  assert.equal(spacingLevels(four).children[0]!.cue, false);
129  assert.deepEqual(spacingLevels(a).children, []);
130});
131
132test("real boxes keep native elements, reading order and the source mapping", () => {
133  const { root } = render(example("article"));
134  const real = [root, ...descendants(root)].filter(
135    (element) => element.getAttribute("data-path") !== null,
136  );
137  assert.deepEqual(stated(root), example("article"));
138  assert.deepEqual(
139    real
140      .slice(0, 6)
141      .map((element) => [
142        element.tagName,
143        element.getAttribute("class"),
144        element.getAttribute("data-kind"),
145        element.getAttribute("data-path"),
146      ]),
147    [
148      ["div", "node", "Stack", "0"],
149      ["div", "node", "Stack", "0.0"],
150      ["h3", "leaf", "Heading", "0.0.0"],
151      ["p", "leaf", "Text", "0.0.1"],
152      ["div", "node", "Shelf", "0.0.2"],
153      ["p", "leaf", "Meta", "0.0.2.0"],
154    ],
155  );
156  assert.deepEqual(
157    [root, ...descendants(root)].filter(mechanical),
158    [],
159    "a composition without a Switcher has no measurement boxes",
160  );
161});
162
163test("a group with one member or none keeps its box, level and Switcher decision", () => {
164  const tree = Stack(Switcher(), Shelf(a), Stack(), Switcher(b));
165  const { root, switchers } = render(tree);
166  assert.deepEqual(stated(root), tree, "no group is dropped or merged");
167  assert.deepEqual(
168    root.children.map((child) => [
169      child.getAttribute("data-path"),
170      child.getAttribute("data-axiomatic-level"),
171    ]),
172    [
173      ["0.0", "1"],
174      ["0.1", "1"],
175      ["0.2", "1"],
176      ["0.3", "1"],
177    ],
178  );
179  // A parent spaces its members as groups, whatever those groups hold.
180  assert.equal(root.getAttribute("data-axiomatic-level"), "2");
181  assert.deepEqual(spacingLevels(Stack(Stack())).level, 2);
182  // Each Switcher is still decided: its requirement copy states what it
183  // holds, and nothing stands in for missing content.
184  assert.deepEqual(
185    switchers.map(({ switcher, requirement }) => [
186      switcher.getAttribute("data-path"),
187      stated(requirement),
188    ]),
189    [
190      ["0.0", Switcher()],
191      ["0.3", Switcher(b)],
192    ],
193  );
194  assert.deepEqual(
195    switchers[0]!.switcher.children.map(mechanical),
196    ["slot", "requirement"],
197    "an empty Switcher holds only its measurement boxes",
198  );
199});
200
201test("a boundary cue names the spacing level of the group it divides", () => {
202  const { root } = render(Stack(Stack(Stack(Stack(a, b), c), d), e));
203  const cues = (element: FakeElement) =>
204    element.children.map((child) => child.getAttribute("data-axiomatic-cue"));
205  assert.equal(root.getAttribute("data-axiomatic-level"), "3");
206  assert.deepEqual(cues(root), [null, "3"]);
207  assert.deepEqual(cues(root.children[0]!), [null, null], "below the ceiling");
208});
209
210test("each Switcher's requirement is its own row inside one hidden copy", () => {
211  const tree = Stack(Switcher(Stack(Switcher(a, b), c), d), Switcher(e, a));
212  const { root, switchers } = render(tree);
213  assert.deepEqual(
214    switchers.map(({ switcher }) => switcher.getAttribute("data-path")),
215    ["0.0", "0.0.0.0", "0.1"],
216    "outermost first",
217  );
218  const [outer, inner, sibling] = switchers as [
219    (typeof switchers)[0],
220    (typeof switchers)[0],
221    (typeof switchers)[0],
222  ];
223  const holders = [root, ...descendants(root)].filter(
224    (element) => mechanical(element) === "requirement",
225  );
226  assert.deepEqual(
227    holders.map((holder) => holder.parent),
228    [outer.switcher, sibling.switcher],
229    "only outermost Switchers hold a copy",
230  );
231  // The copy states the same composition as the real subtree it stands for.
232  assert.deepEqual(
233    stated(outer.requirement),
234    Switcher(Stack(Switcher(a, b), c), d),
235  );
236  assert.deepEqual(stated(inner.requirement), Switcher(a, b));
237  assert.ok(within(inner.requirement, outer.requirement));
238  assert.ok(!within(inner.requirement, inner.switcher));
239  // Each Switcher has its own slot, a direct mechanical child of the real box.
240  for (const { switcher, slot } of switchers) {
241    assert.equal(mechanical(slot.parent!), "slot");
242    assert.equal(slot.parent!.parent, switcher);
243  }
244});
245
246test("measurement boxes are hidden from assistive technology and carry no authored identity", () => {
247  const { root } = render(Stack(Switcher(Shelf(a, b), Switcher(c, d)), e));
248  const boxes = [root, ...descendants(root)];
249  const roots = boxes.filter(mechanical);
250  assert.equal(roots.length, 3);
251  for (const element of roots) {
252    assert.equal(element.getAttribute("aria-hidden"), "true");
253    assert.equal(element.getAttribute("inert"), "");
254  }
255  for (const element of roots.flatMap((element) => [
256    element,
257    ...descendants(element),
258  ])) {
259    for (const hook of [
260      "class",
261      "data-kind",
262      "data-path",
263      "data-axiomatic-cue",
264    ])
265      assert.equal(element.getAttribute(hook), null, hook);
266  }
267  // Real members are exactly the children that are not mechanical.
268  const outer = root.children[0]!;
269  assert.deepEqual(
270    outer.children.map(
271      (child) => child.getAttribute("data-path") ?? mechanical(child),
272    ),
273    ["0.0.0", "0.0.1", "slot", "requirement"],
274  );
275});
276
277test("a nested slot is deeper than every box an enclosing Switcher is decided from", () => {
278  // After an ancestor's decision the browser redelivers only deeper targets
279  // in the same frame, so this ordering is what carries the dependency.
280  const { switchers } = render(
281    Switcher(Stack(Switcher(a, Switcher(b, c))), Shelf(Switcher(d, e)), a),
282  );
283  assert.equal(switchers.length, 4);
284  let pairs = 0;
285  for (const outer of switchers) {
286    for (const inner of switchers) {
287      if (!within(inner.switcher, outer.switcher)) continue;
288      pairs++;
289      assert.ok(depth(inner.slot) > depth(outer.slot));
290      assert.ok(depth(inner.slot) > depth(outer.requirement));
291    }
292  }
293  assert.equal(pairs, 4);
294});
295
296test("mounting registers Switchers, updating swaps them, disposing leaves nothing", () => {
297  const document = new FakeDocument();
298  const host = document.createElement("div");
299  const neighbor = document.createElement("div");
300  const coordinator = new SwitcherCoordinator(
301    IdleObserver as unknown as typeof ResizeObserver,
302  );
303  const mounted = mountComposition(
304    host as unknown as Element,
305    Stack(Switcher(a, b), c),
306    coordinator,
307  );
308  host.append(neighbor);
309  const first = mounted.element as unknown as FakeElement;
310  assert.equal(coordinator.size, 1);
311  assert.equal(IdleObserver.observed.size, 2);
312
313  mounted.update(Stack(Switcher(Switcher(a, b), c), Switcher(d, e)));
314  const second = mounted.element as unknown as FakeElement;
315  assert.notEqual(second, first);
316  assert.deepEqual(host.children, [second, neighbor], "replaced in place");
317  assert.equal(first.parent, undefined);
318  assert.equal(coordinator.size, 3);
319  assert.ok(
320    [...IdleObserver.observed].every((target) =>
321      within(target as FakeElement, second),
322    ),
323    "the previous tree is no longer observed",
324  );
325
326  mounted.dispose();
327  assert.equal(coordinator.size, 0);
328  assert.equal(IdleObserver.observed.size, 0);
329  assert.deepEqual(host.children, [neighbor]);
330});