basalt-ui 2.13.3 → 2.15.0

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 (187) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/MIGRATING.md +42 -12
  3. package/agent/agents/basalt-design-reviewer.md +83 -0
  4. package/agent/rules/basalt-batteries.md +1 -2
  5. package/agent/rules/basalt-charts.md +1 -1
  6. package/agent/rules/basalt-controls.md +3 -3
  7. package/agent/rules/basalt-mantine.md +1 -2
  8. package/agent/rules/basalt-state.md +1 -2
  9. package/agent/rules/basalt-tokens.md +1 -3
  10. package/agent/skills/basalt-design/SKILL.md +26 -8
  11. package/agent/templates/AGENTS-block.md.tpl +7 -0
  12. package/configs/oxlint-plugin.js +39 -2
  13. package/configs/oxlint-plugin.test.ts +48 -0
  14. package/dist/agent/chat/thread-feed-row.d.ts.map +1 -1
  15. package/dist/agent/chat/thread-feed-row.js +2 -2
  16. package/dist/agent/chat/thread-message.d.ts.map +1 -1
  17. package/dist/agent/chat/thread-message.js +2 -2
  18. package/dist/agent/chat/thread-outcome-card.js +2 -2
  19. package/dist/charts/DualPanel.d.ts.map +1 -1
  20. package/dist/charts/DualPanel.js +1 -0
  21. package/dist/charts/compile.d.ts.map +1 -1
  22. package/dist/charts/compile.js +3 -2
  23. package/dist/charts/cursor.d.ts +10 -6
  24. package/dist/charts/cursor.d.ts.map +1 -1
  25. package/dist/charts/cursor.js +20 -13
  26. package/dist/charts/legend.d.ts +7 -6
  27. package/dist/charts/legend.d.ts.map +1 -1
  28. package/dist/charts/legend.js +3 -3
  29. package/dist/charts/panel.d.ts +2 -0
  30. package/dist/charts/panel.d.ts.map +1 -1
  31. package/dist/charts/panel.js +1 -0
  32. package/dist/cli/board-freshness.d.ts +25 -0
  33. package/dist/cli/board-freshness.d.ts.map +1 -0
  34. package/dist/cli/board-freshness.js +88 -0
  35. package/dist/cli/doctor.d.ts +2 -1
  36. package/dist/cli/doctor.d.ts.map +1 -1
  37. package/dist/cli/doctor.js +3 -1
  38. package/dist/cli/help.d.ts.map +1 -1
  39. package/dist/cli/help.js +9 -3
  40. package/dist/cli/index.d.ts +15 -1
  41. package/dist/cli/index.d.ts.map +1 -1
  42. package/dist/cli/index.js +57 -7
  43. package/dist/cli/init.d.ts.map +1 -1
  44. package/dist/cli/init.js +6 -1
  45. package/dist/cli/shot/board.d.ts +5 -0
  46. package/dist/cli/shot/board.d.ts.map +1 -0
  47. package/dist/cli/shot/board.js +96 -0
  48. package/dist/cli/shot/capture.d.ts +59 -0
  49. package/dist/cli/shot/capture.d.ts.map +1 -0
  50. package/dist/cli/shot/capture.js +473 -0
  51. package/dist/cli/shot/index.d.ts +45 -0
  52. package/dist/cli/shot/index.d.ts.map +1 -0
  53. package/dist/cli/shot/index.js +289 -0
  54. package/dist/cli/shot/measure.d.ts +28 -0
  55. package/dist/cli/shot/measure.d.ts.map +1 -0
  56. package/dist/cli/shot/measure.js +176 -0
  57. package/dist/cli/shot/playwright.d.ts +101 -0
  58. package/dist/cli/shot/playwright.d.ts.map +1 -0
  59. package/dist/cli/shot/playwright.js +60 -0
  60. package/dist/cli/shot/serve.d.ts +6 -0
  61. package/dist/cli/shot/serve.d.ts.map +1 -0
  62. package/dist/cli/shot/serve.js +33 -0
  63. package/dist/cli/shot/types.d.ts +97 -0
  64. package/dist/cli/shot/types.d.ts.map +1 -0
  65. package/dist/cli/shot/types.js +17 -0
  66. package/dist/cli/sync.d.ts.map +1 -1
  67. package/dist/cli/sync.js +2 -1
  68. package/dist/commands/notifications/center.d.ts.map +1 -1
  69. package/dist/commands/notifications/center.js +2 -11
  70. package/dist/controls/control-name.d.ts +27 -0
  71. package/dist/controls/control-name.d.ts.map +1 -0
  72. package/dist/controls/control-name.js +11 -0
  73. package/dist/controls/enum-filter.d.ts +3 -6
  74. package/dist/controls/enum-filter.d.ts.map +1 -1
  75. package/dist/controls/enum-filter.js +8 -4
  76. package/dist/controls/filter-base.d.ts +30 -0
  77. package/dist/controls/filter-base.d.ts.map +1 -0
  78. package/dist/controls/filter-base.js +0 -0
  79. package/dist/controls/filter-pill.d.ts +3 -1
  80. package/dist/controls/filter-pill.d.ts.map +1 -1
  81. package/dist/controls/filter-pill.js +2 -0
  82. package/dist/controls/filter-sheet.d.ts +0 -32
  83. package/dist/controls/filter-sheet.d.ts.map +1 -1
  84. package/dist/controls/filter-sheet.js +1 -28
  85. package/dist/controls/glyphs.d.ts +12 -0
  86. package/dist/controls/glyphs.d.ts.map +1 -1
  87. package/dist/controls/glyphs.js +23 -2
  88. package/dist/controls/index.d.ts +2 -1
  89. package/dist/controls/index.d.ts.map +1 -1
  90. package/dist/controls/multi-select-filter.d.ts +8 -3
  91. package/dist/controls/multi-select-filter.d.ts.map +1 -1
  92. package/dist/controls/multi-select-filter.js +27 -10
  93. package/dist/controls/number-filter.d.ts +3 -12
  94. package/dist/controls/number-filter.d.ts.map +1 -1
  95. package/dist/controls/number-filter.js +17 -6
  96. package/dist/controls/panel-row.d.ts +5 -8
  97. package/dist/controls/panel-row.d.ts.map +1 -1
  98. package/dist/controls/panel-row.js +3 -0
  99. package/dist/controls/range-filter.d.ts +14 -14
  100. package/dist/controls/range-filter.d.ts.map +1 -1
  101. package/dist/controls/range-filter.js +18 -41
  102. package/dist/controls/search-filter.d.ts +5 -2
  103. package/dist/controls/search-filter.d.ts.map +1 -1
  104. package/dist/controls/search-filter.js +74 -40
  105. package/dist/controls/select-filter.d.ts +2 -15
  106. package/dist/controls/select-filter.d.ts.map +1 -1
  107. package/dist/controls/sync-button.d.ts +0 -6
  108. package/dist/controls/sync-button.d.ts.map +1 -1
  109. package/dist/controls/sync-button.js +6 -36
  110. package/dist/controls/toggle-filter.d.ts +2 -2
  111. package/dist/controls/toggle-filter.d.ts.map +1 -1
  112. package/dist/controls/toggle-filter.js +3 -2
  113. package/dist/controls/view-tabs.d.ts +3 -4
  114. package/dist/controls/view-tabs.d.ts.map +1 -1
  115. package/dist/controls/view-tabs.js +24 -5
  116. package/dist/format/date.d.ts +43 -10
  117. package/dist/format/date.d.ts.map +1 -1
  118. package/dist/format/date.js +109 -18
  119. package/dist/format/index.d.ts +12 -11
  120. package/dist/format/index.d.ts.map +1 -1
  121. package/dist/format/index.js +11 -2
  122. package/dist/format/measure.d.ts +9 -9
  123. package/dist/format/measure.d.ts.map +1 -1
  124. package/dist/format/measure.js +19 -8
  125. package/dist/format/number.d.ts +35 -27
  126. package/dist/format/number.d.ts.map +1 -1
  127. package/dist/format/number.js +41 -20
  128. package/dist/format/shared.d.ts +38 -7
  129. package/dist/format/shared.d.ts.map +1 -1
  130. package/dist/format/shared.js +61 -13
  131. package/dist/provider/index.d.ts +13 -1
  132. package/dist/provider/index.d.ts.map +1 -1
  133. package/dist/provider/index.js +8 -0
  134. package/dist/surfaces.d.ts +2 -0
  135. package/dist/surfaces.d.ts.map +1 -1
  136. package/dist/surfaces.js +2 -0
  137. package/llms.txt +35 -14
  138. package/package.json +1 -1
  139. package/src/agent/chat/thread-feed-row.tsx +2 -2
  140. package/src/agent/chat/thread-message.tsx +2 -2
  141. package/src/agent/chat/thread-outcome-card.tsx +2 -2
  142. package/src/charts/DualPanel.tsx +1 -0
  143. package/src/charts/compile.ts +3 -2
  144. package/src/charts/cursor.ts +44 -27
  145. package/src/charts/legend.tsx +11 -8
  146. package/src/charts/panel.tsx +3 -0
  147. package/src/cli/board-freshness.ts +132 -0
  148. package/src/cli/doctor.ts +10 -1
  149. package/src/cli/help.ts +14 -2
  150. package/src/cli/index.ts +80 -10
  151. package/src/cli/init.ts +8 -1
  152. package/src/cli/shot/board.ts +154 -0
  153. package/src/cli/shot/capture.ts +650 -0
  154. package/src/cli/shot/index.ts +362 -0
  155. package/src/cli/shot/measure.ts +225 -0
  156. package/src/cli/shot/playwright.ts +152 -0
  157. package/src/cli/shot/serve.ts +35 -0
  158. package/src/cli/shot/types.ts +91 -0
  159. package/src/cli/sync.ts +2 -1
  160. package/src/commands/notifications/center.tsx +2 -14
  161. package/src/controls/control-name.ts +33 -0
  162. package/src/controls/enum-filter.tsx +29 -27
  163. package/src/controls/filter-base.ts +31 -0
  164. package/src/controls/filter-pill.tsx +4 -0
  165. package/src/controls/filter-sheet.tsx +0 -56
  166. package/src/controls/glyphs.tsx +45 -2
  167. package/src/controls/index.ts +2 -1
  168. package/src/controls/multi-select-filter.tsx +67 -43
  169. package/src/controls/number-filter.tsx +47 -47
  170. package/src/controls/panel-row.tsx +7 -8
  171. package/src/controls/range-filter.tsx +54 -78
  172. package/src/controls/search-filter.tsx +107 -54
  173. package/src/controls/select-filter.tsx +2 -18
  174. package/src/controls/sync-button.tsx +7 -40
  175. package/src/controls/toggle-filter.tsx +9 -7
  176. package/src/controls/view-tabs.tsx +41 -21
  177. package/src/format/date.ts +189 -36
  178. package/src/format/index.ts +12 -11
  179. package/src/format/measure.ts +29 -18
  180. package/src/format/number.ts +76 -37
  181. package/src/format/shared.ts +116 -25
  182. package/src/provider/index.tsx +23 -0
  183. package/src/surfaces.ts +5 -0
  184. package/dist/agent/chat/relative-time.d.ts +0 -27
  185. package/dist/agent/chat/relative-time.d.ts.map +0 -1
  186. package/dist/agent/chat/relative-time.js +0 -27
  187. package/src/agent/chat/relative-time.ts +0 -55
