documentation/components/source/switcher-coordinator.ts

1/**
2 * The shared decision for atomic Switchers.
3 *
4 * CSS lays a Switcher out as one row or one column. It cannot compare the
5 * row's intrinsic requirement with the space the Switcher's slot provides, so
6 * this module makes that one comparison and publishes the result as an
7 * attribute. It reads no geometry itself: the browser reports both numbers
8 * through a single ResizeObserver, and the decision is written inside the
9 * observer callback, before the frame paints.
10 *
11 * The module knows nothing about how a Switcher is rendered. A registration
12 * names the two boxes that carry its numbers; `primitives.ts` builds them for
13 * the controlled Composition tree.
14 *
15 * Dependencies between Switchers are carried by the browser, not by a tree
16 * walk here. Within a frame, ResizeObserver delivers in rounds, and after a
17 * round it redelivers only targets deeper than the shallowest target that
18 * round delivered, for any observer in the document. That places two
19 * obligations on tree depth:
20 *
21 * - A nested Switcher's slot is deeper than the slot and requirement of every
22 *   enclosing Switcher (see {@link SwitcherRegistration.slot}).
23 * - Any other observer of a box that a published arrangement can resize
24 *   watches from deeper than that Switcher's slot and requirement. Otherwise
25 *   its notification waits a frame and the browser reports a loop error.
26 */
27
28export type Arrangement = "row" | "column";
29
30/** Where the decision is published. CSS may still derive a row from the host
31 * (see `primitives.css`), so read `flex-direction` for the effective mode. */
32export const arrangementAttribute = "data-axiomatic-arrangement";
33
34/**
35 * A row that exactly fits is a row. Engines keep layout sizes in fixed-point
36 * units (1/64px in Blink and WebKit, 1/60px in Gecko), so two boxes laid out
37 * from the same content can report sizes one unit apart. The tolerance is
38 * four Blink units: above that noise, and far below a device pixel.
39 */
40export const fitTolerance = 1 / 16;
41
42/** The whole decision: a function of two numbers and no history. */
43export function arrangementFor(requirement: number, slot: number): Arrangement {
44  return requirement <= slot + fitTolerance ? "row" : "column";
45}
46
47export interface SwitcherRegistration {
48  /** Receives {@link arrangementAttribute}. */
49  readonly switcher: Element;
50  /**
51   * Its inline size is the space available to the row. The published
52   * arrangement must not be able to resize this box in a host that imposes a
53   * width, and it must sit deeper in the tree than the slot and requirement
54   * boxes of every enclosing registered Switcher, so that an ancestor's
55   * decision reaches it in the same frame.
56   */
57  readonly slot: Element;
58  /**
59   * Its inline size is the row requirement, laid out independently of every
60   * Switcher's current arrangement. Its block size is non-zero whenever it is
61   * rendered, so a 0×0 report means "not rendered" rather than "needs no room".
62   */
63  readonly requirement: Element;
64}
65
66/** What one observer delivery concluded for one Switcher. */
67export interface SwitcherDecision {
68  readonly switcher: Element;
69  readonly slot: number;
70  /** `undefined` while the requirement box is not rendered. */
71  readonly requirement: number | undefined;
72  /** `undefined` when the previous arrangement was kept for lack of a requirement. */
73  readonly arrangement: Arrangement | undefined;
74  readonly written: boolean;
75}
76
77interface Measured {
78  readonly registration: SwitcherRegistration;
79  /** Starts at zero, as an unreported ResizeObserver size does. */
80  slot: number;
81  requirement: number | undefined;
82}
83
84export class SwitcherCoordinator {
85  /** Diagnostic hook for fixtures: receives every delivery's conclusions. */
86  trace: ((decisions: readonly SwitcherDecision[]) => void) | undefined;
87
88  readonly #observer: ResizeObserver;
89  // Registration owners must unregister: native observation retains targets.
90  // `size` exposes outstanding registrations for lifecycle qualification.
91  readonly #measured = new WeakMap<Element, Measured>();
92  #size = 0;
93
94  constructor(Observer: typeof ResizeObserver) {
95    this.#observer = new Observer((entries) => this.#receive(entries));
96  }
97
98  /** Registrations not yet unregistered. */
99  get size(): number {
100    return this.#size;
101  }
102
103  /** Starts deciding for a Switcher. Call the returned function to stop. */
104  register(registration: SwitcherRegistration): () => void {
105    const { slot, requirement } = registration;
106    if (this.#measured.has(slot) || this.#measured.has(requirement))
107      throw new Error("This Switcher is already registered");
108    const measured: Measured = {
109      registration,
110      slot: 0,
111      requirement: undefined,
112    };
113    this.#measured.set(slot, measured);
114    this.#measured.set(requirement, measured);
115    this.#observer.observe(slot);
116    this.#observer.observe(requirement);
117    this.#size++;
118    let registered = true;
119    return () => {
120      if (!registered) return;
121      registered = false;
122      this.#observer.unobserve(slot);
123      this.#observer.unobserve(requirement);
124      this.#measured.delete(slot);
125      this.#measured.delete(requirement);
126      this.#size--;
127    };
128  }
129
130  #receive(entries: readonly ResizeObserverEntry[]) {
131    // Record every delivered number before deciding, so the result cannot
132    // depend on the order of entries within a delivery.
133    const affected = new Set<Measured>();
134    for (const entry of entries) {
135      const measured = this.#measured.get(entry.target);
136      const size = entry.contentBoxSize[0];
137      if (!measured || !size) continue;
138      if (entry.target === measured.registration.slot) {
139        measured.slot = size.inlineSize;
140      } else {
141        const rendered = size.inlineSize > 0 || size.blockSize > 0;
142        measured.requirement = rendered ? size.inlineSize : undefined;
143      }
144      affected.add(measured);
145    }
146    const decisions: SwitcherDecision[] = [];
147    for (const { registration, slot, requirement } of affected) {
148      const { switcher } = registration;
149      // Without a rendered requirement there is nothing to compare. Keeping
150      // the last arrangement lets a hidden Switcher reappear undisturbed.
151      const arrangement =
152        requirement === undefined
153          ? undefined
154          : arrangementFor(requirement, slot);
155      const written =
156        arrangement !== undefined &&
157        switcher.getAttribute(arrangementAttribute) !== arrangement;
158      if (written) switcher.setAttribute(arrangementAttribute, arrangement);
159      decisions.push({ switcher, slot, requirement, arrangement, written });
160    }
161    this.trace?.(decisions);
162  }
163}
164
165const coordinators = new WeakMap<Document, SwitcherCoordinator>();
166
167/** The one coordinator, and so the one ResizeObserver, for a document. It
168 * serves Switchers in the document and in any of its shadow roots. */
169export function switcherCoordinator(document: Document): SwitcherCoordinator {
170  let coordinator = coordinators.get(document);
171  if (!coordinator) {
172    const view = document.defaultView;
173    if (!view) throw new Error("Switchers need a document with a window");
174    coordinator = new SwitcherCoordinator(view.ResizeObserver);
175    coordinators.set(document, coordinator);
176  }
177  return coordinator;
178}