1/**
2 * Renders the controlled Composition tree as native boxes for
3 * `primitives.css`, and names the boxes the Switcher coordinator observes.
4 *
5 * Each rendered box answers two separate questions with separate hooks:
6 *
7 * - What it is, for layout: `data-axiomatic` and the spacing metadata. The
8 * stylesheet uses only these, so measurement copies are styled exactly like
9 * the boxes they stand for.
10 * - Which authored node it is, for selection and inspection: `.node`/`.leaf`,
11 * `data-kind` and `data-path`. Only real boxes carry these, so a consumer
12 * that queries them never meets a measurement box.
13 *
14 * Everything else under a `data-axiomatic-mechanical` element exists for
15 * measurement. It is hidden from assistive technology and holds no authored
16 * content of its own.
17 */
18import type { Composition } from "./composition.ts";
19import {
20 switcherCoordinator,
21 type SwitcherCoordinator,
22 type SwitcherRegistration,
23} from "./switcher-coordinator.ts";
24
25/** Matches the measurement boxes a Switcher owns, and nothing authored. */
26export const mechanicalSelector = "[data-axiomatic-mechanical]";
27
28/**
29 * Structural spacing for a composition, computed when the tree changes.
30 * `primitives.css` turns a level into a length.
31 *
32 * This is the provisional teaching policy: a leaf has no level; a group sits
33 * one level above its most widely spaced member, up to a ceiling of three.
34 * A group at the ceiling whose member is also there can no longer show the
35 * difference with space, so its members are separated by a boundary cue.
36 */
37export interface SpacingLevels {
38 readonly level: 0 | 1 | 2 | 3;
39 readonly cue: boolean;
40 readonly children: readonly SpacingLevels[];
41}
42
43export function spacingLevels(value: Composition): SpacingLevels {
44 if (!("children" in value)) return { level: 0, cue: false, children: [] };
45 const children = value.children.map(spacingLevels);
46 const inner = Math.max(0, ...children.map((child) => child.level));
47 return {
48 level: Math.min(3, inner + 1) as SpacingLevels["level"],
49 cue: inner >= 3,
50 children,
51 };
52}
53
54export interface RenderedComposition {
55 /**
56 * The root box. Place it where its container imposes an inline size that
57 * cannot depend on this composition's block size. A scrolling host with
58 * classic scrollbars needs `scrollbar-gutter: stable` to preserve that slot.
59 */
60 readonly element: HTMLElement;
61 /** One registration per Switcher, outermost first. */
62 readonly switchers: readonly SwitcherRegistration[];
63}
64
65/**
66 * Builds the boxes for a composition without registering anything.
67 *
68 * A Switcher's requirement is the max-content size of its content on one
69 * line, with every nested Switcher also on one line. The outermost Switcher
70 * therefore owns a single hidden copy of its subtree, laid out that way by
71 * CSS, and a nested Switcher's requirement is the size of its own copy inside
72 * it. The copy is built from the composition, never cloned from live boxes,
73 * so no current arrangement or teaching decoration can reach it.
74 */
75export function renderComposition(
76 value: Composition,
77 document: Document = globalThis.document,
78): RenderedComposition {
79 const switchers: SwitcherRegistration[] = [];
80
81 function box(value: Composition, levels: SpacingLevels): HTMLElement {
82 const branch = "children" in value;
83 const element = document.createElement(
84 branch ? "div" : value.kind === "Heading" ? "h3" : "p",
85 );
86 element.setAttribute("data-axiomatic", value.kind);
87 if (branch) element.setAttribute("data-axiomatic-level", `${levels.level}`);
88 else element.textContent = value.text;
89 return element;
90 }
91
92 function mechanical(role: "slot" | "requirement", content: HTMLElement) {
93 const element = document.createElement("div");
94 element.setAttribute("data-axiomatic-mechanical", role);
95 element.setAttribute("aria-hidden", "true");
96 element.setAttribute("inert", "");
97 element.append(content);
98 return element;
99 }
100
101 /** `copy` is present when an enclosing Switcher mirrors this subtree. */
102 function render(
103 value: Composition,
104 levels: SpacingLevels,
105 path: string,
106 mirrored: boolean,
107 ): { real: HTMLElement; copy: HTMLElement | undefined } {
108 const real = box(value, levels);
109 real.setAttribute("data-kind", value.kind);
110 real.setAttribute("data-path", path);
111 if (!("children" in value)) {
112 real.setAttribute("class", "leaf");
113 return { real, copy: mirrored ? box(value, levels) : undefined };
114 }
115 real.setAttribute("class", "node");
116 const decides = value.kind === "Switcher";
117 const copy = mirrored || decides ? box(value, levels) : undefined;
118 // The slot target sits one level below its mechanical parent on purpose:
119 // that keeps it deeper than an enclosing Switcher's requirement copy.
120 const slot = decides ? document.createElement("div") : undefined;
121 if (slot && copy)
122 switchers.push({ switcher: real, slot, requirement: copy });
123 value.children.forEach((child, index) => {
124 const member = render(
125 child,
126 levels.children[index]!,
127 `${path}.${index}`,
128 copy !== undefined,
129 );
130 if (levels.cue && index > 0)
131 member.real.setAttribute("data-axiomatic-cue", `${levels.level}`);
132 real.append(member.real);
133 if (member.copy) copy?.append(member.copy);
134 });
135 if (slot && copy) {
136 real.append(mechanical("slot", slot));
137 if (!mirrored) real.append(mechanical("requirement", copy));
138 }
139 return { real, copy: mirrored ? copy : undefined };
140 }
141
142 const { real } = render(value, spacingLevels(value), "0", false);
143 return { element: real, switchers };
144}
145
146export interface MountedComposition {
147 /** The current root box. `update` replaces it. */
148 readonly element: HTMLElement;
149 /** The boxes each current Switcher is decided from, outermost first. */
150 readonly switchers: readonly SwitcherRegistration[];
151 /** Renders a changed composition in the same place. */
152 update(value: Composition): void;
153 /** Unregisters every Switcher and removes the boxes. */
154 dispose(): void;
155}
156
157/**
158 * Renders a composition into `host` and keeps its Switchers registered with
159 * the document's shared coordinator for as long as it is mounted. The host
160 * decides the available inline size; nothing here observes or sets it.
161 */
162export function mountComposition(
163 host: Element,
164 value: Composition,
165 coordinator: SwitcherCoordinator = switcherCoordinator(host.ownerDocument),
166): MountedComposition {
167 let current: RenderedComposition;
168 let unregister: readonly (() => void)[] = [];
169
170 function show(value: Composition, place: (next: HTMLElement) => void) {
171 const rendered = renderComposition(value, host.ownerDocument);
172 for (const stop of unregister) stop();
173 unregister = rendered.switchers.map((switcher) =>
174 coordinator.register(switcher),
175 );
176 place(rendered.element);
177 current = rendered;
178 }
179
180 show(value, (next) => host.append(next));
181 return {
182 get element() {
183 return current.element;
184 },
185 get switchers() {
186 return current.switchers;
187 },
188 update(value) {
189 show(value, (next) => current.element.replaceWith(next));
190 },
191 dispose() {
192 for (const stop of unregister) stop();
193 unregister = [];
194 current.element.remove();
195 },
196 };
197}