@@ -0,0 +1,650 @@
1
+ /** Per route × scheme × viewport: full-page shot, then every `data-shot` anchor through every state. */
2
+ import { createHash } from 'node:crypto'
3
+ import { readFileSync } from 'node:fs'
4
+ import { basename, join } from 'node:path'
5
+
6
+ import { buildSheet } from './board'
7
+
8
+ import { finishMeasurement, measureAnchor } from './measure'
9
+ import type { Box, PwBrowser, PwContext, PwLocator, PwPage, ShotOptions } from './playwright'
10
+ import { PAGE_ANCHOR, SCHEMES, URL_STATES, VIEWPORTS, VIEWPORT_SPECS } from './types'
11
+ import type {
12
+ AnchorMetrics,
13
+ Measurement,
14
+ Scale,
15
+ Scheme,
16
+ ShotRecord,
17
+ ShotState,
18
+ Viewport,
19
+ } from './types'
20
+
21
+ const NAV_TIMEOUT_MS = 30_000
22
+ const HOVER_TIMEOUT_MS = 5_000
23
+ const TOOLTIP_TIMEOUT_MS = 3_000
24
+ const TAB_PRESSES = 80
25
+ const FOCUS_MARGIN_PX = 8
26
+ const TIP_PROBE_MS = 250
27
+ const TIP_SETTLE_MS = 60
28
+ const TIP_SETTLE_READS = 10
29
+
30
+ export type CaptureInput = {
31
+ browser: PwBrowser
32
+ base: string
33
+ routes: readonly string[]
34
+ states: readonly ShotState[]
35
+ pngDir: string
36
+ /** Replaces the in-page measurer (tests). */
37
+ measure?: (anchor: PwLocator) => Promise<Measurement>
38
+ log: (line: string) => void
39
+ }
40
+
41
+ type PageFacts = { anchors: string[]; declared: string[] }
42
+
43
+ /** Everything one page visit shares: where the records go and what was already measured. */
44
+ type Ctx = {
45
+ page: PwPage
46
+ input: CaptureInput
47
+ route: string
48
+ scheme: Scheme
49
+ viewport: Viewport
50
+ facts: PageFacts
51
+ anchors: AnchorMetrics[]
52
+ shots: ShotRecord[]
53
+ measured: Set<string>
54
+ /** Read on the first page of a context that loads. */
55
+ scale?: Steps | undefined
56
+ scaleError?: string | undefined
57
+ }
58
+
59
+ type Outcome = {
60
+ name: string
61
+ state: ShotState
62
+ status: ShotRecord['status']
63
+ file?: string
64
+ note?: string
65
+ }
66
+
67
+ /** Thrown inside a capture when the anchor simply has no such target: recorded `not-declared`, not `error`. */
68
+ class NotDeclared extends Error {}
69
+
70
+ const hash = (text: string): string => createHash('sha1').update(text).digest('hex').slice(0, 6)
71
+ const slug = (text: string): string => text.replace(/[^\w-]+/g, '-').replace(/^-+|-+$/g, '')
72
+ const firstLine = (error: unknown): string =>
73
+ (error instanceof Error ? error.message : String(error)).split('\n')[0] ?? ''
74
+ const sel = (name: string): string => `[data-shot=${JSON.stringify(name)}]`
75
+ const anchorOf = (c: Ctx, name: string): PwLocator => c.page.locator(sel(name)).first()
76
+
77
+ /** `<route>-<hash>__<name>-<hash>__…`: the hash of the RAW text keeps `/a/b` and `/a-b` apart. */
78
+ export const fileName = (
79
+ route: string,
80
+ name: string,
81
+ scheme: Scheme,
82
+ viewport: Viewport,
83
+ state: ShotState,
84
+ ): string =>
85
+ `${slug(route) || 'root'}-${hash(route)}__${slug(name)}-${hash(name)}__${scheme}__${viewport}__${state}.png`
86
+
87
+ /** The state URL: the query goes before any `#fragment`. */
88
+ export function withParam(route: string, state: ShotState): string {
89
+ const hash = route.indexOf('#')
90
+ const [path, fragment] = hash < 0 ? [route, ''] : [route.slice(0, hash), route.slice(hash)]
91
+ return `${path}${path.includes('?') ? '&' : '?'}shot-state=${state}${fragment}`
92
+ }
93
+
94
+ /** The rect union of `boxes`, grown by `margin` and clamped to the viewport. */
95
+ export function unionClip(boxes: readonly Box[], margin: number, viewport: Viewport): Box {
96
+ const { width, height } = VIEWPORT_SPECS[viewport]
97
+ const left = Math.max(0, Math.min(...boxes.map((b) => b.x)) - margin)
98
+ const top = Math.max(0, Math.min(...boxes.map((b) => b.y)) - margin)
99
+ const right = Math.min(width, Math.max(...boxes.map((b) => b.x + b.width)) + margin)
100
+ const bottom = Math.min(height, Math.max(...boxes.map((b) => b.y + b.height)) + margin)
101
+ return { x: left, y: top, width: Math.max(1, right - left), height: Math.max(1, bottom - top) }
102
+ }
103
+
104
+ /** One screenshot with the options every shot shares. */
105
+ const snap = (
106
+ target: { screenshot(options: ShotOptions): Promise<unknown> },
107
+ path: string,
108
+ extra: { fullPage?: boolean; clip?: Box } = {},
109
+ ): Promise<unknown> => target.screenshot({ path, animations: 'disabled', caret: 'hide', ...extra })
110
+
111
+ function record(c: Ctx, { name, state, status, file, note }: Outcome): void {
112
+ const { route, scheme, viewport } = c
113
+ c.shots.push({
114
+ route,
115
+ name,
116
+ scheme,
117
+ viewport,
118
+ state,
119
+ file: file ?? null,
120
+ status,
121
+ ...(note ? { note } : {}),
122
+ })
123
+ if (status === 'error')
124
+ c.input.log(`[shot] ${route} ${name} ${scheme}/${viewport}/${state}: ${note}`)
125
+ }
126
+
127
+ async function load(page: PwPage, url: string): Promise<void> {
128
+ await page.goto(url, { waitUntil: 'networkidle' })
129
+ await page.evaluate('document.fonts.ready.then(() => undefined)')
130
+ }
131
+
132
+ const readFacts = (page: PwPage): Promise<PageFacts> =>
133
+ page.evaluate(`(() => ({
134
+ anchors: [...new Set([...document.querySelectorAll('[data-shot]')].map((e) => e.getAttribute('data-shot')).filter(Boolean))],
135
+ declared: [...document.querySelectorAll('[data-shot-states]')].flatMap((e) => (e.getAttribute('data-shot-states') ?? '').split(/\\s+/)).filter(Boolean),
136
+ }))()`)
137
+
138
+ /** Brings the anchor into view; throws when it is absent, hidden or off-screen at this viewport. */
139
+ async function reveal(anchor: PwLocator): Promise<void> {
140
+ if ((await anchor.count()) === 0) throw new Error('anchor not found')
141
+ await anchor.scrollIntoViewIfNeeded()
142
+ if (!(await anchor.isVisible())) throw new Error('anchor is not visible at this viewport')
143
+ }
144
+
145
+ /**
146
+ * Runs one capture and records it. Metrics are taken after the FIRST successful capture of an
147
+ * anchor, whichever state that is, so `--states hover` still yields them.
148
+ */
149
+ async function attempt(
150
+ c: Ctx,
151
+ name: string,
152
+ state: ShotState,
153
+ run: (path: string) => Promise<void>,
154
+ note?: string,
155
+ ): Promise<void> {
156
+ const file = fileName(c.route, name, c.scheme, c.viewport, state)
157
+ try {
158
+ await run(join(c.input.pngDir, file))
159
+ } catch (error) {
160
+ const status = error instanceof NotDeclared ? 'not-declared' : 'error'
161
+ record(c, { name, state, status, note: firstLine(error) })
162
+ return
163
+ }
164
+ // The PNG is good: a measurement failure is recorded beside it, never instead of it.
165
+ let notes = note ? [note] : []
166
+ if (name !== PAGE_ANCHOR && !c.measured.has(name)) {
167
+ try {
168
+ const measure =
169
+ c.input.measure ?? ((a: PwLocator) => a.evaluate(measureAnchor).then(finishMeasurement))
170
+ const m = await measure(anchorOf(c, name))
171
+ c.anchors.push({ route: c.route, name, scheme: c.scheme, viewport: c.viewport, ...m })
172
+ c.measured.add(name)
173
+ } catch (error) {
174
+ notes = [...notes, `metrics unavailable: ${firstLine(error)}`]
175
+ }
176
+ }
177
+ record(c, {
178
+ name,
179
+ state,
180
+ status: 'ok',
181
+ file: `png/${file}`,
182
+ ...(notes.length ? { note: notes.join('; ') } : {}),
183
+ })
184
+ }
185
+
186
+ const skipOnMobile = (c: Ctx, name: string, state: ShotState): boolean => {
187
+ if (c.viewport === 'desktop') return false
188
+ record(c, { name, state, status: 'skipped', note: 'desktop only' })
189
+ return true
190
+ }
191
+
192
+ const restCrop = async (c: Ctx, name: string, path: string): Promise<void> => {
193
+ const anchor = anchorOf(c, name)
194
+ await reveal(anchor)
195
+ await snap(anchor, path)
196
+ }
197
+
198
+ async function captureRest(c: Ctx, name: string): Promise<void> {
199
+ await attempt(c, name, 'rest', (path) => restCrop(c, name, path))
200
+ }
201
+
202
+ /**
203
+ * Runs in the page: forgets the previous marks, then marks every tooltip that is visible now, so
204
+ * a tooltip another component already holds open is never taken for the one a trigger opens.
205
+ */
206
+ export function markVisibleTooltips(): void {
207
+ for (const el of Array.from(document.querySelectorAll('[data-shot-seen]')))
208
+ el.removeAttribute('data-shot-seen')
209
+ for (const el of Array.from(document.querySelectorAll('[role="tooltip"]'))) {
210
+ const rect = el.getBoundingClientRect()
211
+ if (rect.width > 0 && rect.height > 0 && getComputedStyle(el).visibility !== 'hidden')
212
+ el.setAttribute('data-shot-seen', '')
213
+ }
214
+ }
215
+
216
+ /** Runs in the page: the first id a trigger names in `aria-describedby`, looking at it and its descendants. */
217
+ export function describedByOf(el: Element | null): string {
218
+ const named = el?.matches('[aria-describedby]') ? el : el?.querySelector('[aria-describedby]')
219
+ return named?.getAttribute('aria-describedby')?.split(/\s+/)[0] ?? ''
220
+ }
221
+
222
+ /** The tooltip the trigger names, else any that was not already visible at the snapshot. */
223
+ export const tooltipSelector = (describedBy: string): string =>
224
+ describedBy
225
+ ? `[role="tooltip"][id=${JSON.stringify(describedBy)}]`
226
+ : '[role="tooltip"]:not([data-shot-seen])'
227
+
228
+ /**
229
+ * The box of the tooltip an action opened, or null when none shows up. Call `markVisibleTooltips`
230
+ * before the action; `describedBy` is the trigger's own tooltip id, when it has one.
231
+ */
232
+ async function openTooltipBox(
233
+ c: Ctx,
234
+ describedBy: string,
235
+ timeout = TIP_PROBE_MS,
236
+ ): Promise<Box | null> {
237
+ const tip = c.page.locator(tooltipSelector(describedBy)).first()
238
+ try {
239
+ await tip.waitFor({ state: 'visible', timeout })
240
+ } catch {
241
+ return null
242
+ }
243
+ // The tooltip animates in: read its box once two reads agree, or the crop clips the final size.
244
+ let box = await tip.boundingBox()
245
+ for (let i = 0; i < TIP_SETTLE_READS; i++) {
246
+ await new Promise((done) => setTimeout(done, TIP_SETTLE_MS))
247
+ const next = await tip.boundingBox()
248
+ const settled = JSON.stringify(next) === JSON.stringify(box)
249
+ box = next
250
+ if (settled) break
251
+ }
252
+ return box
253
+ }
254
+
255
+ const idOf = (value: unknown): string => (typeof value === 'string' ? value : '')
256
+
257
+ async function captureHover(c: Ctx, name: string): Promise<void> {
258
+ if (skipOnMobile(c, name, 'hover')) return
259
+ await attempt(c, name, 'hover', async (path) => {
260
+ const anchor = anchorOf(c, name)
261
+ await reveal(anchor)
262
+ const inner = c.page.locator(`${sel(name)} [data-shot-hover]`).first()
263
+ const target = (await inner.count()) > 0 ? inner : anchor
264
+ await c.page.evaluate(markVisibleTooltips, undefined)
265
+ await target.hover({ timeout: HOVER_TIMEOUT_MS })
266
+ const describedBy = idOf(await target.evaluate(describedByOf))
267
+ const [box, tip] = [await anchor.boundingBox(), await openTooltipBox(c, describedBy)]
268
+ if (!box || !tip) return void (await snap(anchor, path))
269
+ await snap(c.page, path, { clip: unionClip([box, tip], FOCUS_MARGIN_PX, c.viewport) })
270
+ })
271
+ await c.page.mouse.move(0, 0)
272
+ }
273
+
274
+ /** Sequential focus from the document top until `:focus-visible` lands inside the anchor. */
275
+ async function tabInto(page: PwPage, name: string): Promise<void> {
276
+ await page.evaluate(
277
+ '(() => { document.activeElement?.blur(); window.scrollTo(0, 0); getSelection()?.collapse(document.body, 0) })()',
278
+ )
279
+ const landed = `(() => { const a = document.activeElement; return a != null && a.matches(':focus-visible') && a.closest(${JSON.stringify(sel(name))}) != null })()`
280
+ for (let i = 0; i < TAB_PRESSES; i++) {
281
+ await page.keyboard.press('Tab')
282
+ if (await page.evaluate<boolean>(landed)) return
283
+ }
284
+ throw new Error(`:focus-visible never reached the anchor in ${TAB_PRESSES} Tab presses`)
285
+ }
286
+
287
+ /**
288
+ * True when Tab can reach the anchor or something in it: a link, an enabled control, a `tabindex`
289
+ * ≥ 0 or editable host, outside any `hidden`/`inert` subtree, and actually rendered. Runs in the page, so it is
290
+ * self-contained.
291
+ */
292
+ export function hasFocusTarget(root: Element): boolean {
293
+ const candidates =
294
+ 'a[href], button, input:not([type="hidden"]), select, textarea, summary, [tabindex], [contenteditable=""], [contenteditable="true"]'
295
+ return [root, ...Array.from(root.querySelectorAll(candidates))].some(
296
+ (el) =>
297
+ el.matches(candidates) &&
298
+ !el.matches(':disabled') &&
299
+ !el.getAttribute('tabindex')?.startsWith('-') &&
300
+ el.closest('[hidden], [inert]') === null &&
301
+ (typeof el.checkVisibility === 'function'
302
+ ? el.checkVisibility()
303
+ : el.getClientRects().length > 0) &&
304
+ getComputedStyle(el).visibility !== 'hidden',
305
+ )
306
+ }
307
+
308
+ async function captureFocus(c: Ctx, name: string): Promise<void> {
309
+ await attempt(c, name, 'focus', async (path) => {
310
+ const anchor = anchorOf(c, name)
311
+ if (!(await anchor.evaluate(hasFocusTarget)))
312
+ throw new NotDeclared('no focus target in the anchor')
313
+ await reveal(anchor)
314
+ await c.page.evaluate(markVisibleTooltips, undefined)
315
+ await tabInto(c.page, name)
316
+ const box = await anchor.boundingBox()
317
+ if (!box) throw new Error('anchor has no box')
318
+ const focused = idOf(
319
+ await c.page.evaluate(
320
+ () => document.activeElement?.getAttribute('aria-describedby')?.split(/\s+/)[0] ?? '',
321
+ undefined,
322
+ ),
323
+ )
324
+ const tip = await openTooltipBox(c, focused)
325
+ await snap(c.page, path, {
326
+ clip: unionClip(tip ? [box, tip] : [box], FOCUS_MARGIN_PX, c.viewport),
327
+ })
328
+ })
329
+ await c.page.evaluate('document.activeElement?.blur()')
330
+ }
331
+
332
+ async function captureTooltip(c: Ctx, name: string): Promise<void> {
333
+ if (skipOnMobile(c, name, 'tooltip')) return
334
+ const trigger = c.page.locator(`${sel(name)} [data-shot-tooltip]`).first()
335
+ await attempt(c, name, 'tooltip', async (path) => {
336
+ if ((await trigger.count()) === 0) throw new NotDeclared('no [data-shot-tooltip] in the anchor')
337
+ const anchor = anchorOf(c, name)
338
+ await reveal(anchor)
339
+ await c.page.evaluate(markVisibleTooltips, undefined)
340
+ await trigger.hover({ timeout: HOVER_TIMEOUT_MS })
341
+ const describedBy = idOf(await trigger.evaluate(describedByOf))
342
+ const t = await openTooltipBox(c, describedBy, TOOLTIP_TIMEOUT_MS)
343
+ if (!t) throw new Error('no visible [role="tooltip"] after hover')
344
+ const a = await anchor.boundingBox()
345
+ if (!a) throw new Error('tooltip or anchor has no box')
346
+ await snap(c.page, path, { clip: unionClip([a, t], FOCUS_MARGIN_PX, c.viewport) })
347
+ })
348
+ await c.page.mouse.move(0, 0)
349
+ }
350
+
351
+ const POINTER_STATES = {
352
+ rest: captureRest,
353
+ hover: captureHover,
354
+ focus: captureFocus,
355
+ tooltip: captureTooltip,
356
+ }
357
+
358
+ /** `empty`/`loading`/`error`: reload with `shot-state=<state>`, re-read the anchors, crop each. */
359
+ async function captureUrlState(c: Ctx, state: ShotState): Promise<void> {
360
+ const restNames = c.facts.anchors
361
+ if (!c.facts.declared.includes(state)) {
362
+ for (const name of restNames) {
363
+ record(c, { name, state, status: 'not-declared', note: 'page does not declare this state' })
364
+ }
365
+ return
366
+ }
367
+ let here: PageFacts
368
+ try {
369
+ await load(c.page, c.input.base + withParam(c.route, state))
370
+ here = await readFacts(c.page)
371
+ } catch (error) {
372
+ for (const name of restNames)
373
+ record(c, { name, state, status: 'error', note: `load failed: ${firstLine(error)}` })
374
+ return
375
+ }
376
+ for (const name of new Set([...restNames, ...here.anchors])) {
377
+ if (!here.anchors.includes(name)) {
378
+ record(c, { name, state, status: 'error', note: 'anchor absent in this state' })
379
+ continue
380
+ }
381
+ const note = restNames.includes(name) ? undefined : 'anchor only present in this state'
382
+ await attempt(c, name, state, (path) => restCrop(c, name, path), note)
383
+ }
384
+ }
385
+
386
+ const STEPS = ['xs', 'sm', 'md', 'lg', 'xl', 'default']
387
+
388
+ type Steps = Pick<Scale, 'spacing' | 'radius' | 'fontSizes'>
389
+ type ScaleRead = { mantine: Steps; vx: Record<string, number> }
390
+
391
+ /**
392
+ * Runs in the page: Mantine's steps plus every `--vx-space-*`, `--vx-text-*` and `--vx-radius-*`
393
+ * custom property declared by ANY style rule (the root's and each component's own), resolved to px
394
+ * through a probe's `width` so `calc()`/`rem` read as the page sees them. Self-contained: it is
395
+ * serialised into the page.
396
+ */
397
+ export function readScaleInPage(steps: string[]): ScaleRead {
398
+ const probe = document.createElement('div')
399
+ probe.style.cssText = 'position:absolute;visibility:hidden'
400
+ document.body.append(probe)
401
+ const root = getComputedStyle(document.documentElement)
402
+ const px = (width: string): number | undefined => {
403
+ probe.style.width = ''
404
+ probe.style.width = width
405
+ const value = parseFloat(getComputedStyle(probe).width)
406
+ return Number.isFinite(value) ? Math.round(value * 100) / 100 : undefined
407
+ }
408
+ const read = (prefix: string): Record<string, number> => {
409
+ const out: Record<string, number> = {}
410
+ for (const key of steps) {
411
+ const name = prefix + key
412
+ const value = root.getPropertyValue(name).trim() ? px(`var(${name})`) : undefined
413
+ if (value !== undefined) out[key] = value
414
+ }
415
+ return out
416
+ }
417
+ const declared = new Map<string, string>()
418
+ const walk = (rules: CSSRuleList): void => {
419
+ for (const rule of Array.from(rules)) {
420
+ if ('cssRules' in rule) walk((rule as CSSGroupingRule).cssRules)
421
+ const style = (rule as CSSStyleRule).style
422
+ if (!style) continue
423
+ for (const name of Array.from(style)) {
424
+ if (/^--vx-(space|text|radius)-/.test(name))
425
+ declared.set(name, style.getPropertyValue(name).trim())
426
+ }
427
+ }
428
+ }
429
+ try {
430
+ for (const sheet of Array.from(document.styleSheets)) {
431
+ try {
432
+ walk(sheet.cssRules)
433
+ } catch {
434
+ // A cross-origin stylesheet's rules throw SecurityError: its tokens are not ours to read.
435
+ }
436
+ }
437
+ const vx: Record<string, number> = {}
438
+ for (const [name, value] of declared) {
439
+ // A token set on the root resolves through the cascade; a component-scoped one only by its text.
440
+ const resolved = root.getPropertyValue(name).trim() ? px(`var(${name})`) : px(value)
441
+ if (resolved !== undefined) vx[name] = resolved
442
+ }
443
+ return {
444
+ mantine: {
445
+ spacing: read('--mantine-spacing-'),
446
+ radius: read('--mantine-radius-'),
447
+ fontSizes: read('--mantine-font-size-'),
448
+ },
449
+ vx,
450
+ }
451
+ } finally {
452
+ probe.remove()
453
+ }
454
+ }
455
+
456
+ /** Sorts the page's `--vx-*` readings into the three kinds; a step of 0 px (or an unresolvable one) is not a step. */
457
+ export function groupScale({ mantine, vx }: ScaleRead): Steps {
458
+ const pick = (kind: string): Record<string, number> =>
459
+ Object.fromEntries(
460
+ Object.entries(vx)
461
+ .filter(([name, value]) => name.startsWith(`--vx-${kind}-`) && value > 0)
462
+ .map(([name, value]) => [name.slice(2), value]),
463
+ )
464
+ return {
465
+ spacing: { ...mantine.spacing, ...pick('space') },
466
+ radius: { ...mantine.radius, ...pick('radius') },
467
+ fontSizes: { ...mantine.fontSizes, ...pick('text') },
468
+ }
469
+ }
470
+
471
+ async function capturePage(
472
+ args: Omit<Ctx, 'facts' | 'anchors' | 'shots' | 'measured'> & { wantScale: boolean },
473
+ ) {
474
+ const { wantScale, ...rest } = args
475
+ const c: Ctx = {
476
+ ...rest,
477
+ facts: { anchors: [], declared: [] },
478
+ anchors: [],
479
+ shots: [],
480
+ measured: new Set(),
481
+ }
482
+ const { input, route } = c
483
+ try {
484
+ await load(c.page, input.base + route)
485
+ c.facts = await readFacts(c.page)
486
+ } catch (error) {
487
+ record(c, {
488
+ name: PAGE_ANCHOR,
489
+ state: 'rest',
490
+ status: 'error',
491
+ note: `load failed: ${firstLine(error)}`,
492
+ })
493
+ return c
494
+ }
495
+ if (wantScale) {
496
+ try {
497
+ c.scale = groupScale(await c.page.evaluate(readScaleInPage, STEPS))
498
+ } catch (error) {
499
+ c.scaleError = firstLine(error)
500
+ }
501
+ }
502
+ const usable = c.facts.anchors.filter((n) => slug(n) !== '' && n !== PAGE_ANCHOR)
503
+ for (const name of c.facts.anchors.filter((n) => !usable.includes(n))) {
504
+ record(c, { name, state: 'rest', status: 'error', note: 'unusable data-shot name' })
505
+ }
506
+ c.facts.anchors = usable
507
+ if (usable.length === 0 && c.scheme === 'light' && c.viewport === 'desktop') {
508
+ input.log(`[shot] no data-shot anchors on ${route}`)
509
+ }
510
+ if (input.states.includes('rest')) {
511
+ await attempt(c, PAGE_ANCHOR, 'rest', (path) =>
512
+ snap(c.page, path, { fullPage: true }).then(() => undefined),
513
+ )
514
+ }
515
+ for (const name of usable) {
516
+ for (const [state, capture] of Object.entries(POINTER_STATES)) {
517
+ if (input.states.includes(state as ShotState)) await capture(c, name)
518
+ }
519
+ }
520
+ for (const state of URL_STATES) if (input.states.includes(state)) await captureUrlState(c, state)
521
+ return c
522
+ }
523
+
524
+ /** A fresh context for one scheme × viewport: the colour scheme is set on the context AND in storage before load. */
525
+ export async function openContext<C extends PwContext>(
526
+ browser: PwBrowser<C>,
527
+ scheme: Scheme,
528
+ viewport: Viewport,
529
+ ): Promise<C> {
530
+ const spec = VIEWPORT_SPECS[viewport]
531
+ const context = await browser.newContext({
532
+ viewport: { width: spec.width, height: spec.height },
533
+ deviceScaleFactor: 1,
534
+ isMobile: spec.mobile,
535
+ hasTouch: spec.mobile,
536
+ colorScheme: scheme,
537
+ reducedMotion: 'reduce',
538
+ })
539
+ await context.addInitScript(`localStorage.setItem('mantine-color-scheme-value', '${scheme}')`)
540
+ return context
541
+ }
542
+
543
+ const SHEET_WIDTH_PX = 2000
544
+
545
+ /** `<route>-<hash>__<name>-<hash>__sheet.png`: one contact sheet per anchor, beside its crops. */
546
+ export const sheetName = (route: string, name: string): string =>
547
+ `${slug(route) || 'root'}-${hash(route)}__${slug(name)}-${hash(name)}__sheet.png`
548
+
549
+ const dataUri = (path: string): string =>
550
+ `data:image/png;base64,${readFileSync(path).toString('base64')}`
551
+
552
+ /**
553
+ * One contact sheet per anchor: the board's section for it (every state × scheme × viewport,
554
+ * labelled), rendered in the open browser from the crops already on disk and screenshot whole. A
555
+ * failed sheet is logged and left unlisted — the reviewer treats an anchor without one as unverified.
556
+ */
557
+ async function writeSheets(
558
+ input: CaptureInput,
559
+ out: { anchors: AnchorMetrics[]; shots: ShotRecord[] },
560
+ ): Promise<void> {
561
+ const targets = new Map<string, { route: string; name: string }>()
562
+ for (const s of out.shots) {
563
+ if (s.name !== PAGE_ANCHOR)
564
+ targets.set(`${s.route}\0${s.name}`, { route: s.route, name: s.name })
565
+ }
566
+ if (targets.size === 0) return
567
+ const context = await input.browser.newContext({
568
+ viewport: { width: SHEET_WIDTH_PX, height: 1000 },
569
+ deviceScaleFactor: 1,
570
+ isMobile: false,
571
+ hasTouch: false,
572
+ colorScheme: 'light',
573
+ reducedMotion: 'reduce',
574
+ })
575
+ try {
576
+ const page = await context.newPage()
577
+ for (const { route, name } of targets.values()) {
578
+ try {
579
+ const shots = out.shots
580
+ .filter((s) => s.route === route && s.name === name)
581
+ .map((s) =>
582
+ s.status === 'ok' && s.file
583
+ ? { ...s, file: dataUri(join(input.pngDir, basename(s.file))) }
584
+ : s,
585
+ )
586
+ await page.setContent(buildSheet(route, name, input.states, shots), { waitUntil: 'load' })
587
+ const file = sheetName(route, name)
588
+ await snap(page, join(input.pngDir, file), { fullPage: true })
589
+ for (const a of out.anchors) {
590
+ if (a.route === route && a.name === name) a.sheet = `png/${file}`
591
+ }
592
+ } catch (error) {
593
+ input.log(`[shot] ${route} ${name}: sheet not written: ${firstLine(error)}`)
594
+ }
595
+ }
596
+ } finally {
597
+ await context.close().catch(() => undefined)
598
+ }
599
+ }
600
+
601
+ export async function capture(input: CaptureInput): Promise<{
602
+ anchors: AnchorMetrics[]
603
+ shots: ShotRecord[]
604
+ scale: Scale[]
605
+ scaleError?: string
606
+ }> {
607
+ const out = {
608
+ anchors: [] as AnchorMetrics[],
609
+ shots: [] as ShotRecord[],
610
+ scale: [] as Scale[],
611
+ scaleError: undefined as string | undefined,
612
+ }
613
+ for (const scheme of SCHEMES) {
614
+ for (const viewport of VIEWPORTS) {
615
+ const context = await openContext(input.browser, scheme, viewport)
616
+ try {
617
+ const page = await context.newPage()
618
+ page.setDefaultTimeout(NAV_TIMEOUT_MS)
619
+ let scaled = false
620
+ for (const route of input.routes) {
621
+ const done = await capturePage({
622
+ page,
623
+ input,
624
+ route,
625
+ scheme,
626
+ viewport,
627
+ wantScale: !scaled,
628
+ })
629
+ if (done.scale) {
630
+ out.scale.push({ scheme, viewport, ...done.scale })
631
+ scaled = true
632
+ }
633
+ if (done.scaleError) out.scaleError = out.scaleError ?? done.scaleError
634
+ out.anchors.push(...done.anchors)
635
+ out.shots.push(...done.shots)
636
+ }
637
+ } finally {
638
+ await context.close().catch(() => undefined)
639
+ }
640
+ }
641
+ }
642
+ await writeSheets(input, out).catch((error: unknown) =>
643
+ input.log(`[shot] contact sheets not written: ${firstLine(error)}`),
644
+ )
645
+ // A scale that was read at all is a scale: the error is only for one that never was.
646
+ const { anchors, shots, scale } = out
647
+ if (scale.length > 0 || out.scaleError === undefined) return { anchors, shots, scale }
648
+ input.log(`[shot] scale unavailable: ${out.scaleError}`)
649
+ return { anchors, shots, scale, scaleError: out.scaleError }
650
+ }