@uselazuli/cli 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/LICENSE +21 -0
  3. package/README.md +202 -2
  4. package/agents/lazuli-design-reviewer.md +30 -0
  5. package/agents/lazuli-first-look.md +22 -0
  6. package/agents/lazuli-task-tester.md +25 -0
  7. package/bin/lazuli.mjs +699 -0
  8. package/package.json +11 -4
  9. package/rules/accessibility/HYPOTHESES.md +8 -0
  10. package/rules/accessibility/_area.yaml +7 -0
  11. package/rules/accessibility/operable.yaml +100 -0
  12. package/rules/accessibility/perceivable.yaml +153 -0
  13. package/rules/accessibility/robust.yaml +24 -0
  14. package/rules/accessibility/understandable.yaml +72 -0
  15. package/rules/color/HYPOTHESES.md +27 -0
  16. package/rules/color/_area.yaml +10 -0
  17. package/rules/color/adapt.yaml +183 -0
  18. package/rules/color/create.yaml +259 -0
  19. package/rules/color/review.yaml +215 -0
  20. package/rules/color/signal.yaml +196 -0
  21. package/rules/content/HYPOTHESES.md +18 -0
  22. package/rules/content/_area.yaml +8 -0
  23. package/rules/content/review.yaml +347 -0
  24. package/rules/content/voice.yaml +144 -0
  25. package/rules/content/writing.yaml +202 -0
  26. package/rules/data/HYPOTHESES.md +11 -0
  27. package/rules/data/_area.yaml +7 -0
  28. package/rules/data/charts.yaml +189 -0
  29. package/rules/data/dashboards.yaml +141 -0
  30. package/rules/data/review.yaml +159 -0
  31. package/rules/graphic/HYPOTHESES.md +17 -0
  32. package/rules/graphic/_area.yaml +8 -0
  33. package/rules/graphic/identity.yaml +141 -0
  34. package/rules/graphic/pieces.yaml +164 -0
  35. package/rules/graphic/review.yaml +242 -0
  36. package/rules/graphic/symbol.yaml +141 -0
  37. package/rules/motion/HYPOTHESES.md +19 -0
  38. package/rules/motion/_area.yaml +7 -0
  39. package/rules/motion/micro.yaml +143 -0
  40. package/rules/motion/review.yaml +347 -0
  41. package/rules/motion/transitions.yaml +169 -0
  42. package/rules/typography/HYPOTHESES.md +12 -0
  43. package/rules/typography/_area.yaml +8 -0
  44. package/rules/typography/adapt.yaml +45 -0
  45. package/rules/typography/create.yaml +126 -0
  46. package/rules/typography/review.yaml +127 -0
  47. package/rules/ui/HYPOTHESES.md +23 -0
  48. package/rules/ui/_area.yaml +9 -0
  49. package/rules/ui/compose.yaml +219 -0
  50. package/rules/ui/grid.yaml +75 -0
  51. package/rules/ui/review.yaml +399 -0
  52. package/rules/ui/states.yaml +257 -0
  53. package/rules/ux/HYPOTHESES.md +13 -0
  54. package/rules/ux/_area.yaml +8 -0
  55. package/rules/ux/flows.yaml +164 -0
  56. package/rules/ux/forms.yaml +142 -0
  57. package/rules/ux/review.yaml +186 -0
  58. package/skills/lazuli/SKILL.md +180 -0
  59. package/skills/lazuli/procedures/create.md +29 -0
  60. package/skills/lazuli/procedures/explain-decisions.md +22 -0
  61. package/skills/lazuli/procedures/improve.md +30 -0
  62. package/skills/lazuli/procedures/remember-this.md +41 -0
  63. package/skills/lazuli/procedures/review-design.md +35 -0
  64. package/skills/lazuli/procedures/show-options.md +32 -0
  65. package/skills/lazuli-accessibility-check/SKILL.md +68 -0
  66. package/skills/lazuli-color-context-and-culture/SKILL.md +53 -0
  67. package/skills/lazuli-color-context-and-culture/references/sectors.md +26 -0
  68. package/skills/lazuli-color-palette-by-intent/SKILL.md +54 -0
  69. package/skills/lazuli-color-palette-by-intent/references/intent-chords.md +51 -0
  70. package/skills/lazuli-color-screen-review/SKILL.md +51 -0
  71. package/skills/lazuli-color-states-and-signals/SKILL.md +53 -0
  72. package/skills/lazuli-content-interface-writing/SKILL.md +53 -0
  73. package/skills/lazuli-content-voice/SKILL.md +39 -0
  74. package/skills/lazuli-data-charts-and-dashboards/SKILL.md +59 -0
  75. package/skills/lazuli-graphic-derived-pieces/SKILL.md +40 -0
  76. package/skills/lazuli-graphic-derived-pieces/references/piece-template.html +24 -0
  77. package/skills/lazuli-graphic-identity/SKILL.md +43 -0
  78. package/skills/lazuli-motion-micro-and-transitions/SKILL.md +49 -0
  79. package/skills/lazuli-typography-choose-and-pair/SKILL.md +50 -0
  80. package/skills/lazuli-typography-screen-review/SKILL.md +51 -0
  81. package/skills/lazuli-ui-composition/SKILL.md +42 -0
  82. package/skills/lazuli-ui-composition/references/option-template.html +34 -0
  83. package/skills/lazuli-ui-layout-review/SKILL.md +47 -0
  84. package/skills/lazuli-ui-states-and-system/SKILL.md +54 -0
  85. package/skills/lazuli-ux-flows-and-forms/SKILL.md +51 -0
  86. package/skills/lazuli-ux-task-test/SKILL.md +44 -0
  87. package/src/browser.mjs +161 -0
  88. package/src/commands/capture.mjs +313 -0
  89. package/src/commands/catalog.mjs +37 -0
  90. package/src/commands/check-design.mjs +428 -0
  91. package/src/commands/check-goals.mjs +57 -0
  92. package/src/commands/compare-designs.mjs +97 -0
  93. package/src/commands/draft-memo.mjs +161 -0
  94. package/src/commands/hooks.mjs +343 -0
  95. package/src/commands/install-hooks.mjs +120 -0
  96. package/src/commands/install.mjs +132 -0
  97. package/src/commands/list-rules.mjs +49 -0
  98. package/src/commands/map-page.mjs +594 -0
  99. package/src/commands/record-answers.mjs +79 -0
  100. package/src/commands/record-log.mjs +296 -0
  101. package/src/commands/record-task.mjs +250 -0
  102. package/src/commands/render-options.mjs +164 -0
  103. package/src/commands/start-project.mjs +32 -0
  104. package/src/measure/a11y.mjs +383 -0
  105. package/src/measure/asset.mjs +206 -0
  106. package/src/measure/at-rest.mjs +49 -0
  107. package/src/measure/cases.mjs +549 -0
  108. package/src/measure/chart-read.mjs +401 -0
  109. package/src/measure/chart.mjs +264 -0
  110. package/src/measure/coherence.mjs +145 -0
  111. package/src/measure/color.mjs +79 -0
  112. package/src/measure/content.mjs +82 -0
  113. package/src/measure/cvd.mjs +24 -0
  114. package/src/measure/extreme.mjs +241 -0
  115. package/src/measure/forms.mjs +150 -0
  116. package/src/measure/in-page/a11y.js +489 -0
  117. package/src/measure/in-page/color.js +346 -0
  118. package/src/measure/in-page/composition.js +1496 -0
  119. package/src/measure/in-page/contrast.js +15 -0
  120. package/src/measure/in-page/cvd.js +173 -0
  121. package/src/measure/in-page/extreme.js +355 -0
  122. package/src/measure/in-page/frames.js +781 -0
  123. package/src/measure/in-page/look.js +28 -0
  124. package/src/measure/in-page/motion-probe.js +169 -0
  125. package/src/measure/in-page/style.js +107 -0
  126. package/src/measure/in-page/svg-strokes.js +112 -0
  127. package/src/measure/in-page/svg-uses.js +50 -0
  128. package/src/measure/in-page/symbol.js +123 -0
  129. package/src/measure/in-page/type.js +266 -0
  130. package/src/measure/in-page/weight.js +207 -0
  131. package/src/measure/layout.mjs +91 -0
  132. package/src/measure/motion.mjs +508 -0
  133. package/src/measure/piece.mjs +195 -0
  134. package/src/measure/registry.mjs +252 -0
  135. package/src/measure/rhythm.mjs +81 -0
  136. package/src/measure/signature.mjs +65 -0
  137. package/src/measure/states.mjs +240 -0
  138. package/src/measure/style.mjs +13 -0
  139. package/src/measure/symbol.mjs +268 -0
  140. package/src/measure/terms.mjs +153 -0
  141. package/src/measure/tiles.mjs +20 -0
  142. package/src/measure/timeline.mjs +621 -0
  143. package/src/measure/type.mjs +167 -0
  144. package/src/measure/weight.mjs +18 -0
  145. package/src/private-strings.mjs +81 -0
  146. package/src/project/blind.mjs +70 -0
  147. package/src/project/edits.mjs +154 -0
  148. package/src/project/gate.mjs +159 -0
  149. package/src/project/lazuli-md.mjs +497 -0
  150. package/src/project/log.mjs +329 -0
  151. package/src/project/match.mjs +112 -0
  152. package/src/project/records.mjs +380 -0
  153. package/src/project/tasks.mjs +153 -0
  154. package/src/report/evaluate.mjs +27 -0
  155. package/src/report/evaluators/a11y.mjs +206 -0
  156. package/src/report/evaluators/chart.mjs +151 -0
  157. package/src/report/evaluators/coherence.mjs +103 -0
  158. package/src/report/evaluators/color.mjs +86 -0
  159. package/src/report/evaluators/content.mjs +112 -0
  160. package/src/report/evaluators/extreme.mjs +53 -0
  161. package/src/report/evaluators/forms.mjs +116 -0
  162. package/src/report/evaluators/layout.mjs +94 -0
  163. package/src/report/evaluators/motion.mjs +273 -0
  164. package/src/report/evaluators/piece.mjs +69 -0
  165. package/src/report/evaluators/rhythm.mjs +99 -0
  166. package/src/report/evaluators/states.mjs +39 -0
  167. package/src/report/evaluators/style.mjs +35 -0
  168. package/src/report/evaluators/symbol.mjs +110 -0
  169. package/src/report/evaluators/terms.mjs +49 -0
  170. package/src/report/evaluators/type.mjs +163 -0
  171. package/src/report/evaluators/weight.mjs +51 -0
  172. package/src/report/evidence.mjs +4 -0
  173. package/src/report/finding.mjs +11 -0
  174. package/src/report/format.mjs +215 -0
  175. package/src/rules/hypotheses.mjs +28 -0
  176. package/src/rules/load.mjs +256 -0
  177. package/src/rules/public-text.mjs +56 -0
  178. package/src/rules/schema.mjs +212 -0
  179. package/templates/LAZULI.md +86 -0
