documentation/components/source/example-readouts.ts

1import { inlineObservation } from "./inline-observation.ts";
2import {
3  compositionMembers,
4  compositionAnchorName,
5} from "./composition-elements.ts";
6
7/**
8 * What a rendered composition reports about itself in any host: which
9 * Switchers are rows now, and whether a Shelf has more than it can show.
10 * An overflowing Shelf also becomes reachable from the keyboard.
11 *
12 * Teaching chrome observes only the boxes whose sizes it displays. It never
13 * determines the arrangement of a primitive.
14 */
15export class CompositionReadouts {
16  protected readonly observer: ResizeObserver;
17  private readonly shelves = new Set<HTMLElement>();
18  private readonly shelfInputs = new Set<Element>();
19  private readonly shelfObservations: ReturnType<typeof inlineObservation>[] =
20    [];
21  private scrollable = false;
22  private readonly note: HTMLElement;
23  private readonly directions: () => readonly string[];
24
25  constructor(note: HTMLElement, directions: () => readonly string[]) {
26    this.note = note;
27    this.directions = directions;
28    this.observer = new ResizeObserver((entries) => this.receive(entries));
29  }
30
31  protected receive(entries: readonly ResizeObserverEntry[]) {
32    if (entries.some((entry) => this.shelfInputs.has(entry.target)))
33      this.refreshOverflow();
34  }
35
36  /** Call after a composition edit; content-sized children expose overflow changes. */
37  observeComposition(rendered: HTMLElement) {
38    for (const input of this.shelfInputs) this.observer.unobserve(input);
39    this.shelfInputs.clear();
40    this.shelves.clear();
41    for (const observation of this.shelfObservations) observation.dispose();
42    this.shelfObservations.length = 0;
43    for (const marker of rendered.querySelectorAll(
44      '[data-decoration="overflow-extent"]',
45    ))
46      marker.remove();
47    for (const shelf of rendered.querySelectorAll<HTMLElement>(
48      '[data-kind="Shelf"]',
49    )) {
50      this.shelves.add(shelf);
51      const width = inlineObservation(shelf);
52      this.shelfObservations.push(width);
53      this.shelfInputs.add(width.target);
54      const members = compositionMembers(shelf);
55      if (members.length) {
56        const extent = shelf.ownerDocument.createElement("span");
57        extent.className = "overflow-extent";
58        extent.dataset.decoration = "overflow-extent";
59        extent.setAttribute("aria-hidden", "true");
60        extent.style.setProperty(
61          "--extent-first",
62          compositionAnchorName(members[0]!.dataset.path!),
63        );
64        extent.style.setProperty(
65          "--extent-last",
66          compositionAnchorName(members.at(-1)!.dataset.path!),
67        );
68        shelf.append(extent);
69        this.shelfInputs.add(extent);
70      }
71    }
72    for (const input of this.shelfInputs) {
73      this.observer.observe(input);
74    }
75    this.scrollable = false;
76    this.refreshModes();
77  }
78
79  refreshOverflow() {
80    this.scrollable = false;
81    for (const shelf of this.shelves) {
82      // Scroll extent is the input to keyboard accessibility, not a fit decision.
83      const overflow = shelf.scrollWidth > shelf.clientWidth + 1;
84      const tabIndex = overflow ? 0 : -1;
85      if (shelf.tabIndex !== tabIndex) shelf.tabIndex = tabIndex;
86      if (overflow) {
87        if (shelf.getAttribute("role") !== "group")
88          shelf.setAttribute("role", "group");
89        if (shelf.getAttribute("aria-label") !== "Scrollable row")
90          shelf.setAttribute("aria-label", "Scrollable row");
91        this.scrollable = true;
92      } else {
93        shelf.removeAttribute("role");
94        shelf.removeAttribute("aria-label");
95      }
96    }
97    this.refreshModes();
98  }
99
100  refreshModes() {
101    // Naming the primitive keeps this apart from a selected group's caption.
102    const modes = this.directions().map((direction) =>
103      direction === "row" ? "one row" : "one column",
104    );
105    const note = this.scrollable
106      ? "Scroll the row to read all its members."
107      : modes.length
108        ? `${modes.length > 1 ? "Switchers" : "Switcher"}: ${modes.join(" ยท ")}`
109        : "";
110    if (this.note.textContent !== note) this.note.textContent = note;
111  }
112
113  disconnect() {
114    this.observer.disconnect();
115    for (const observation of this.shelfObservations) observation.dispose();
116    this.shelfObservations.length = 0;
117    this.shelves.clear();
118    this.shelfInputs.clear();
119  }
120}
121
122/** Adds the width a resizable example has, and the widest it may request. */
123export class ExampleReadouts extends CompositionReadouts {
124  private actualWidth = 0;
125  private maximumWidth = 720;
126  private readonly stage: ReturnType<typeof inlineObservation>;
127  private readonly viewport: ReturnType<typeof inlineObservation>;
128  private readonly input: HTMLInputElement;
129
130  constructor(
131    stage: HTMLElement,
132    viewport: HTMLElement,
133    input: HTMLInputElement,
134    note: HTMLElement,
135    directions: () => readonly string[],
136  ) {
137    super(note, directions);
138    this.stage = inlineObservation(stage);
139    this.viewport = inlineObservation(viewport);
140    this.input = input;
141    this.observer.observe(this.stage.target);
142    this.observer.observe(this.viewport.target);
143  }
144
145  protected override receive(entries: readonly ResizeObserverEntry[]) {
146    for (const entry of entries) {
147      const size = entry.contentBoxSize[0]!.inlineSize;
148      if (entry.target === this.stage.target)
149        this.maximumWidth = Math.max(1, Math.min(720, size));
150      if (entry.target === this.viewport.target)
151        this.actualWidth = Math.round(size);
152    }
153    this.refreshWidth();
154    super.receive(entries);
155  }
156
157  get maximum(): number {
158    return this.maximumWidth;
159  }
160
161  refreshWidth() {
162    this.input.min = String(Math.min(160, this.maximumWidth));
163    this.input.max = String(Math.floor(this.maximumWidth));
164    const root = this.input.getRootNode();
165    if (root instanceof ShadowRoot && root.activeElement === this.input) return;
166    if (this.actualWidth) this.input.value = String(this.actualWidth);
167  }
168
169  override disconnect() {
170    super.disconnect();
171    this.stage.dispose();
172    this.viewport.dispose();
173  }
174}