@@ -0,0 +1,1496 @@
1
+ // Evaluated inside the page as a function expression: (opts, lookOf) => plain data. Plain script, no imports.
2
+ // The shared composition library (blocks, sections, coverage, body size) lives inside; opts.read picks
3
+ // the reader that turns it into plain data ("layout", "rhythm", "components", "forms", "actions", "piece",
4
+ // "motion" or "chart").
5
+ // opts.options true is the render-options reading: elements marked data-block are the option blocks. Without it
6
+ // the marks are ignored (a finished page measures as a page) and counted in the reader's marks.
7
+ // lookOf is the look.js function, injected as source by the caller:
8
+ // (${composition})(${JSON.stringify(opts)}, ${look}); only the components reader uses it.
9
+ // The forms reader (fields grouped by form) and the actions reader (every visible link, button and
10
+ // control) return plain data and never act on the page: no click, focus, input, change or submit.
11
+ // The motion reader (the animated elements the motion probe recorded, kept and in view, and the
12
+ // gradients on the screen) is read only too.
13
+ // No live function crosses back to Node. The one exception: the components reader with opts.elements
14
+ // true also returns the component elements, for CDP evaluation without returnByValue; page.evaluate
15
+ // callers (layout, rhythm) never set it.
16
+ // The piece reader (a derived piece at its canvas) reads the colors, image and symbol references of the
17
+ // elements the walk keeps, the html and body backgrounds, and the drawn shapes inside each inline svg (a use
18
+ // of an in-document symbol read with the paint its copy gets). Not read: pseudo-element colors (::before,
19
+ // ::after), colors inside images, canvas and filters, and paint that is not a color (a url() paint server,
20
+ // counted in a note).
21
+ // The content reader (buttons, links, headings and labels with their text as written, and alerts) is read
22
+ // only too. The seen reader returns the kept elements themselves (walk().seen less what offPage drops), for
23
+ // in-page callers only (extreme.js); Node never receives it.
24
+ // The chart reader lists the svg and canvas elements of chart size the walk keeps, with the shapes,
25
+ // texts and legend that paint in each svg; a canvas is a box and a name only (its pixels are never read here).
26
+ (opts, lookOf) => {
27
+ // Measurement tolerance, not a rule cutoff: two edges within this many px are one edge (the same
28
+ // 2 px the type measurer uses for one line).
29
+ const ALIGN_PX = 2;
30
+ // Coverage raster resolution, not a rule cutoff: areas are read on square cells of this many px.
31
+ const CELL_PX = 8;
32
+
33
+ // A letter or a digit: a numeral set large is a text block too.
34
+ const LETTER = /[\p{L}\p{N}]/u;
35
+ const SKIP = new Set(["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE", "HEAD", "TITLE", "META", "LINK", "IFRAME"]);
36
+ const MEDIA = new Set(["IMG", "VIDEO", "CANVAS", "svg"]);
37
+ const CONTROL = new Set(["BUTTON", "SELECT", "TEXTAREA", "INPUT"]);
38
+ const HIDDEN_CLIP = /^(rect\(0(px)?,? 0(px)?,? 0(px)?,? 0(px)?\)|inset\(\s*(?:(?:50|100)%\s*)+\))/;
39
+ const root = document.documentElement;
40
+ const body = document.body;
41
+
42
+ const selectorOf = (el) => {
43
+ const tag = el.tagName.toLowerCase();
44
+ if (el.id) return `${tag}#${CSS.escape(el.id)}`;
45
+ const first = (el.getAttribute("class") || "").split(/\s+/).find(Boolean);
46
+ if (first) return `${tag}.${CSS.escape(first)}`;
47
+ const block = el.getAttribute("data-block");
48
+ return block ? `${tag}[data-block="${block}"]` : tag;
49
+ };
50
+ // Page coordinates of a client rect.
51
+ const box = (r) => ({ x: r.left + scrollX, y: r.top + scrollY, w: r.width, h: r.height });
52
+ const pinned = (s) => s.position === "fixed" || s.position === "sticky";
53
+ // Visibility tolerance, not a rule cutoff: a clipping box this many px or less in both directions is a
54
+ // visually hidden box (the sr-only pattern).
55
+ const SR_ONLY_PX = 1;
56
+ // A subtree that paints nothing: display none, opacity 0, or a visually hidden box (sr-only, skip
57
+ // links). visibility: hidden is not pruned here: a descendant can set it back to visible and paint;
58
+ // shown() drops each hidden element on its own.
59
+ const hiddenTree = (el, s, r) => {
60
+ if (s.display === "none" || parseFloat(s.opacity) === 0) return true;
61
+ if (el === body) return false; // body's overflow propagates to the viewport; an app shell gives it no height
62
+ const clips = s.overflowX !== "visible" || s.overflowY !== "visible";
63
+ if (clips && r.width <= SR_ONLY_PX && r.height <= SR_ONLY_PX) return true;
64
+ if (s.clip !== "auto" && HIDDEN_CLIP.test(s.clip)) return true;
65
+ return s.clipPath !== "none" && HIDDEN_CLIP.test(s.clipPath);
66
+ };
67
+ const shown = (el) =>
68
+ typeof el.checkVisibility === "function" ? el.checkVisibility({ opacityProperty: true, visibilityProperty: true }) : true;
69
+ const textOf = (nodes) => nodes.map((n) => n.nodeValue).join(" ").replace(/\s+/g, " ").trim();
70
+ const rectsOf = (nodes) =>
71
+ nodes.flatMap((n) => {
72
+ const range = document.createRange();
73
+ range.selectNodeContents(n);
74
+ return [...range.getClientRects()].filter((x) => x.width > 0 && x.height > 0);
75
+ });
76
+ const union = (rects) => {
77
+ const left = Math.min(...rects.map((r) => r.left));
78
+ const top = Math.min(...rects.map((r) => r.top));
79
+ return { left, top, width: Math.max(...rects.map((r) => r.right)) - left, height: Math.max(...rects.map((r) => r.bottom)) - top };
80
+ };
81
+ const painted = (s) => {
82
+ const alpha = (c) => {
83
+ const m = /rgba?\(([^)]+)\)/.exec(c || "");
84
+ if (!m) return c && c !== "transparent" ? 1 : 0;
85
+ const parts = m[1].split(/[\s,/]+/).filter(Boolean);
86
+ return parts.length >= 4 ? parseFloat(parts[3]) : 1;
87
+ };
88
+ if (alpha(s.backgroundColor) > 0 || s.backgroundImage !== "none") return true;
89
+ return ["Top", "Right", "Bottom", "Left"].some(
90
+ (side) => parseFloat(s[`border${side}Width`]) > 0 && s[`border${side}Style`] !== "none" && alpha(s[`border${side}Color`]) > 0,
91
+ );
92
+ };
93
+
94
+ // Clip rects in client coordinates ({ left, top, right, bottom }); null means nothing clips.
95
+ const overlaps = (r, c) => !c || (Math.min(r.right, c.right) > Math.max(r.left, c.left) && Math.min(r.bottom, c.bottom) > Math.max(r.top, c.top));
96
+ // The clip a box passes to its children: the clip it inherits, narrowed on each axis it does not let overflow.
97
+ const narrow = (clip, s, r) => {
98
+ const cx = s.overflowX !== "visible";
99
+ const cy = s.overflowY !== "visible";
100
+ if (!cx && !cy) return clip;
101
+ const c = clip ?? { left: -Infinity, top: -Infinity, right: Infinity, bottom: Infinity };
102
+ return {
103
+ left: cx ? Math.max(c.left, r.left) : c.left,
104
+ right: cx ? Math.min(c.right, r.right) : c.right,
105
+ top: cy ? Math.max(c.top, r.top) : c.top,
106
+ bottom: cy ? Math.min(c.bottom, r.bottom) : c.bottom,
107
+ };
108
+ };
109
+
110
+ // ---- one walk of the page: blocks, option blocks, space blocks ----
111
+ // Fixed and sticky elements and their descendants are pruned, as are subtrees that paint nothing and
112
+ // subtrees an ancestor clips away entirely (a collapsed menu: height 0, overflow hidden).
113
+ // With opts.keepPinned (the components, forms and actions readers) fixed and sticky subtrees are
114
+ // walked like any other.
115
+ // The components, forms, actions and piece readers also collect every visible element in document order
116
+ // (found.seen) and every iframe that paints (found.frames; nothing inside a frame is read).
117
+ let walked = null;
118
+ const walk = () => {
119
+ if (walked) return walked;
120
+ const found = { blocks: [], options: [], spaces: [], pinnedContent: false, seen: [], frames: [] };
121
+ const collect = opts.read === "components" || opts.read === "forms" || opts.read === "actions" || opts.read === "piece" || opts.read === "motion" || opts.read === "content" || opts.read === "seen" || opts.read === "chart";
122
+ const visit = (el, clip) => {
123
+ if (SKIP.has(el.tagName)) {
124
+ if (collect && el.tagName === "IFRAME") {
125
+ const r = el.getBoundingClientRect();
126
+ if (r.width > 0 && r.height > 0 && overlaps(r, clip) && !hiddenTree(el, getComputedStyle(el), r) && shown(el)) found.frames.push(el);
127
+ }
128
+ return;
129
+ }
130
+ const s = getComputedStyle(el);
131
+ const r = el.getBoundingClientRect();
132
+ if (el !== body && pinned(s)) {
133
+ if (!opts.keepPinned) {
134
+ if (r.width > 0 && r.height > 0 && s.display !== "none") found.pinnedContent = true;
135
+ return;
136
+ }
137
+ // A fixed box escapes its ancestors' overflow clips (an ancestor transform is not checked);
138
+ // a sticky box stays inside them.
139
+ if (s.position === "fixed") clip = null;
140
+ }
141
+ if (hiddenTree(el, s, r)) return;
142
+ // body's overflow propagates to the viewport, so body never clips its children here.
143
+ const inner = el === body ? clip : narrow(clip, s, r);
144
+ // Clipped to nothing. With keepPinned the walk goes on, so a fixed descendant can still show;
145
+ // nothing else below is visible, since an empty clip overlaps no box.
146
+ if (inner && !(inner.right > inner.left && inner.bottom > inner.top) && !opts.keepPinned) return;
147
+ const visible = r.width > 0 && r.height > 0 && overlaps(r, clip) && shown(el);
148
+ if (collect && visible) found.seen.push(el);
149
+ const option = el.getAttribute("data-block");
150
+ if (option !== null && opts.options === true) {
151
+ if (visible) {
152
+ const kind = option.trim().toLowerCase();
153
+ const sized = kind === "title" || kind === "text";
154
+ const entry = {
155
+ el, selector: selectorOf(el), kind: "block", option: kind, ...box(r),
156
+ sizePx: sized ? parseFloat(s.fontSize) : null, chars: (el.textContent || "").replace(/\s+/g, " ").trim().length,
157
+ };
158
+ (kind === "space" ? found.spaces : found.options).push(entry);
159
+ }
160
+ return; // an option block is one block, whatever it holds
161
+ }
162
+ const tag = el.tagName;
163
+ if (MEDIA.has(tag) || (tag === "INPUT" && el.type === "image")) {
164
+ if (visible) found.blocks.push({ el, selector: selectorOf(el), kind: "media", ...box(r), sizePx: null, chars: 0 });
165
+ return; // nothing inside an image, a video, a canvas or an svg is another block
166
+ }
167
+ if (visible && ((CONTROL.has(tag) && !(tag === "INPUT" && el.type === "hidden")) || (tag === "A" && el.hasAttribute("href") && painted(s)))) {
168
+ found.blocks.push({ el, selector: selectorOf(el), kind: "control", ...box(r), sizePx: null, chars: 0 });
169
+ } else if (visible) {
170
+ const nodes = [...el.childNodes].filter((n) => n.nodeType === 3 && LETTER.test(n.nodeValue));
171
+ const rects = nodes.length ? rectsOf(nodes) : [];
172
+ const lines = rects.length ? union(rects) : null;
173
+ if (lines && overlaps({ ...lines, right: lines.left + lines.width, bottom: lines.top + lines.height }, clip)) {
174
+ found.blocks.push({
175
+ el, selector: selectorOf(el), kind: "text", ...box(lines),
176
+ sizePx: parseFloat(s.fontSize), chars: textOf(nodes).length,
177
+ });
178
+ }
179
+ }
180
+ for (const child of el.children) visit(child, inner);
181
+ };
182
+ if (body) visit(body, null);
183
+ walked = found;
184
+ return found;
185
+ };
186
+ const within = (scope) => (b) => !scope || scope === body || scope.contains(b.el);
187
+ const textBlocks = (scope) => walk().blocks.filter((b) => b.kind === "text").filter(within(scope));
188
+ const mediaBlocks = (scope) => walk().blocks.filter((b) => b.kind === "media").filter(within(scope));
189
+ const controlBlocks = (scope) => walk().blocks.filter((b) => b.kind === "control").filter(within(scope));
190
+ const optionBlocks = () => walk().options;
191
+ const isOptions = () => opts.options === true && (walk().options.length > 0 || walk().spaces.length > 0);
192
+ // The figure blocks of a scope: option blocks on an options page, else text, media and control blocks.
193
+ const blocksIn = (scope) => (isOptions() ? optionBlocks().filter(within(scope)) : walk().blocks.filter(within(scope)));
194
+
195
+ // Font size carrying the most characters. On an options page, the size of the text block with most characters.
196
+ const bodySize = () => {
197
+ if (isOptions()) {
198
+ const text = optionBlocks().filter((b) => b.option === "text").sort((a, b) => b.chars - a.chars)[0];
199
+ return text ? text.sizePx : null;
200
+ }
201
+ const chars = new Map();
202
+ for (const b of textBlocks()) chars.set(b.sizePx, (chars.get(b.sizePx) ?? 0) + b.chars);
203
+ let best = null;
204
+ for (const [size, n] of chars) {
205
+ if (best === null || n > best.n || (n === best.n && size < best.size)) best = { size, n };
206
+ }
207
+ return best ? best.size : null;
208
+ };
209
+
210
+ // ---- sections ----
211
+ // A child that paints nothing (hiddenTree: a skip link or a screen-reader-only span) is no section
212
+ // and does not stop the descent through single-child wrappers.
213
+ const visibleChildren = (el) =>
214
+ [...el.children].filter((c) => {
215
+ if (SKIP.has(c.tagName)) return false;
216
+ const s = getComputedStyle(c);
217
+ if (pinned(s) || s.display === "none") return false;
218
+ const r = c.getBoundingClientRect();
219
+ return r.width > 0 && r.height > 0 && !hiddenTree(c, s, r) && shown(c);
220
+ });
221
+ const sectionsOf = () => {
222
+ const marked = [...document.querySelectorAll("[data-section]")].filter((el) => {
223
+ for (let e = el; e && e !== body; e = e.parentElement) if (pinned(getComputedStyle(e))) return false;
224
+ const r = el.getBoundingClientRect();
225
+ return r.height > 0 && shown(el);
226
+ });
227
+ if (marked.length) return marked;
228
+ if (!body) return [];
229
+ let current = body;
230
+ let kids = visibleChildren(current);
231
+ while (kids.length === 1) {
232
+ current = kids[0];
233
+ kids = visibleChildren(current);
234
+ }
235
+ const tallest = kids.reduce((t, k) => (!t || k.getBoundingClientRect().height > t.getBoundingClientRect().height ? k : t), null);
236
+ if (tallest && tallest.tagName === "MAIN") {
237
+ const inner = visibleChildren(tallest);
238
+ if (inner.length >= 2) return kids.flatMap((k) => (k === tallest ? inner : [k]));
239
+ }
240
+ return kids;
241
+ };
242
+
243
+ // ---- coverage: share of area covered by the union of rects, on CELL_PX cells (a cell counts when its
244
+ // center lies inside a rect; partial edge cells weigh by their area) ----
245
+ const coverage = (rects, area) => {
246
+ if (!(area.w > 0 && area.h > 0)) return 0;
247
+ const cols = Math.ceil(area.w / CELL_PX);
248
+ const rows = Math.ceil(area.h / CELL_PX);
249
+ const hit = new Uint8Array(cols * rows);
250
+ // Cell i along one axis spans start + i * CELL_PX to the next cell or the end of the area.
251
+ const cell = (i, start, end) => {
252
+ const a = start + i * CELL_PX;
253
+ const b = Math.min(a + CELL_PX, end);
254
+ return { mid: (a + b) / 2, len: b - a };
255
+ };
256
+ for (const r of rects) {
257
+ const c0 = Math.max(0, Math.floor((r.x - area.x) / CELL_PX));
258
+ const c1 = Math.min(cols - 1, Math.floor((r.x + r.w - area.x) / CELL_PX));
259
+ const r0 = Math.max(0, Math.floor((r.y - area.y) / CELL_PX));
260
+ const r1 = Math.min(rows - 1, Math.floor((r.y + r.h - area.y) / CELL_PX));
261
+ for (let j = r0; j <= r1; j++) {
262
+ const my = cell(j, area.y, area.y + area.h).mid;
263
+ if (my < r.y || my >= r.y + r.h) continue;
264
+ for (let i = c0; i <= c1; i++) {
265
+ const mx = cell(i, area.x, area.x + area.w).mid;
266
+ if (mx >= r.x && mx < r.x + r.w) hit[j * cols + i] = 1;
267
+ }
268
+ }
269
+ }
270
+ let covered = 0;
271
+ for (let j = 0; j < rows; j++) {
272
+ const hy = cell(j, area.y, area.y + area.h).len;
273
+ for (let i = 0; i < cols; i++) if (hit[j * cols + i]) covered += hy * cell(i, area.x, area.x + area.w).len;
274
+ }
275
+ return covered / (area.w * area.h);
276
+ };
277
+
278
+ // The viewport's overflow on one axis: html's, or body's when html's is visible (CSS propagation).
279
+ const viewportOverflow = (axis) => {
280
+ const h = getComputedStyle(root);
281
+ const src = h.overflowX === "visible" && h.overflowY === "visible" && body ? getComputedStyle(body) : h;
282
+ return axis === "x" ? src.overflowX : src.overflowY;
283
+ };
284
+ const locked = (v) => v === "hidden" || v === "clip";
285
+
286
+ // ---- reader: layout (first view, sections, bleeds, crossings), raw numbers; Node rounds ----
287
+ const layout = ({ spaceCells }) => {
288
+ const w = root.clientWidth;
289
+ const h = root.clientHeight;
290
+ const scrolls = root.scrollHeight > h + ALIGN_PX && !locked(viewportOverflow("y"));
291
+ const sideways = root.scrollWidth > w + ALIGN_PX && !locked(viewportOverflow("x"));
292
+ const all = blocksIn(body);
293
+ const plain = (b) => ({ selector: b.selector, kind: b.kind, x: b.x, y: b.y, w: b.w, h: b.h, sizePx: b.sizePx });
294
+
295
+ // First view: blocks with area inside it; a block covering all of it is ground, not figure.
296
+ const inView = all.filter((b) => b.x < w && b.x + b.w > 0 && b.y < h && b.y + b.h > 0);
297
+ const ground = inView.filter((b) => b.x <= ALIGN_PX && b.y <= ALIGN_PX && b.x + b.w >= w - ALIGN_PX && b.y + b.h >= h - ALIGN_PX);
298
+ const figure = inView.filter((b) => !ground.includes(b));
299
+ const clipped = figure.map((b) => {
300
+ const x0 = Math.max(0, b.x), y0 = Math.max(0, b.y);
301
+ const x1 = Math.min(w, b.x + b.w), y1 = Math.min(h, b.y + b.h);
302
+ return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };
303
+ });
304
+ const emptyCells = [];
305
+ for (let row = 0; row < spaceCells; row++) {
306
+ for (let col = 0; col < spaceCells; col++) {
307
+ const area = { x: (col * w) / spaceCells, y: (row * h) / spaceCells, w: w / spaceCells, h: h / spaceCells };
308
+ emptyCells.push(1 - coverage(clipped, area));
309
+ }
310
+ }
311
+
312
+ // Sections: their edges are the min left and max right of their blocks.
313
+ let elements = sectionsOf();
314
+ const noSections = elements.length === 0;
315
+ const synthetic = noSections || !scrolls;
316
+ if (synthetic) elements = [body];
317
+ const sections = elements.map((el) => {
318
+ const r = el === body ? { left: 0, top: 0, width: w, height: root.scrollHeight } : el.getBoundingClientRect();
319
+ const mine = all.filter(within(el));
320
+ const left = mine.length ? Math.min(...mine.map((b) => b.x)) : null;
321
+ const right = mine.length ? Math.max(...mine.map((b) => b.x + b.w)) : null;
322
+ return {
323
+ selector: el === body ? "body" : selectorOf(el),
324
+ top: el === body ? 0 : r.top + scrollY,
325
+ height: r.height,
326
+ left,
327
+ right,
328
+ centered: left !== null && Math.abs(left - (w - right)) <= ALIGN_PX,
329
+ textOnly: mine.length > 0 && mine.every((b) => b.kind === "text"),
330
+ };
331
+ });
332
+ const edged = sections.filter((s) => s.left !== null);
333
+ const uniformGrid =
334
+ edged.length >= 2 && edged.every((s) => s.centered) && Math.max(...edged.map((s) => s.left)) - Math.min(...edged.map((s) => s.left)) <= ALIGN_PX;
335
+
336
+ // Bleeds: partly in view sideways and past the left or right edge, on a page that does not scroll sideways.
337
+ const bleeds = sideways ? [] : all.filter((b) => b.x + b.w > 0 && b.x < w && (b.x < -ALIGN_PX || b.x + b.w > w + ALIGN_PX));
338
+ // Crossings: media whose box runs over the boundary between two consecutive sections.
339
+ const bounds = sections.slice(1).map((s) => s.top);
340
+ const crossings = all.filter((b) => b.kind === "media" && bounds.some((y) => b.y < y - ALIGN_PX && b.y + b.h > y + ALIGN_PX));
341
+
342
+ return {
343
+ viewport: { w, h },
344
+ scrolls,
345
+ sideways,
346
+ scrollWidth: root.scrollWidth,
347
+ bodyPx: bodySize(),
348
+ blocks: figure.map(plain),
349
+ clipped,
350
+ ground: ground.map((b) => b.selector),
351
+ spaces: walk().spaces.map((b) => b.selector),
352
+ emptyCells,
353
+ emptyShare: 1 - coverage(clipped, { x: 0, y: 0, w, h }),
354
+ sections,
355
+ noSections,
356
+ pinnedContent: walk().pinnedContent,
357
+ uniformGrid,
358
+ bleeds: bleeds.map((b) => b.selector),
359
+ crossings: crossings.map((b) => b.selector),
360
+ };
361
+ };
362
+
363
+ // ---- reader: rhythm (sections and viewport steps down the page, to capPx), raw numbers; Node rounds ----
364
+ const rhythm = ({ capPx }) => {
365
+ const w = root.clientWidth;
366
+ const h = root.clientHeight;
367
+ const pageH = root.scrollHeight;
368
+ const scrolls = pageH > h + ALIGN_PX && !locked(viewportOverflow("y"));
369
+ const measured = Math.min(pageH, capPx);
370
+ const all = blocksIn(body);
371
+ const largest = (list) => {
372
+ const sizes = list.filter((b) => b.sizePx !== null).map((b) => b.sizePx);
373
+ return sizes.length ? Math.max(...sizes) : null;
374
+ };
375
+
376
+ // The same synthetic step as the layout reader: no sections, or no scroll, gives one body section.
377
+ let elements = sectionsOf();
378
+ const noSections = elements.length === 0;
379
+ if (noSections || !scrolls) elements = [body];
380
+ const sections = [];
381
+ let dropped = 0;
382
+ for (const el of elements) {
383
+ const r = el === body ? { left: 0, top: 0, width: w, height: pageH } : el.getBoundingClientRect();
384
+ const top = el === body ? 0 : r.top + scrollY;
385
+ if (top >= measured) {
386
+ dropped += 1; // starts below the cap: not read
387
+ continue;
388
+ }
389
+ const mine = all.filter(within(el));
390
+ const area = { x: el === body ? 0 : r.left + scrollX, y: top, w: r.width, h: Math.min(top + r.height, measured) - top };
391
+ // densityStep: the share of one row of coverage cells in this section, the resolution of its density.
392
+ const densityStep = area.h > 0 ? CELL_PX / area.h : null;
393
+ sections.push({ selector: el === body ? "body" : selectorOf(el), top, height: r.height, density: coverage(mine, area), densityStep, maxPx: largest(mine) });
394
+ }
395
+
396
+ // Viewport steps: consecutive slices of the viewport height from the top to the cap.
397
+ const steps = [];
398
+ if (h > 0) {
399
+ for (let top = 0; top < measured; top += h) {
400
+ const area = { x: 0, y: top, w, h: Math.min(h, measured - top) };
401
+ const inStep = all.filter((b) => b.y < area.y + area.h && b.y + b.h > area.y);
402
+ steps.push({ top, density: coverage(inStep, area), maxPx: largest(inStep) });
403
+ }
404
+ }
405
+
406
+ return {
407
+ viewportPx: h,
408
+ pageHeightPx: pageH,
409
+ measuredPx: measured,
410
+ scrolls,
411
+ noSections,
412
+ pinnedContent: walk().pinnedContent,
413
+ bodyPx: bodySize(),
414
+ sections,
415
+ dropped,
416
+ steps,
417
+ };
418
+ };
419
+
420
+ // ---- reader: components (kinds, identity signatures, looks, state markers) ----
421
+ // Identity is kind plus accessible text, never class names; a data-component name replaces it.
422
+ const BUTTON_INPUT = new Set(["button", "submit", "reset"]);
423
+ const NOT_FIELD = new Set(["hidden", "button", "submit", "reset", "image", "checkbox", "radio", "range", "color", "file"]);
424
+ const collapse = (t) => (t || "").replace(/\s+/g, " ").trim();
425
+ const roleOf = (el) => collapse(el.getAttribute("role")).toLowerCase().split(" ")[0];
426
+ // The control or heading kind; an element with data-component that is neither is a component; else null.
427
+ // data-component on a control or heading changes only its signature (the name it is matched by across
428
+ // screens), never its kind.
429
+ const kindOf = (el) => {
430
+ const tag = el.tagName;
431
+ if (/^H[1-6]$/.test(tag)) return "heading";
432
+ if (tag === "BUTTON" || (tag === "INPUT" && BUTTON_INPUT.has(el.type)) || roleOf(el) === "button") return "button";
433
+ if (tag === "A" && el.hasAttribute("href")) return painted(getComputedStyle(el)) ? "button" : "link";
434
+ if (tag === "TEXTAREA" || tag === "SELECT" || (tag === "INPUT" && !NOT_FIELD.has(el.type))) return "field";
435
+ return el.hasAttribute("data-component") ? "component" : null;
436
+ };
437
+ // A descendant of el that paints: shown, not a hidden or clipped subtree (sr-only, clip), and not
438
+ // inside a box between it and el that clips to zero size.
439
+ const paintsWithin = (node, el) => {
440
+ if (!shown(node)) return false;
441
+ for (let e = node; e && e !== el; e = e.parentElement) {
442
+ const s = getComputedStyle(e);
443
+ const r = e.getBoundingClientRect();
444
+ if (hiddenTree(e, s, r)) return false;
445
+ if ((s.overflowX !== "visible" || s.overflowY !== "visible") && !(r.width > 0 && r.height > 0)) return false;
446
+ }
447
+ return true;
448
+ };
449
+ // The control's visible text: text nodes whose parent paints, in document order. With skipFields, text
450
+ // inside a select or a textarea (a label wrapping its field) is left out.
451
+ const visibleText = (el, skipFields = false) => {
452
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
453
+ let text = "";
454
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
455
+ if (skipFields && n.parentElement?.closest("select, textarea")) continue;
456
+ if (n.parentElement && !SKIP.has(n.parentElement.tagName) && paintsWithin(n.parentElement, el)) text += n.nodeValue;
457
+ }
458
+ return collapse(text);
459
+ };
460
+ // The elements named by an id-list attribute (aria-labelledby, aria-describedby), in order; missing ids skipped.
461
+ const idRefs = (el, attr) => collapse(el.getAttribute(attr)).split(" ").filter(Boolean).map((id) => document.getElementById(id)).filter(Boolean);
462
+ // The first two steps of the accessible name: aria-labelledby (text of the referenced elements), else
463
+ // aria-label. { name, from }, name "" and from "" when neither gives one.
464
+ const ariaName = (el) => {
465
+ const labelled = collapse(idRefs(el, "aria-labelledby").map((ref) => ref.textContent || "").join(" "));
466
+ if (labelled) return { name: labelled, from: "labelledby" };
467
+ const aria = collapse(el.getAttribute("aria-label"));
468
+ if (aria) return { name: aria, from: "aria-label" };
469
+ return { name: "", from: "" };
470
+ };
471
+ // A simplified accessible name for buttons and links: aria-labelledby (text of the referenced
472
+ // elements), else aria-label, else visible text, else an input button's value (a submit with none
473
+ // reads "Submit"), else the alt of an img inside, else title.
474
+ const controlName = (el) => {
475
+ const named = ariaName(el).name;
476
+ if (named) return named;
477
+ const text = visibleText(el);
478
+ if (text) return text;
479
+ if (el.tagName === "INPUT" && BUTTON_INPUT.has(el.type)) {
480
+ const value = collapse(el.value);
481
+ if (value) return value;
482
+ if (el.type === "submit") return "Submit";
483
+ }
484
+ const alt = collapse([...el.querySelectorAll("img[alt]")].filter((img) => paintsWithin(img, el)).map((img) => img.getAttribute("alt")).join(" "));
485
+ if (alt) return alt;
486
+ return collapse(el.getAttribute("title"));
487
+ };
488
+ // The name in the page's own capitalization, whitespace collapsed (the label); the signature lowercases
489
+ // it for buttons and links.
490
+ const nameOf = (el, kind) => {
491
+ if (kind === "component") return collapse(el.getAttribute("data-component"));
492
+ if (kind === "heading") return collapse(el.textContent);
493
+ if (kind === "field") return collapse(el.getAttribute("name")) || collapse(el.id) || collapse(el.getAttribute("placeholder"));
494
+ return controlName(el);
495
+ };
496
+ const componentName = (el) => (el.hasAttribute("data-component") ? collapse(el.getAttribute("data-component")) : "");
497
+ const signatureOf = (el, kind, name) => {
498
+ const component = componentName(el);
499
+ if (component) return `component:${component}`;
500
+ if (kind === "component") return `component:${name}`;
501
+ if (kind === "heading") return el.tagName.toLowerCase();
502
+ if (kind === "field") return `field:${el.tagName === "INPUT" ? el.type : el.tagName.toLowerCase()}:${name}`;
503
+ return `${kind}:${name.toLowerCase()}`;
504
+ };
505
+ const isDisabled = (el) => el.matches(":disabled") || el.getAttribute("aria-disabled") === "true";
506
+ // The current page in a nav is a state, not another look. A current marker made only with a class is not seen.
507
+ const isCurrent = (el) => {
508
+ const current = el.getAttribute("aria-current");
509
+ return (current !== null && current !== "false") || el.getAttribute("aria-selected") === "true" || el.getAttribute("aria-pressed") === "true";
510
+ };
511
+ const plural = (n, one, many) => (n === 1 ? one : many);
512
+ // A box entirely before the document origin (a skip link at left -9999px, a drawer moved off the
513
+ // page) or entirely past its right edge (a closed off-canvas drawer) is not shown to anyone
514
+ // scrolling the page: the components, forms and actions readers do not count it.
515
+ const offPage = (el) => {
516
+ const r = el.getBoundingClientRect();
517
+ return r.right + scrollX <= 0 || r.bottom + scrollY <= 0 || r.left + scrollX >= root.scrollWidth;
518
+ };
519
+
520
+ const components = ({ props, elements }) => {
521
+ const notes = [];
522
+ const present = { disabled: 0, invalid: 0, busy: 0, alert: 0, status: 0, progressbar: 0 };
523
+ const list = [];
524
+ const els = [];
525
+ let outside = 0;
526
+ for (const el of walk().seen) {
527
+ const kind = kindOf(el);
528
+ const role = roleOf(el);
529
+ const marks = {
530
+ disabled: kind !== null && kind !== "heading" && isDisabled(el),
531
+ invalid: el.getAttribute("aria-invalid") === "true",
532
+ busy: el.getAttribute("aria-busy") === "true",
533
+ alert: role === "alert",
534
+ status: role === "status" || el.tagName === "OUTPUT",
535
+ progressbar: role === "progressbar" || el.tagName === "PROGRESS",
536
+ };
537
+ const marked = Object.values(marks).some(Boolean);
538
+ if (kind === null && !marked) continue;
539
+ if (offPage(el)) {
540
+ outside += 1;
541
+ continue;
542
+ }
543
+ for (const key of Object.keys(present)) if (marks[key]) present[key] += 1;
544
+ if (kind === null) continue;
545
+ const name = nameOf(el, kind);
546
+ list.push({
547
+ kind,
548
+ signature: signatureOf(el, kind, name),
549
+ // A data-component name is enough to match an element across screens.
550
+ named: name !== "" || componentName(el) !== "",
551
+ label: name,
552
+ selector: selectorOf(el),
553
+ disabled: isDisabled(el),
554
+ invalid: marks.invalid,
555
+ current: isCurrent(el),
556
+ look: lookOf ? lookOf(el, props, false) : null,
557
+ });
558
+ els.push(el);
559
+ }
560
+ if (outside) {
561
+ notes.push(`${outside} ${plural(outside, "element placed outside the page (before its top or left edge, or past its right edge) was not counted.", "elements placed outside the page (before its top or left edge, or past its right edge) were not counted.")}`);
562
+ }
563
+ // The limit lives in look.js; a look read with parts stops at it. Counted on controls, whose looks
564
+ // are read with parts.
565
+ if (lookOf && Number.isFinite(lookOf.descendants)) {
566
+ const limit = lookOf.descendants;
567
+ const over = els
568
+ .filter((el, i) => list[i].kind !== "heading" && list[i].kind !== "component")
569
+ .map((el) => el.querySelectorAll("*").length)
570
+ .filter((n) => n > limit);
571
+ if (over.length) {
572
+ notes.push(`${over.length} ${plural(over.length, "control has", "controls have")} more than ${limit} descendant elements (up to ${Math.max(...over)}); a look with parts reads the first ${limit}.`);
573
+ }
574
+ }
575
+ return elements ? { components: list, present, notes, elements: els } : { components: list, present, notes };
576
+ };
577
+
578
+ // ---- field names and the form control set (forms and actions readers) ----
579
+ // Definitions, not cutoffs: fixed before any site was read and never edited after a site reading. Words match whole
580
+ // tokens of a name, id or label, lowercased and split on every character that is not a letter or a
581
+ // digit; a word with a hyphen (e-mail) matches that run of tokens. "*" is no token: it matches as a
582
+ // character anywhere in the visible label (an aria-hidden star included).
583
+ const REQUIRED_MARKS = ["*", "required", "obrigatorio", "obrigatório"];
584
+ const OPTIONAL_MARKS = ["optional", "opcional"];
585
+ // Checked in this order; the first purpose with a matching word wins.
586
+ const PURPOSE_WORDS = [
587
+ ["organization", ["company", "empresa"]],
588
+ ["email", ["email", "e-mail"]],
589
+ ["tel", ["phone", "tel", "telefone", "celular", "whatsapp", "mobile"]],
590
+ ["postal-code", ["cep", "zip", "postal"]],
591
+ ["street-address", ["address", "endereco", "endereço", "rua"]],
592
+ ["address-level2", ["city", "cidade"]],
593
+ ["bday", ["birthday", "nascimento"]],
594
+ ["name", ["name", "nome"]],
595
+ ];
596
+ const NUMERIC_WORDS = ["cpf", "cnpj", "cep", "zip", "number", "numero", "número", "code", "codigo", "código", "quantity", "quantidade"];
597
+ const tokensOf = (text) => (text || "").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
598
+ const hasWord = (tokens, word) => {
599
+ const run = tokensOf(word);
600
+ for (let i = 0; i + run.length <= tokens.length; i++) if (run.every((t, j) => tokens[i + j] === t)) return true;
601
+ return false;
602
+ };
603
+ // sources: token lists, one per source (name, id, label), so a run never crosses two sources.
604
+ const anyWord = (sources, words) => sources.some((tokens) => words.some((w) => hasWord(tokens, w)));
605
+ const markOf = (text) => {
606
+ const tokens = [tokensOf(text)];
607
+ if (text.includes("*") || anyWord(tokens, REQUIRED_MARKS.filter((w) => w !== "*"))) return "required";
608
+ return anyWord(tokens, OPTIONAL_MARKS) ? "optional" : null;
609
+ };
610
+
611
+ // Form controls: every input that takes a value (checkbox, radio, file, range and color included), select, textarea.
612
+ const FORM_SKIP = new Set(["hidden", "button", "submit", "reset", "image"]);
613
+ const isField = (el) => el.tagName === "SELECT" || el.tagName === "TEXTAREA" || (el.tagName === "INPUT" && !FORM_SKIP.has(el.type));
614
+ // An element a person sees: it and every ancestor up to body paint (not sr-only, not clipped to zero
615
+ // size), and it is not placed outside the page. Text is read from such elements only.
616
+ const paints = (el) => paintsWithin(el, body) && !offPage(el);
617
+ const shownText = (els) => collapse(els.filter(paints).map((e) => visibleText(e, true)).join(" "));
618
+ // A field's name in the shipped order (aria-labelledby, aria-label, the text of its labels, title,
619
+ // placeholder) and whether a person sees a label: a label that paints with text, or aria-labelledby
620
+ // elements that all paint with text, whichever source gave the name. labelText is that seen text.
621
+ const fieldName = (el) => {
622
+ const labels = [...(el.labels || [])];
623
+ const seenLabel = labels.filter(paints).map((l) => visibleText(l, true)).find(Boolean) || "";
624
+ const refs = idRefs(el, "aria-labelledby");
625
+ const refsSeen = refs.length > 0 && refs.every((r) => paints(r) && visibleText(r, true) !== "");
626
+ const labelText = seenLabel || (refsSeen ? shownText(refs) : "");
627
+ const result = (name, from) => ({ name, from, visible: labelText !== "", labelText });
628
+ const aria = ariaName(el);
629
+ if (aria.name) return result(aria.name, aria.from);
630
+ const label = collapse(labels.map((l) => visibleText(l, true)).join(" "));
631
+ if (label) return result(label, "label");
632
+ const title = collapse(el.getAttribute("title"));
633
+ if (title) return result(title, "title");
634
+ const placeholder = collapse(el.getAttribute("placeholder"));
635
+ return placeholder ? result(placeholder, "placeholder") : result("", "");
636
+ };
637
+ const disabledNote = (n) => `${n} disabled ${plural(n, "control was", "controls were")} left out.`;
638
+ const framesNote = (rest) => {
639
+ const n = walk().frames.filter((f) => !offPage(f)).length;
640
+ return n ? [`${n} ${plural(n, "embedded frame (iframe) was not read;", "embedded frames (iframe) were not read;")} ${rest}`] : [];
641
+ };
642
+ // A form's named controls shadow its properties (an input named "id" is form.id): read it through Element.prototype.
643
+ const formAttr = (form, name) => Element.prototype.getAttribute.call(form, name);
644
+ const formSelector = (form) => selectorOf({ tagName: "FORM", id: formAttr(form, "id") || "", getAttribute: (name) => formAttr(form, name) });
645
+ const docOrder = (a, b) => (Node.prototype.compareDocumentPosition.call(a, b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1);
646
+
647
+ // Custom controls (a narrow exception to "never count hidden content"): a checkbox,
648
+ // radio or file input hidden only by its own style (opacity 0, a visually hidden clip, zero size), not
649
+ // display none or visibility hidden, whose parent paints, counts when one of its labels paints with
650
+ // text (a Bootstrap custom checkbox, an sr-only peer toggle, a styled file upload): that label is the
651
+ // control a person sees, and its box is the control's box.
652
+ const CUSTOM_TYPES = new Set(["checkbox", "radio", "file"]);
653
+ let reached = null;
654
+ // The elements the forms and actions readers go through, in document order: walk().seen plus the
655
+ // custom controls; faceOf maps each custom control to its painting label.
656
+ const reachable = () => {
657
+ if (reached) return reached;
658
+ const seen = new Set(walk().seen);
659
+ const faceOf = new Map();
660
+ for (const el of document.querySelectorAll("input")) {
661
+ if (!CUSTOM_TYPES.has(el.type) || seen.has(el)) continue;
662
+ const s = getComputedStyle(el);
663
+ if (s.display === "none" || s.visibility === "hidden") continue;
664
+ const r = el.getBoundingClientRect();
665
+ const ownHidden = parseFloat(s.opacity) === 0 || hiddenTree(el, s, r) || !(r.width > 0 && r.height > 0);
666
+ if (!ownHidden || !el.parentElement || !paints(el.parentElement)) continue;
667
+ const face = [...el.labels].find((l) => paints(l) && visibleText(l, true) !== "");
668
+ if (face) faceOf.set(el, face);
669
+ }
670
+ reached = { list: faceOf.size ? [...walk().seen, ...faceOf.keys()].sort(docOrder) : walk().seen, faceOf };
671
+ return reached;
672
+ };
673
+ // Off the page: a custom control is placed where its label is, and its label already paints.
674
+ const outside = (el) => !reachable().faceOf.has(el) && offPage(el);
675
+ const customNote = (n) => `${n} ${plural(n, "custom control read through its visible label.", "custom controls read through their visible label.")}`;
676
+
677
+ const fieldOf = (el) => {
678
+ const n = fieldName(el);
679
+ const sources = [el.getAttribute("name"), el.id, n.name].map(tokensOf);
680
+ const type = el.type;
681
+ const choice = type === "radio" || type === "checkbox";
682
+ return {
683
+ selector: selectorOf(el),
684
+ tag: el.tagName.toLowerCase(),
685
+ type,
686
+ name: n.name,
687
+ nameFrom: n.from,
688
+ visibleLabel: n.visible,
689
+ labelText: n.labelText,
690
+ required: el.hasAttribute("required") || el.getAttribute("aria-required") === "true",
691
+ marked: markOf(n.labelText),
692
+ autocomplete: collapse(el.getAttribute("autocomplete")).toLowerCase(),
693
+ inputmode: collapse(el.getAttribute("inputmode")).toLowerCase(),
694
+ purpose: type === "email" || type === "tel" ? type : PURPOSE_WORDS.find(([, words]) => anyWord(sources, words))?.[0] ?? null,
695
+ numeric: anyWord(sources, NUMERIC_WORDS),
696
+ invalid: el.getAttribute("aria-invalid") === "true",
697
+ errorText: shownText(idRefs(el, "aria-errormessage")) || shownText(idRefs(el, "aria-describedby")) || null,
698
+ group: choice ? collapse(el.getAttribute("name")) || null : null,
699
+ custom: reachable().faceOf.has(el),
700
+ };
701
+ };
702
+ // Questions a person answers: each field once, the radios or checkboxes of one group once.
703
+ const questionsOf = (fields) => {
704
+ const groups = new Set();
705
+ let n = 0;
706
+ for (const f of fields) {
707
+ if (f.group !== null) {
708
+ if (groups.has(f.group)) continue;
709
+ groups.add(f.group);
710
+ }
711
+ n += 1;
712
+ }
713
+ return n;
714
+ };
715
+
716
+ // ---- reader: forms (visible fields grouped by their form, read only) ----
717
+ // owners: the form elements in report order; the actions reader indexes into it.
718
+ let formsRead = null;
719
+ const readForms = () => {
720
+ if (formsRead) return formsRead;
721
+ const groups = new Map();
722
+ let disabled = 0;
723
+ for (const el of reachable().list) {
724
+ if (!isField(el) || outside(el)) continue;
725
+ if (isDisabled(el)) {
726
+ disabled += 1;
727
+ continue;
728
+ }
729
+ const owner = el.form || null;
730
+ if (!groups.has(owner)) groups.set(owner, []);
731
+ groups.get(owner).push(fieldOf(el));
732
+ }
733
+ const owners = [...groups.keys()].filter(Boolean).sort(docOrder);
734
+ const list = owners.map((form) => ({ selector: formSelector(form), fields: groups.get(form), questions: questionsOf(groups.get(form)) }));
735
+ if (groups.has(null)) list.push({ selector: "(fields outside a form)", fields: groups.get(null), questions: questionsOf(groups.get(null)) });
736
+ const all = list.flatMap((f) => f.fields);
737
+ const notes = framesNote("a form inside one is not counted.");
738
+ if (disabled) notes.push(disabledNote(disabled));
739
+ const custom = all.filter((f) => f.custom).length;
740
+ if (custom) notes.push(customNote(custom));
741
+ formsRead ={ owners, report: { forms: list, fields: all.length, unnamed: all.filter((f) => f.name === "").length, notes } };
742
+ return formsRead;
743
+ };
744
+ const forms = () => readForms().report;
745
+
746
+ // ---- reader: actions (every visible link, button and control in document order, read only) ----
747
+ const ACTION_ROLES = new Set(["tab", "menuitem", "switch", "checkbox", "radio", "combobox"]);
748
+ // A link whenever it has an href, whatever it paints or its role. Image-map links (area[href]) are
749
+ // not read: an area has no box of its own, so the walk never sees it.
750
+ const actionKind = (el) => {
751
+ const tag = el.tagName;
752
+ if (tag === "A" && el.hasAttribute("href")) return "link";
753
+ if (tag === "BUTTON" || (tag === "INPUT" && (BUTTON_INPUT.has(el.type) || el.type === "image")) || roleOf(el) === "button") return "button";
754
+ if (isField(el)) return el.type === "checkbox" || el.type === "radio" ? "choice" : tag === "SELECT" ? "select" : "field";
755
+ return tag === "SUMMARY" || ACTION_ROLES.has(roleOf(el)) ? "other" : null;
756
+ };
757
+ const submitsForm = (el) =>
758
+ !!el.form && ((el.tagName === "BUTTON" && el.type === "submit") || (el.tagName === "INPUT" && (el.type === "submit" || el.type === "image")));
759
+ // Where the control's form posts, absolute: a submitter's own formaction; for any other control, the
760
+ // formaction of the form's default button (its first submitter, which Enter in a field uses); else the
761
+ // form's action (none means the page itself). Null outside a form.
762
+ const formActionOf = (el) => {
763
+ if (!el.form) return null;
764
+ // Searched by form owner in document order: form.elements leaves out image buttons.
765
+ const by = submitsForm(el) ? el : [...document.querySelectorAll("button, input")].find((c) => c.form === el.form && submitsForm(c));
766
+ const own = by && by.hasAttribute("formaction") ? by.getAttribute("formaction") : null;
767
+ try {
768
+ return new URL(own ?? formAttr(el.form, "action") ?? "", document.baseURI).href;
769
+ } catch {
770
+ return null;
771
+ }
772
+ };
773
+ // A disclosure-type control (summary, aria-expanded, aria-controls, aria-haspopup other than false, role
774
+ // tab): the only kind the motion recorder may click, and only on a local page.
775
+ const isDisclosure = (el) =>
776
+ el.tagName === "SUMMARY" ||
777
+ el.hasAttribute("aria-expanded") ||
778
+ el.hasAttribute("aria-controls") ||
779
+ (el.hasAttribute("aria-haspopup") && el.getAttribute("aria-haspopup") !== "false") ||
780
+ roleOf(el) === "tab";
781
+ // With opts.disclosure (the motion recorder) each action also carries disclosure; map-page never sets it.
782
+ const actions = (o = {}) => {
783
+ const { owners } = readForms();
784
+ const w = root.clientWidth;
785
+ const h = root.clientHeight;
786
+ const list = [];
787
+ let disabled = 0;
788
+ let custom = 0;
789
+ const { list: reached, faceOf } = reachable();
790
+ for (const el of reached) {
791
+ const kind = actionKind(el);
792
+ if (kind === null || outside(el)) continue;
793
+ if (isDisabled(el)) {
794
+ disabled += 1;
795
+ continue;
796
+ }
797
+ const field = kind === "field" || kind === "choice" || kind === "select";
798
+ // An image button is named by its alt when nothing before it names it.
799
+ const name = field ? fieldName(el).name : controlName(el) || (el.tagName === "INPUT" && el.type === "image" ? collapse(el.getAttribute("alt")) : "");
800
+ if (faceOf.has(el)) custom += 1;
801
+ const b = box((faceOf.get(el) ?? el).getBoundingClientRect());
802
+ const index = el.form ? owners.indexOf(el.form) : -1;
803
+ list.push({
804
+ kind,
805
+ name,
806
+ selector: selectorOf(el),
807
+ box: b,
808
+ firstView: b.x < w && b.x + b.w > 0 && b.y < h && b.y + b.h > 0,
809
+ href: kind === "link" ? el.href : null,
810
+ form: index === -1 ? null : index,
811
+ submits: submitsForm(el),
812
+ formAction: formActionOf(el),
813
+ ...(o.disclosure ? { disclosure: isDisclosure(el) } : {}),
814
+ });
815
+ }
816
+ const notes = framesNote("a link or control inside one is not mapped.");
817
+ if (disabled) notes.push(disabledNote(disabled));
818
+ if (custom) notes.push(customNote(custom));
819
+ return { actions: list, notes };
820
+ };
821
+
822
+ // ---- svg paint and color helpers (piece and chart readers) ----
823
+ // Inside these an SVG holds shapes that are only referenced, never drawn where they stand.
824
+ const SVG_UNDRAWN = "defs, clipPath, mask, symbol, pattern, marker, linearGradient, radialGradient";
825
+ // The fill and stroke a shape paints (computed values), null when that paint draws nothing.
826
+ const svgPaints = (s) => ({
827
+ fill: s.fill !== "none" && parseFloat(s.fillOpacity) > 0 ? s.fill : null,
828
+ stroke: s.stroke !== "none" && parseFloat(s.strokeOpacity) > 0 && parseFloat(s.strokeWidth) > 0 ? s.stroke : null,
829
+ });
830
+ // A color in another syntax (oklch(), lab(), color(), color-mix()) is converted by the browser: painted on
831
+ // a 1 px sRGB canvas of our own (never a page canvas) and read back ({ r, g, b, a } in 0 to 255;
832
+ // out-of-gamut colors are mapped into sRGB, and the channels of a partly transparent color may round).
833
+ // null when it is not a color.
834
+ let pixel = null;
835
+ const throughCanvas = (v) => {
836
+ if (!CSS.supports("color", v)) return null;
837
+ pixel ??= document.createElement("canvas").getContext("2d", { willReadFrequently: true });
838
+ pixel.clearRect(0, 0, 1, 1);
839
+ pixel.fillStyle = v;
840
+ pixel.fillRect(0, 0, 1, 1);
841
+ const [r, g, b, a] = pixel.getImageData(0, 0, 1, 1).data;
842
+ return { r, g, b, a };
843
+ };
844
+ // [r, g, b] in 0 to 255 as lowercase #rrggbb.
845
+ const hexOf = (rgb) => `#${rgb.map((x) => Math.round(Math.min(255, Math.max(0, x))).toString(16).padStart(2, "0")).join("")}`;
846
+
847
+ // ---- reader: piece (colors, symbol references and images of a derived piece at its canvas, read only) ----
848
+ // Display limit, not a rule cutoff: selectors kept per color.
849
+ const MAX_WHERE = 3;
850
+ const SVG_SHAPES = new Set(["path", "rect", "circle", "ellipse", "line", "polyline", "polygon", "text", "tspan", "textPath"]);
851
+ // A color function in a computed gradient, with one level of nested parentheses (calc() inside oklch(),
852
+ // oklch() inside color-mix()). Computed gradients write keywords and hex as rgb().
853
+ const GRADIENT_STOP = /\b(?:color-mix|rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\((?:[^()]|\([^()]*\))*\)/g;
854
+ const piece = () => {
855
+ const colors = new Map();
856
+ const symbolRefs = [];
857
+ let images = 0;
858
+ let unread = 0;
859
+ const where = (el) => (el === root ? "html" : selectorOf(el));
860
+ // A computed color as lowercase #rrggbb (alpha dropped); a fully transparent one is skipped; a value the
861
+ // browser cannot read as a color (a url() paint server) is counted as unread.
862
+ const add = (value, el) => {
863
+ const v = (value || "").trim();
864
+ if (v === "" || v === "none") return;
865
+ const m = /^rgba?\(([^)]+)\)$/.exec(v);
866
+ let rgb;
867
+ if (m) {
868
+ const p = m[1].split(/[\s,/]+/).filter(Boolean);
869
+ const alpha = p.length >= 4 ? (p[3].endsWith("%") ? parseFloat(p[3]) / 100 : parseFloat(p[3])) : 1;
870
+ if (!(alpha > 0)) return;
871
+ rgb = p.slice(0, 3).map(parseFloat);
872
+ } else {
873
+ const c = throughCanvas(v);
874
+ if (!c) {
875
+ unread += 1;
876
+ return;
877
+ }
878
+ if (c.a === 0) return;
879
+ rgb = [c.r, c.g, c.b];
880
+ }
881
+ const hex = hexOf(rgb);
882
+ const list = colors.get(hex) ?? [];
883
+ const sel = where(el);
884
+ if (!list.includes(sel) && list.length < MAX_WHERE) list.push(sel);
885
+ colors.set(hex, list);
886
+ };
887
+ const ref = (url, el) => {
888
+ if (!url) return;
889
+ let abs;
890
+ try {
891
+ abs = new URL(url, document.baseURI);
892
+ } catch {
893
+ return;
894
+ }
895
+ abs.hash = "";
896
+ const r = el.getBoundingClientRect();
897
+ symbolRefs.push({ url: abs.href, selector: where(el), px: Math.max(r.width, r.height) });
898
+ };
899
+ const hrefOf = (el) => el.getAttribute("href") ?? el.getAttributeNS("http://www.w3.org/1999/xlink", "href");
900
+ const readBox = (el, s) => {
901
+ if (el !== root && [...el.childNodes].some((n) => n.nodeType === 3 && /\S/.test(n.nodeValue))) add(s.color, el);
902
+ add(s.backgroundColor, el);
903
+ for (const side of ["Top", "Right", "Bottom", "Left"]) {
904
+ if (parseFloat(s[`border${side}Width`]) > 0 && s[`border${side}Style`] !== "none") add(s[`border${side}Color`], el);
905
+ }
906
+ const bg = s.backgroundImage || "none";
907
+ if (/gradient\(/.test(bg)) for (const stop of bg.match(GRADIENT_STOP) ?? []) add(stop, el);
908
+ for (const u of bg.matchAll(/url\(\s*(["']?)(.*?)\1\s*\)/g)) {
909
+ images += 1;
910
+ ref(u[2], el);
911
+ }
912
+ };
913
+ const shape = (el) => {
914
+ const r = el.getBoundingClientRect();
915
+ if (!(r.width > 0 || r.height > 0) || !shown(el)) return;
916
+ const p = svgPaints(getComputedStyle(el));
917
+ add(p.fill, el);
918
+ add(p.stroke, el);
919
+ };
920
+ // The paint a shape drawn through a use gets: its own fill or stroke, declared on it or on an element
921
+ // between it and the referenced element (attribute or inline style; currentColor takes the use's color);
922
+ // otherwise the use's own, which the copy inherits. A value set only by a style sheet rule on the
923
+ // referenced shapes is read as the use's.
924
+ const declared = (e, prop) => {
925
+ const v = (e.style?.getPropertyValue(prop) || e.getAttribute(prop) || "").trim().toLowerCase();
926
+ return v === "" || v === "inherit" ? null : v;
927
+ };
928
+ const paintThroughUse = (shapeEl, top, use, prop) => {
929
+ for (let e = shapeEl; e; e = e.parentElement) {
930
+ const v = declared(e, prop);
931
+ if (v) return v === "currentcolor" ? getComputedStyle(use).color : getComputedStyle(e)[prop];
932
+ if (e === top) break;
933
+ }
934
+ return getComputedStyle(use)[prop];
935
+ };
936
+ // A use that points inside this document draws a copy of the referenced element (often a symbol in
937
+ // defs): its drawn shapes are read with the paint the copy gets, under the use's selector. A use that
938
+ // points to another file is a reference, not read for color.
939
+ const useInside = (use) => {
940
+ const r = use.getBoundingClientRect();
941
+ if (!(r.width > 0 && r.height > 0) || !shown(use)) return;
942
+ const href = hrefOf(use);
943
+ if (!href) return;
944
+ if (!href.startsWith("#")) {
945
+ ref(href, use);
946
+ return;
947
+ }
948
+ const top = document.getElementById(href.slice(1));
949
+ if (!top || top === use || top.contains(use)) return;
950
+ const nested = (e) => e !== top && e.closest(SVG_UNDRAWN) !== top.closest(SVG_UNDRAWN);
951
+ for (const el of [top, ...top.querySelectorAll("*")]) {
952
+ if (!SVG_SHAPES.has(el.localName) || (el !== top && nested(el.parentElement))) continue;
953
+ const s = getComputedStyle(use);
954
+ const fill = paintThroughUse(el, top, use, "fill");
955
+ const stroke = paintThroughUse(el, top, use, "stroke");
956
+ if (fill !== "none" && parseFloat(s.fillOpacity) > 0) add(fill, use);
957
+ if (stroke !== "none" && parseFloat(s.strokeOpacity) > 0 && parseFloat(getComputedStyle(el).strokeWidth) > 0) add(stroke, use);
958
+ }
959
+ };
960
+ const svgInside = (svg) => {
961
+ for (const el of svg.querySelectorAll("*")) {
962
+ if (el.closest(SVG_UNDRAWN)) continue;
963
+ if (el.localName === "image") {
964
+ const r = el.getBoundingClientRect();
965
+ if (r.width > 0 && r.height > 0 && shown(el)) {
966
+ images += 1;
967
+ ref(hrefOf(el), el);
968
+ }
969
+ } else if (el.localName === "use") {
970
+ useInside(el);
971
+ } else if (SVG_SHAPES.has(el.localName)) {
972
+ shape(el);
973
+ }
974
+ }
975
+ };
976
+ // html, then body, read directly: body paints the canvas even when it has no box of its own (every
977
+ // child out of flow), so the walk would not keep it.
978
+ readBox(root, getComputedStyle(root));
979
+ const bodyStyle = body ? getComputedStyle(body) : null;
980
+ if (bodyStyle && bodyStyle.display !== "none") readBox(body, bodyStyle);
981
+ for (const el of walk().seen) {
982
+ if (el === body) continue;
983
+ readBox(el, getComputedStyle(el));
984
+ if (el.tagName === "IMG") {
985
+ images += 1;
986
+ ref(el.currentSrc || el.src, el);
987
+ } else if (el instanceof SVGSVGElement) {
988
+ svgInside(el);
989
+ }
990
+ }
991
+ return {
992
+ overflow: { right: Math.max(0, root.scrollWidth - innerWidth), bottom: Math.max(0, root.scrollHeight - innerHeight) },
993
+ colors: [...colors].map(([hex, list]) => ({ hex, where: list })),
994
+ symbolRefs,
995
+ images,
996
+ unread,
997
+ };
998
+ };
999
+
1000
+ // ---- reader: motion (the elements the motion probe recorded, and the gradients, read only) ----
1001
+ // For window.__lazuliMotion.targets from opts.from on: kept when the walk keeps the element or its
1002
+ // closest svg or video (the walk does not go inside them), inView when its box meets the viewport now.
1003
+ // gradients: kept elements whose computed background-image holds a gradient, the box clipped to the
1004
+ // viewport (viewport coordinates), the first opts.maxGradients (MAX_GRADIENTS), noted when cut.
1005
+ const motion = ({ from = 0, maxGradients, snapshot = null }) => {
1006
+ const seen = new Set(walk().seen);
1007
+ const w = root.clientWidth;
1008
+ const h = root.clientHeight;
1009
+ const keptEl = (el) => {
1010
+ if (seen.has(el)) return true;
1011
+ for (let a = el.closest("svg"); a; a = a.parentElement && a.parentElement.closest("svg")) {
1012
+ if (seen.has(a)) return true;
1013
+ }
1014
+ const video = el.closest("video");
1015
+ return !!video && seen.has(video);
1016
+ };
1017
+ const meets = (r) => r.width > 0 && r.height > 0 && r.right > 0 && r.bottom > 0 && r.left < w && r.top < h;
1018
+ const all = (window.__lazuliMotion && window.__lazuliMotion.targets) || [];
1019
+ const targets = [];
1020
+ for (let index = from; index < all.length; index++) {
1021
+ const el = all[index];
1022
+ const connected = !!el && el.isConnected;
1023
+ targets.push({
1024
+ index,
1025
+ selector: el ? selectorOf(el) : "",
1026
+ kept: connected && keptEl(el),
1027
+ inView: connected && meets(el.getBoundingClientRect()),
1028
+ });
1029
+ }
1030
+ const found = [];
1031
+ for (const el of walk().seen) {
1032
+ if (!getComputedStyle(el).backgroundImage.includes("gradient(")) continue;
1033
+ const r = el.getBoundingClientRect();
1034
+ const left = Math.max(0, r.left);
1035
+ const top = Math.max(0, r.top);
1036
+ const right = Math.min(w, r.right);
1037
+ const bottom = Math.min(h, r.bottom);
1038
+ if (right > left && bottom > top) found.push({ selector: selectorOf(el), box: { x: left, y: top, w: right - left, h: bottom - top } });
1039
+ }
1040
+ const notes = framesNote("motion inside one is not read.");
1041
+ if (found.length > maxGradients) notes.push(`The first ${maxGradients} of ${found.length} gradients on the screen were read.`);
1042
+ if (!snapshot) return { targets, gradients: found.slice(0, maxGradients), notes };
1043
+ // With opts.snapshot (frames pass): each target's box now (viewport coordinates), the
1044
+ // kept element painted at every point of a grid of snapshot px (the selector index per point, row by row,
1045
+ // from 0 to the viewport size inclusive), and the visible video and audio elements with controls.
1046
+ for (const t of targets) {
1047
+ const el = all[t.index];
1048
+ const r = el && el.isConnected ? el.getBoundingClientRect() : null;
1049
+ t.box = r ? { x: r.left, y: r.top, width: r.width, height: r.height } : null;
1050
+ }
1051
+ const selectors = [];
1052
+ const indexOf = new Map();
1053
+ const keptAt = (x, y) => {
1054
+ for (let el = document.elementFromPoint(x, y); el; el = el.parentElement) if (keptEl(el)) return el;
1055
+ return null;
1056
+ };
1057
+ const cols = Math.floor(w / snapshot) + 1;
1058
+ const rows = Math.floor(h / snapshot) + 1;
1059
+ const at = [];
1060
+ for (let j = 0; j < rows; j++) {
1061
+ for (let i = 0; i < cols; i++) {
1062
+ const el = keptAt(Math.min(i * snapshot, w - 1), Math.min(j * snapshot, h - 1));
1063
+ if (!el) {
1064
+ at.push(-1);
1065
+ continue;
1066
+ }
1067
+ if (!indexOf.has(el)) {
1068
+ indexOf.set(el, selectors.length);
1069
+ selectors.push(selectorOf(el));
1070
+ }
1071
+ at.push(indexOf.get(el));
1072
+ }
1073
+ }
1074
+ const media = [];
1075
+ for (const el of seen) {
1076
+ if ((el.tagName === "VIDEO" || el.tagName === "AUDIO") && el.controls && meets(el.getBoundingClientRect())) media.push({ kind: el.tagName.toLowerCase(), selector: selectorOf(el) });
1077
+ }
1078
+ return { targets, gradients: found.slice(0, maxGradients), notes, points: { step: snapshot, cols, rows, at, selectors }, media };
1079
+ };
1080
+
1081
+ // ---- reader: content (text as written, read only) ----
1082
+ // Definitions, not cutoffs (fixed before any page was read).
1083
+ const NAV_REGIONS = "nav, header, footer, [role=navigation], [role=banner], [role=contentinfo]";
1084
+ const HEADING_SCOPE = "h1, h2, h3, h4, h5, h6, [role=heading]";
1085
+ // The nearest ancestor (or self) up to el whose box is not inline: text of two such boxes is two blocks.
1086
+ const blockOf = (node, el) => {
1087
+ for (let e = node; e && e !== el; e = e.parentElement) if (!getComputedStyle(e).display.startsWith("inline")) return e;
1088
+ return el;
1089
+ };
1090
+ // visibleText with a space between text of different block-level boxes (a card link holding an h3 and a
1091
+ // p reads "Linen shirt From R$ 120"). Its own helper: controlName and the other readers are unchanged.
1092
+ const blockText = (el, skipFields = false) => {
1093
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
1094
+ let text = "";
1095
+ let last = null;
1096
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
1097
+ const parent = n.parentElement;
1098
+ if (skipFields && parent?.closest("select, textarea")) continue;
1099
+ if (!parent || SKIP.has(parent.tagName) || !paintsWithin(parent, el)) continue;
1100
+ const block = blockOf(parent, el);
1101
+ if (last !== null && block !== last) text += " ";
1102
+ text += n.nodeValue;
1103
+ last = block;
1104
+ }
1105
+ return collapse(text);
1106
+ };
1107
+ const contentKept = () => walk().seen.filter((el) => !offPage(el));
1108
+ const content = () => {
1109
+ const items = [];
1110
+ const alerts = [];
1111
+ const kept = contentKept();
1112
+ // Elements tied to an invalid field (aria-describedby, aria-errormessage): the field's message, never
1113
+ // listed again as an alert.
1114
+ const tied = [...document.querySelectorAll("[aria-invalid=true]")].filter(isField).flatMap((f) => [...idRefs(f, "aria-describedby"), ...idRefs(f, "aria-errormessage")]);
1115
+ const isTied = (el) => tied.some((t) => t === el || t.contains(el) || el.contains(t));
1116
+ for (const el of kept) {
1117
+ const k = kindOf(el);
1118
+ let kind = null;
1119
+ if (k === "button" || k === "link") kind = k;
1120
+ else if (el.matches(HEADING_SCOPE)) kind = "heading";
1121
+ else if (el.tagName === "LABEL") kind = "label";
1122
+ if (kind !== null) {
1123
+ const control = kind === "button" || kind === "link";
1124
+ const shownOwn = blockText(el, kind === "label");
1125
+ const text = control ? ariaName(el).name || shownOwn || controlName(el) : shownOwn;
1126
+ if (text) {
1127
+ let href = null;
1128
+ if (el.tagName === "A" && el.hasAttribute("href")) {
1129
+ try {
1130
+ const u = new URL(el.href, document.baseURI);
1131
+ // A non-empty fragment is part of the destination ("/" and "/#contato" are two places);
1132
+ // an empty "#" is dropped (URL.hash is "" for it).
1133
+ href = u.href.replace(/#$/, "");
1134
+ } catch {
1135
+ href = null;
1136
+ }
1137
+ }
1138
+ // ownText: the element shows text of its own (not only an image alt, an svg title or aria-label).
1139
+ items.push({ kind, text, transform: getComputedStyle(el).textTransform, selector: selectorOf(el), nav: el.closest(NAV_REGIONS) !== null, href, ownText: shownOwn !== "" });
1140
+ }
1141
+ }
1142
+ if (roleOf(el) === "alert" || collapse(el.getAttribute("aria-live")).toLowerCase() === "assertive") {
1143
+ if (isTied(el) || alerts.some((a) => a.el.contains(el))) continue;
1144
+ const text = blockText(el);
1145
+ if (text) alerts.push({ el, text, selector: selectorOf(el) });
1146
+ }
1147
+ }
1148
+ return { items, alerts: alerts.map(({ text, selector }) => ({ text, selector })), notes: framesNote("text inside one is not read.") };
1149
+ };
1150
+
1151
+ // ---- reader: chart (svg and canvas charts at rest, read only) ----
1152
+ // For each outermost svg and each canvas the walk keeps (walk().seen; no second visibility test), both
1153
+ // sides at least opts.minSide, in document order, the first opts.maxCharts (noted when cut): its page box,
1154
+ // name, chart word, background and, for an svg, the shapes and texts that paint inside it and the legend
1155
+ // of the chart or of its container. A canvas is read as a box and a name only: no context is created on a
1156
+ // page canvas and its pixels are never read here (no getContext, toDataURL, toBlob or getImageData on
1157
+ // it), and no library object is read. Inside the svg (which the walk does not enter) a shape or
1158
+ // text counts only when it paints: no display none on it or an ancestor inside the svg, visibility
1159
+ // visible, an opacity product above 0, a box with area that meets the svg's box, and not inside
1160
+ // SVG_UNDRAWN. A clip path of one rect (user space) is applied to the box; any other clip path is counted
1161
+ // in unread.clip and not applied. A url() paint (gradient, pattern) is counted in unread.paint. A use is
1162
+ // read as its own box with its own computed paint and is never expanded. Charts inside a frame are not read.
1163
+ const CHART_SHAPES = new Set(["path", "rect", "circle", "ellipse", "line", "polyline", "polygon", "use"]);
1164
+ const PATH_ARGS = { m: 2, l: 2, h: 1, v: 1, c: 6, s: 4, q: 4, t: 2, a: 7, z: 0 };
1165
+ const chart = (o) => {
1166
+ const re = (r) => new RegExp(r.source, r.flags);
1167
+ const chartWords = re(o.chartWords);
1168
+ const legendWord = re(o.legendWord);
1169
+ const axisWords = re(o.axisWords);
1170
+ const seenSet = new Set(walk().seen);
1171
+ const attr = (el, n) => el.getAttribute(n) || "";
1172
+ const named = (el) =>
1173
+ ["role", "aria-roledescription", "aria-label", "class", "id"]
1174
+ .flatMap((n) => attr(el, n).toLowerCase().split(/[^a-z0-9áà]+/))
1175
+ .some((t) => t && chartWords.test(t));
1176
+ const chartWordOf = (el) => {
1177
+ for (let e = el, i = 0; e && i <= o.containerLevels; e = e.parentElement, i++) if (named(e)) return true;
1178
+ return false;
1179
+ };
1180
+ const isLegend = (e) => legendWord.test(attr(e, "class")) || legendWord.test(attr(e, "id")) || legendWord.test(attr(e, "aria-label"));
1181
+ const clean = (t) => (t || "").replace(/\s+/g, " ").trim();
1182
+ const nameOf = (el) => {
1183
+ const label = clean(attr(el, "aria-label"));
1184
+ if (label) return label;
1185
+ const ids = clean(attr(el, "aria-labelledby"));
1186
+ const by = ids ? clean(ids.split(" ").map((id) => document.getElementById(id)?.textContent || "").join(" ")) : "";
1187
+ if (by) return by;
1188
+ const title = el.localName === "svg" ? [...el.children].find((c) => c.localName === "title") : null;
1189
+ if (title && clean(title.textContent)) return clean(title.textContent);
1190
+ const caption = el.closest("figure")?.querySelector("figcaption");
1191
+ return caption && clean(caption.textContent) ? clean(caption.textContent) : null;
1192
+ };
1193
+ // A computed color as { rgb, a } (a in 0 to 1); null when it is not a color.
1194
+ const rgba = (v) => {
1195
+ const s = (v || "").trim();
1196
+ const m = /^rgba?\(([^)]+)\)$/.exec(s);
1197
+ if (m) {
1198
+ const p = m[1].split(/[\s,/]+/).filter(Boolean);
1199
+ const a = p.length >= 4 ? (p[3].endsWith("%") ? parseFloat(p[3]) / 100 : parseFloat(p[3])) : 1;
1200
+ return { rgb: p.slice(0, 3).map(parseFloat), a };
1201
+ }
1202
+ const c = s && s !== "none" ? throughCanvas(s) : null;
1203
+ return c ? { rgb: [c.r, c.g, c.b], a: c.a / 255 } : null;
1204
+ };
1205
+ const over = (rgb, a, bg) => hexOf(rgb.map((x, i) => x * a + bg[i] * (1 - a)));
1206
+ // The nearest painted background up the tree, translucent layers composited, over white when none.
1207
+ const backgroundOf = (el) => {
1208
+ const layers = [];
1209
+ for (let e = el; e; e = e.parentElement) {
1210
+ const c = rgba(getComputedStyle(e).backgroundColor);
1211
+ if (c && c.a > 0) {
1212
+ layers.push(c);
1213
+ if (c.a >= 1) break;
1214
+ }
1215
+ }
1216
+ return layers.reverse().reduce((bg, c) => bg.map((x, i) => c.rgb[i] * c.a + x * (1 - c.a)), [255, 255, 255]);
1217
+ };
1218
+ const meet = (a, b) => ({ left: Math.max(a.left, b.left), top: Math.max(a.top, b.top), right: Math.min(a.right, b.right), bottom: Math.min(a.bottom, b.bottom) });
1219
+ const full = (c) => c.right > c.left && c.bottom > c.top;
1220
+ const pageBox = (c) => ({ x: c.left + scrollX, y: c.top + scrollY, w: c.right - c.left, h: c.bottom - c.top });
1221
+ // A clip path of one rect without transforms, in user space, as a client rect; null for any other.
1222
+ const clipRect = (el, value) => {
1223
+ const m = /^url\(\s*["']?#([^"')]+)["']?\s*\)$/.exec(value);
1224
+ const cp = m ? document.getElementById(m[1]) : null;
1225
+ if (!cp || cp.localName !== "clipPath" || attr(cp, "clipPathUnits") === "objectBoundingBox" || cp.hasAttribute("transform")) return null;
1226
+ const kids = [...cp.children];
1227
+ if (kids.length !== 1 || kids[0].localName !== "rect" || kids[0].hasAttribute("transform")) return null;
1228
+ const ctm = el.getScreenCTM();
1229
+ if (!ctm) return null;
1230
+ const r = kids[0];
1231
+ const [x, y, w, h] = [r.x, r.y, r.width, r.height].map((l) => l.baseVal.value);
1232
+ const pts = [[x, y], [x + w, y], [x, y + h], [x + w, y + h]].map(([px, py]) => new DOMPoint(px, py).matrixTransform(ctm));
1233
+ return { left: Math.min(...pts.map((p) => p.x)), right: Math.max(...pts.map((p) => p.x)), top: Math.min(...pts.map((p) => p.y)), bottom: Math.max(...pts.map((p) => p.y)) };
1234
+ };
1235
+ // What the ancestors inside the svg pass down: display none, the opacity product, a rect clip, an unread clip.
1236
+ const stateOf = (el, svg, memo) => {
1237
+ if (el === svg || !el) return { none: false, opacity: 1, clip: null, bad: false };
1238
+ if (memo.has(el)) return memo.get(el);
1239
+ const parent = stateOf(el.parentElement, svg, memo);
1240
+ const s = getComputedStyle(el);
1241
+ let st;
1242
+ if (parent.none || s.display === "none") {
1243
+ st = { none: true };
1244
+ } else {
1245
+ let { clip, bad } = parent;
1246
+ if (s.clipPath && s.clipPath !== "none") {
1247
+ const c = clipRect(el, s.clipPath);
1248
+ if (c) clip = clip ? meet(clip, c) : c;
1249
+ else bad = true;
1250
+ }
1251
+ st = { none: false, opacity: parent.opacity * parseFloat(s.opacity), clip, bad };
1252
+ }
1253
+ memo.set(el, st);
1254
+ return st;
1255
+ };
1256
+ const axisMemo = new Map();
1257
+ const axisOf = (el, svg) => {
1258
+ if (!el || el === svg) return false;
1259
+ if (!axisMemo.has(el)) axisMemo.set(el, axisWords.test(attr(el, "class")) || axisWords.test(attr(el, "id")) || axisOf(el.parentElement, svg));
1260
+ return axisMemo.get(el);
1261
+ };
1262
+ // The vertices of a path's d (end points of each segment), null when it cannot be read.
1263
+ const pathVertices = (d) => {
1264
+ const tokens = (d || "").match(/[a-zA-Z]|[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/g) || [];
1265
+ const pts = [];
1266
+ let cmd = null;
1267
+ let x = 0;
1268
+ let y = 0;
1269
+ let sx = 0;
1270
+ let sy = 0;
1271
+ for (let i = 0; i < tokens.length; ) {
1272
+ if (/[a-zA-Z]/.test(tokens[i])) {
1273
+ cmd = tokens[i++];
1274
+ if (cmd === "z" || cmd === "Z") {
1275
+ x = sx;
1276
+ y = sy;
1277
+ continue;
1278
+ }
1279
+ }
1280
+ const lc = cmd ? cmd.toLowerCase() : null;
1281
+ const n = PATH_ARGS[lc];
1282
+ if (!n) return pts.length ? pts : null;
1283
+ const a = tokens.slice(i, i + n).map(Number);
1284
+ if (a.length < n || a.some((v) => Number.isNaN(v))) return pts.length ? pts : null;
1285
+ i += n;
1286
+ const rel = cmd === lc;
1287
+ if (lc === "h") x = rel ? x + a[0] : a[0];
1288
+ else if (lc === "v") y = rel ? y + a[0] : a[0];
1289
+ else {
1290
+ x = rel ? x + a[n - 2] : a[n - 2];
1291
+ y = rel ? y + a[n - 1] : a[n - 1];
1292
+ }
1293
+ if (lc === "m") {
1294
+ sx = x;
1295
+ sy = y;
1296
+ cmd = rel ? "l" : "L";
1297
+ }
1298
+ pts.push([x, y]);
1299
+ }
1300
+ return pts;
1301
+ };
1302
+ const verticesOf = (el) => {
1303
+ if (el.localName === "path") return pathVertices(attr(el, "d"));
1304
+ if (el.localName === "line") return [[el.x1.baseVal.value, el.y1.baseVal.value], [el.x2.baseVal.value, el.y2.baseVal.value]];
1305
+ if (el.localName === "polyline" || el.localName === "polygon") {
1306
+ const list = el.points;
1307
+ const pts = [];
1308
+ for (let i = 0; i < list.numberOfItems; i++) pts.push([list.getItem(i).x, list.getItem(i).y]);
1309
+ return pts;
1310
+ }
1311
+ return null;
1312
+ };
1313
+ // The painted client box of an element inside an svg, with its opacity product; null when it paints
1314
+ // nothing there. An unread clip is reported, not applied.
1315
+ const placed = (el, svg, memo, frame) => {
1316
+ const st = stateOf(el, svg, memo);
1317
+ if (st.none) return null;
1318
+ const s = getComputedStyle(el);
1319
+ if (s.visibility !== "visible" || !(st.opacity > 0)) return null;
1320
+ const r = el.getBoundingClientRect();
1321
+ let c = { left: r.left, top: r.top, right: r.right, bottom: r.bottom };
1322
+ if (!full(c)) return null;
1323
+ c = meet(c, frame);
1324
+ if (!full(c)) return null;
1325
+ if (st.clip) {
1326
+ c = meet(c, st.clip);
1327
+ if (!full(c)) return null;
1328
+ }
1329
+ return { s, c, opacity: st.opacity, bad: st.bad };
1330
+ };
1331
+ // The paint a shape shows: its fill (not for a line), else its stroke; { url: true } for a paint server.
1332
+ const paintOf = (el, s, opacity, bg) => {
1333
+ const p = svgPaints(s);
1334
+ const pick = (v, o, shape) => {
1335
+ if (!v) return null;
1336
+ if (/^url\(/.test(v)) return { shape, color: null };
1337
+ const c = rgba(v);
1338
+ return c && c.a * o > 0 ? { shape, color: over(c.rgb, c.a * o * opacity, bg) } : null;
1339
+ };
1340
+ return (el.localName === "line" ? null : pick(p.fill, parseFloat(s.fillOpacity), "fill")) ?? pick(p.stroke, parseFloat(s.strokeOpacity), "stroke");
1341
+ };
1342
+ const shapeOf = (el, svg, memo, frame, bg) => {
1343
+ const at = placed(el, svg, memo, frame);
1344
+ if (!at) return null;
1345
+ const paint = paintOf(el, at.s, at.opacity, bg);
1346
+ return paint ? { at, paint } : null;
1347
+ };
1348
+ const textOfSvg = (el, svg, memo, frame, bg, inLegend) => {
1349
+ const text = clean(el.textContent);
1350
+ if (!text) return null;
1351
+ const at = placed(el, svg, memo, frame);
1352
+ if (!at) return null;
1353
+ const ctm = el.getScreenCTM();
1354
+ const scale = ctm ? Math.sqrt(Math.abs(ctm.a * ctm.d - ctm.b * ctm.c)) : 1;
1355
+ const paint = paintOf(el, at.s, at.opacity, bg);
1356
+ return { text, selector: selectorOf(el), box: pageBox(at.c), px: parseFloat(at.s.fontSize) * scale, color: paint ? paint.color : null, inLegend };
1357
+ };
1358
+ const outerSvg = (el) => {
1359
+ let top = null;
1360
+ for (let e = el.closest("svg"); e; e = e.parentElement && e.parentElement.closest("svg")) top = e;
1361
+ return top;
1362
+ };
1363
+ const frameOf = (svg) => {
1364
+ const r = svg.getBoundingClientRect();
1365
+ return { left: r.left, top: r.top, right: r.right, bottom: r.bottom };
1366
+ };
1367
+ // The legend: swatches (painted shapes in it, and HTML elements in it of at most swatchPx a side with a
1368
+ // background color) and texts. null when nothing in it paints.
1369
+ const memos = new Map();
1370
+ const memoOf = (svg) => {
1371
+ if (!memos.has(svg)) memos.set(svg, new Map());
1372
+ return memos.get(svg);
1373
+ };
1374
+ const readLegend = (legendEl, bg) => {
1375
+ const swatches = [];
1376
+ const texts = [];
1377
+ const inSvg = legendEl.localName !== "svg" && legendEl.closest("svg");
1378
+ if (!inSvg && !seenSet.has(legendEl)) return null;
1379
+ for (const el of [legendEl, ...legendEl.querySelectorAll("*")]) {
1380
+ const svg = el instanceof SVGElement ? outerSvg(el) : null;
1381
+ if (svg) {
1382
+ if (!seenSet.has(svg) || el.closest(SVG_UNDRAWN)) continue;
1383
+ if (CHART_SHAPES.has(el.localName)) {
1384
+ const sh = shapeOf(el, svg, memoOf(svg), frameOf(svg), bg);
1385
+ if (sh && sh.paint.color) swatches.push({ color: sh.paint.color, box: pageBox(sh.at.c) });
1386
+ } else if (el.localName === "text") {
1387
+ const t = textOfSvg(el, svg, memoOf(svg), frameOf(svg), bg, true);
1388
+ if (t) texts.push(t);
1389
+ }
1390
+ continue;
1391
+ }
1392
+ if (!seenSet.has(el)) continue;
1393
+ const s = getComputedStyle(el);
1394
+ const r = el.getBoundingClientRect();
1395
+ const c = rgba(s.backgroundColor);
1396
+ if (r.width <= o.swatchPx && r.height <= o.swatchPx && c && c.a > 0) swatches.push({ color: over(c.rgb, c.a, bg), box: box(r) });
1397
+ const nodes = [...el.childNodes].filter((n) => n.nodeType === 3 && LETTER.test(n.nodeValue));
1398
+ const rects = nodes.length ? rectsOf(nodes) : [];
1399
+ if (rects.length) {
1400
+ const col = rgba(s.color);
1401
+ texts.push({
1402
+ text: textOf(nodes), selector: selectorOf(el), box: box(union(rects)), px: parseFloat(s.fontSize),
1403
+ color: col ? over(col.rgb, col.a, bg) : null, inLegend: true,
1404
+ });
1405
+ }
1406
+ }
1407
+ return swatches.length || texts.length ? { selector: selectorOf(legendEl), swatches, texts } : null;
1408
+ };
1409
+ const readSvg = (svg, raw) => {
1410
+ const memo = memoOf(svg);
1411
+ const frame = frameOf(svg);
1412
+ const bg = backgroundOf(svg);
1413
+ let legendEl = [...svg.querySelectorAll("*")].find((e) => !e.closest(SVG_UNDRAWN) && isLegend(e)) ?? null;
1414
+ for (let a = svg.parentElement, i = 0; !legendEl && a && i < o.containerLevels; a = a.parentElement, i++) {
1415
+ legendEl = [...a.querySelectorAll("*")].find((e) => !svg.contains(e) && !e.contains(svg) && isLegend(e)) ?? null;
1416
+ }
1417
+ raw.legend = legendEl ? readLegend(legendEl, bg) : null;
1418
+ for (const el of svg.querySelectorAll("*")) {
1419
+ const isShape = CHART_SHAPES.has(el.localName);
1420
+ const isText = el.localName === "text";
1421
+ if (!isShape && !isText) continue;
1422
+ if (raw.cut.marks && raw.cut.texts) break;
1423
+ if (el.closest(SVG_UNDRAWN)) continue;
1424
+ if (isShape && raw.marks.length >= o.maxMarks) {
1425
+ raw.cut.marks = true;
1426
+ continue;
1427
+ }
1428
+ if (isText && raw.texts.length >= o.maxTexts) {
1429
+ raw.cut.texts = true;
1430
+ continue;
1431
+ }
1432
+ const inLegend = !!legendEl && legendEl.contains(el);
1433
+ if (isText) {
1434
+ const t = textOfSvg(el, svg, memo, frame, bg, inLegend);
1435
+ if (t) raw.texts.push(t);
1436
+ continue;
1437
+ }
1438
+ const sh = shapeOf(el, svg, memo, frame, bg);
1439
+ if (!sh) continue;
1440
+ if (sh.at.bad) raw.unread.clip += 1;
1441
+ if (sh.paint.color === null) raw.unread.paint += 1;
1442
+ const v = verticesOf(el);
1443
+ const straight = el.localName === "line" || (!!v && v.length === 2 && (Math.abs(v[0][0] - v[1][0]) < 1e-6 || Math.abs(v[0][1] - v[1][1]) < 1e-6));
1444
+ raw.marks.push({
1445
+ tag: el.localName, selector: selectorOf(el), shape: sh.paint.shape, color: sh.paint.color, box: pageBox(sh.at.c),
1446
+ points: v ? v.length : null, straight, axisLike: axisOf(el, svg), inLegend,
1447
+ });
1448
+ }
1449
+ };
1450
+ const found = walk().seen.filter((el) => {
1451
+ if (!(el instanceof SVGSVGElement || el.tagName === "CANVAS")) return false;
1452
+ if (el instanceof SVGSVGElement && el.parentElement && el.parentElement.closest("svg")) return false;
1453
+ const r = el.getBoundingClientRect();
1454
+ return r.width >= o.minSide && r.height >= o.minSide;
1455
+ });
1456
+ // The part of the chart that paints: its box cut by every ancestor that
1457
+ // clips on an axis (up to a fixed ancestor) and by the document, in page coordinates; null when empty.
1458
+ const visibleOf = (el) => {
1459
+ const r = el.getBoundingClientRect();
1460
+ let c = { left: r.left, top: r.top, right: r.right, bottom: r.bottom };
1461
+ for (let a = el.parentElement; a && a !== body && a !== root; a = a.parentElement) {
1462
+ const s = getComputedStyle(a);
1463
+ // Overflow clips at the padding box: inside the borders and any scrollbar.
1464
+ const b = a.getBoundingClientRect();
1465
+ const left = b.left + a.clientLeft;
1466
+ const top = b.top + a.clientTop;
1467
+ c = narrow(c, s, { left, top, right: left + a.clientWidth, bottom: top + a.clientHeight });
1468
+ if (s.position === "fixed") break;
1469
+ }
1470
+ c = meetDoc(c);
1471
+ return c.right > c.left && c.bottom > c.top ? pageBox(c) : null;
1472
+ };
1473
+ const meetDoc = (c) => ({
1474
+ left: Math.max(c.left, -scrollX), top: Math.max(c.top, -scrollY),
1475
+ right: Math.min(c.right, root.scrollWidth - scrollX), bottom: Math.min(c.bottom, root.scrollHeight - scrollY),
1476
+ });
1477
+ const charts = found.slice(0, o.maxCharts).map((el, index) => {
1478
+ const kind = el.tagName === "CANVAS" ? "canvas" : "svg";
1479
+ const raw = {
1480
+ index, kind, selector: selectorOf(el), box: box(el.getBoundingClientRect()), visible: visibleOf(el), name: nameOf(el), chartWord: chartWordOf(el),
1481
+ background: hexOf(backgroundOf(el)), marks: [], texts: [], legend: null, cut: { marks: false, texts: false }, unread: { paint: 0, clip: 0 },
1482
+ };
1483
+ if (kind === "svg") readSvg(el, raw);
1484
+ return raw;
1485
+ });
1486
+ const notes = framesNote("a chart inside one is not read.");
1487
+ if (found.length > o.maxCharts) notes.push(`The first ${o.maxCharts} of ${found.length} svg and canvas elements of chart size were read.`);
1488
+ return { charts, notes };
1489
+ };
1490
+
1491
+ const readers = { layout, rhythm, components, forms, actions, piece, motion, content, seen: contentKept, chart };
1492
+ // Every reader says how many data-block marks the page carries; Node notes them when they were not read.
1493
+ const out = readers[opts.read](opts);
1494
+ if (out && typeof out === "object" && !Array.isArray(out)) out.marks = document.querySelectorAll("[data-block]").length;
1495
+ return out;
1496
+ }