basalt-ui 2.14.0 → 2.16.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 (134) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/MIGRATING.md +81 -13
  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 +2 -3
  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/card-inset.test.ts +57 -0
  13. package/configs/oxlint-basalt.json +1 -1
  14. package/configs/oxlint-plugin.js +81 -20
  15. package/configs/oxlint-plugin.test.ts +85 -6
  16. package/dist/agent/chat/thread-message.js +1 -1
  17. package/dist/agent/chat/thread-outcome-card.js +1 -1
  18. package/dist/charts/ChartCard.js +1 -1
  19. package/dist/charts/chart-card.module.css +2 -2
  20. package/dist/charts/legend.d.ts +4 -4
  21. package/dist/cli/board-freshness.d.ts +25 -0
  22. package/dist/cli/board-freshness.d.ts.map +1 -0
  23. package/dist/cli/board-freshness.js +88 -0
  24. package/dist/cli/doctor.d.ts +2 -1
  25. package/dist/cli/doctor.d.ts.map +1 -1
  26. package/dist/cli/doctor.js +3 -1
  27. package/dist/cli/help.d.ts.map +1 -1
  28. package/dist/cli/help.js +9 -3
  29. package/dist/cli/index.d.ts +15 -1
  30. package/dist/cli/index.d.ts.map +1 -1
  31. package/dist/cli/index.js +57 -7
  32. package/dist/cli/init.d.ts.map +1 -1
  33. package/dist/cli/init.js +6 -1
  34. package/dist/cli/shot/board.d.ts +5 -0
  35. package/dist/cli/shot/board.d.ts.map +1 -0
  36. package/dist/cli/shot/board.js +96 -0
  37. package/dist/cli/shot/capture.d.ts +59 -0
  38. package/dist/cli/shot/capture.d.ts.map +1 -0
  39. package/dist/cli/shot/capture.js +473 -0
  40. package/dist/cli/shot/index.d.ts +45 -0
  41. package/dist/cli/shot/index.d.ts.map +1 -0
  42. package/dist/cli/shot/index.js +289 -0
  43. package/dist/cli/shot/measure.d.ts +47 -0
  44. package/dist/cli/shot/measure.d.ts.map +1 -0
  45. package/dist/cli/shot/measure.js +191 -0
  46. package/dist/cli/shot/playwright.d.ts +101 -0
  47. package/dist/cli/shot/playwright.d.ts.map +1 -0
  48. package/dist/cli/shot/playwright.js +60 -0
  49. package/dist/cli/shot/serve.d.ts +6 -0
  50. package/dist/cli/shot/serve.d.ts.map +1 -0
  51. package/dist/cli/shot/serve.js +33 -0
  52. package/dist/cli/shot/types.d.ts +98 -0
  53. package/dist/cli/shot/types.d.ts.map +1 -0
  54. package/dist/cli/shot/types.js +17 -0
  55. package/dist/cli/sync.d.ts.map +1 -1
  56. package/dist/cli/sync.js +2 -1
  57. package/dist/dashboard/settings-section.d.ts.map +1 -1
  58. package/dist/dashboard/settings-section.js +5 -2
  59. package/dist/dashboard/stat-card.js +12 -12
  60. package/dist/dashboard/stat-card.module.css +4 -4
  61. package/dist/dashboard/widget-header.module.css +3 -3
  62. package/dist/guard/guard-hook.d.ts.map +1 -1
  63. package/dist/guard/index.d.ts +4 -2
  64. package/dist/guard/index.d.ts.map +1 -1
  65. package/dist/guard/index.js +18 -4
  66. package/dist/guard/vx-names.d.ts.map +1 -1
  67. package/dist/guard/vx-names.js +1 -0
  68. package/dist/shell/app-mobile-nav.module.css +2 -2
  69. package/dist/shell/app-sidebar-account.js +1 -1
  70. package/dist/shell/app-sidebar.js +2 -2
  71. package/dist/shell/app-sidebar.module.css +8 -8
  72. package/dist/shell/index.js +5 -1
  73. package/dist/shell/page-bar.js +1 -1
  74. package/dist/surfaces.d.ts +2 -0
  75. package/dist/surfaces.d.ts.map +1 -1
  76. package/dist/surfaces.js +2 -0
  77. package/dist/table/data-table.d.ts.map +1 -1
  78. package/dist/table/data-table.js +3 -0
  79. package/dist/theme/index.d.ts.map +1 -1
  80. package/dist/theme/index.js +31 -21
  81. package/dist/tokens/core.d.ts +10 -4
  82. package/dist/tokens/core.d.ts.map +1 -1
  83. package/dist/tokens/core.js +16 -10
  84. package/dist/tokens/ctl-vars.d.ts +15 -0
  85. package/dist/tokens/ctl-vars.d.ts.map +1 -0
  86. package/dist/tokens/ctl-vars.js +22 -0
  87. package/dist/tokens/palette.d.ts +37 -29
  88. package/dist/tokens/palette.d.ts.map +1 -1
  89. package/dist/tokens/palette.js +32 -21
  90. package/dist/tokens/space-scale.d.ts +14 -0
  91. package/dist/tokens/space-scale.d.ts.map +1 -0
  92. package/dist/tokens/space-scale.js +10 -0
  93. package/llms.txt +2 -2
  94. package/package.json +1 -1
  95. package/src/agent/chat/thread-message.tsx +1 -1
  96. package/src/agent/chat/thread-outcome-card.tsx +2 -2
  97. package/src/charts/ChartCard.tsx +1 -1
  98. package/src/charts/chart-card.module.css +2 -2
  99. package/src/charts/legend.tsx +4 -4
  100. package/src/cli/board-freshness.ts +132 -0
  101. package/src/cli/doctor.ts +10 -1
  102. package/src/cli/help.ts +14 -2
  103. package/src/cli/index.ts +80 -10
  104. package/src/cli/init.ts +8 -1
  105. package/src/cli/shot/board.ts +154 -0
  106. package/src/cli/shot/capture.ts +650 -0
  107. package/src/cli/shot/index.ts +362 -0
  108. package/src/cli/shot/measure.ts +252 -0
  109. package/src/cli/shot/playwright.ts +152 -0
  110. package/src/cli/shot/serve.ts +35 -0
  111. package/src/cli/shot/types.ts +92 -0
  112. package/src/cli/sync.ts +2 -1
  113. package/src/dashboard/settings-section.tsx +5 -2
  114. package/src/dashboard/stat-card.module.css +4 -4
  115. package/src/dashboard/stat-card.tsx +13 -13
  116. package/src/dashboard/widget-header.module.css +3 -3
  117. package/src/guard/guard-hook.ts +3 -1
  118. package/src/guard/index.ts +27 -13
  119. package/src/guard/vx-names.ts +1 -0
  120. package/src/shell/app-mobile-nav.module.css +2 -2
  121. package/src/shell/app-sidebar-account.tsx +1 -1
  122. package/src/shell/app-sidebar.module.css +8 -8
  123. package/src/shell/app-sidebar.tsx +2 -2
  124. package/src/shell/index.tsx +10 -4
  125. package/src/shell/page-bar.tsx +1 -1
  126. package/src/surfaces.ts +5 -0
  127. package/src/table/data-table.tsx +10 -4
  128. package/src/theme/__snapshots__/plain-theme.test.ts.snap +57 -45
  129. package/src/theme/ctl-theme.tsx +1 -1
  130. package/src/theme/index.ts +43 -23
  131. package/src/tokens/core.ts +16 -8
  132. package/src/tokens/ctl-vars.ts +32 -0
  133. package/src/tokens/palette.ts +40 -29
  134. package/src/tokens/space-scale.ts +13 -0
@@ -0,0 +1,362 @@
1
+ /**
2
+ * `basalt-ui shot <route…> (--base <url> | --dist <dir>) [--out <dir>] [--states <list>]` — render
3
+ * routes in a real browser and write `board.html`, `metrics.json` and `png/*` for a design round.
4
+ */
5
+ import {
6
+ lstatSync,
7
+ mkdirSync,
8
+ mkdtempSync,
9
+ readFileSync,
10
+ readdirSync,
11
+ realpathSync,
12
+ renameSync,
13
+ rmSync,
14
+ statSync,
15
+ writeFileSync,
16
+ } from 'node:fs'
17
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
18
+ import { parseArgs } from 'node:util'
19
+
20
+ import { buildBoard } from './board'
21
+ import { capture } from './capture'
22
+ import { INSTALL_LINE, ShotError, resolvePlaywright, withBrowser } from './playwright'
23
+ import type { Playwright, PlaywrightResolver } from './playwright'
24
+ import { serveDist } from './serve'
25
+ import { SCHEMES, STATES, VIEWPORTS } from './types'
26
+ import type { ShotMetrics, ShotState } from './types'
27
+
28
+ const HOME = '.basalt/shots'
29
+ /** A run dir under the home, so `last.json` and a named run's dir never share the default out. */
30
+ const DEFAULT_OUT = `${HOME}/latest`
31
+ const USAGE_LINE =
32
+ 'usage: basalt-ui shot <route…> (--base <url> | --dist <dir>) [--out <dir>] [--states <list>]'
33
+
34
+ export type ShotDeps = {
35
+ resolve?: PlaywrightResolver
36
+ /** Replaces the browser run (tests): returns what `capture` would. */
37
+ capture?: typeof capture
38
+ now?: () => Date
39
+ log?: (line: string) => void
40
+ }
41
+
42
+ export type ShotArgs = {
43
+ routes: string[]
44
+ base?: string
45
+ dist?: string
46
+ out: string
47
+ states: ShotState[]
48
+ }
49
+
50
+ /** Parses argv; throws `ShotError` with the one-line reason. */
51
+ export function parseShotArgs(flags: readonly string[]): ShotArgs {
52
+ let parsed
53
+ try {
54
+ parsed = parseArgs({
55
+ args: [...flags],
56
+ allowPositionals: true,
57
+ options: {
58
+ base: { type: 'string' },
59
+ dist: { type: 'string' },
60
+ out: { type: 'string' },
61
+ states: { type: 'string' },
62
+ },
63
+ })
64
+ } catch (error) {
65
+ throw new ShotError(`${error instanceof Error ? error.message : String(error)}\n${USAGE_LINE}`)
66
+ }
67
+ const { values, positionals } = parsed
68
+ if (values.base) sanitizeBase(values.base)
69
+ if (positionals.length === 0) throw new ShotError(`no route given.\n${USAGE_LINE}`)
70
+ const bad = positionals.find((r) => !r.startsWith('/'))
71
+ if (bad) throw new ShotError(`route '${bad}' must start with '/'.\n${USAGE_LINE}`)
72
+ if (Boolean(values.base) === Boolean(values.dist)) {
73
+ throw new ShotError(`pass exactly one of --base <url> or --dist <dir>.\n${USAGE_LINE}`)
74
+ }
75
+ const states = values.states
76
+ ? values.states
77
+ .split(',')
78
+ .map((s) => s.trim())
79
+ .filter(Boolean)
80
+ : [...STATES]
81
+ const unknown = states.find((s) => !(STATES as readonly string[]).includes(s))
82
+ if (unknown) throw new ShotError(`unknown state '${unknown}'. Known: ${STATES.join(', ')}`)
83
+ return {
84
+ routes: positionals,
85
+ ...(values.base ? { base: values.base.replace(/\/+$/, '') } : {}),
86
+ ...(values.dist ? { dist: values.dist } : {}),
87
+ out: values.out ?? DEFAULT_OUT,
88
+ states: STATES.filter((s) => states.includes(s)),
89
+ }
90
+ }
91
+
92
+ const PROTECTED_SEGMENTS = new Set(['.git', 'node_modules'])
93
+ /** What a shot writes into its out dir: only a dir made of these is ever emptied. */
94
+ const SHOT_OWNED = new Set(['png', 'board.html', 'metrics.json', '.gitignore'])
95
+
96
+ const outside = (rel: string): boolean =>
97
+ rel === '..' || rel.startsWith('..' + sep) || isAbsolute(rel)
98
+
99
+ const lexists = (path: string): boolean => {
100
+ try {
101
+ lstatSync(path)
102
+ return true
103
+ } catch {
104
+ return false
105
+ }
106
+ }
107
+
108
+ /** A previous render: `metrics.json` (`version: 1`) and nothing but shot-owned entries. */
109
+ const isPreviousShot = (dir: string): boolean => {
110
+ try {
111
+ const marker = JSON.parse(readFileSync(join(dir, 'metrics.json'), 'utf8')) as {
112
+ version?: unknown
113
+ }
114
+ const png = join(dir, 'png')
115
+ return (
116
+ marker.version === 1 &&
117
+ readdirSync(dir).every((e) => SHOT_OWNED.has(e)) &&
118
+ (!lexists(png) || (lstatSync(png).isDirectory() && !lstatSync(png).isSymbolicLink()))
119
+ )
120
+ } catch {
121
+ return false
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Validates `out` WITHOUT touching it and returns its absolute path. A shot only ever empties what
127
+ * it wrote: the dir must be absent, empty, or hold a previous run's `metrics.json` (`version: 1`).
128
+ */
129
+ export function planOut(cwd: string, out: string): string {
130
+ const dir = resolve(cwd, out)
131
+ const rel = relative(cwd, dir)
132
+ const refuse = (why: string): never => {
133
+ throw new ShotError(`--out ${out} ${why}`)
134
+ }
135
+ if (rel === '' || outside(rel)) refuse('must be a directory inside the project')
136
+ if (relative(join(cwd, HOME), dir) === '')
137
+ refuse('is the shot home (holds last.json); use a subdirectory')
138
+ if (rel === '.basalt' || rel.split(sep).some((part) => PROTECTED_SEGMENTS.has(part))) {
139
+ refuse('is (or sits inside) a protected directory (.git, node_modules, .basalt)')
140
+ }
141
+ let probe = dir
142
+ while (!lexists(probe)) probe = dirname(probe)
143
+ if (probe === dir && lstatSync(dir).isSymbolicLink())
144
+ refuse('is a symlink; refusing to follow it')
145
+ let real = ''
146
+ try {
147
+ real = realpathSync(probe)
148
+ } catch {
149
+ refuse('sits behind a dangling symlink')
150
+ }
151
+ if (outside(relative(realpathSync(cwd), real))) refuse('resolves outside the project')
152
+ if (probe === dir) {
153
+ if (!statSync(dir).isDirectory()) refuse('exists and is not a directory')
154
+ if (readdirSync(dir).length > 0 && !isPreviousShot(dir)) {
155
+ refuse(
156
+ 'exists and is not purely a previous shot output (metrics.json version 1 plus png/, board.html, .gitignore); refusing to empty it',
157
+ )
158
+ }
159
+ }
160
+ return dir
161
+ }
162
+
163
+ /** `--base` as recorded: origin and path only, never credentials, query or fragment. */
164
+ export function sanitizeBase(base: string): string {
165
+ try {
166
+ const url = new URL(base)
167
+ return `${url.origin}${url.pathname}`.replace(/\/+$/, '')
168
+ } catch {
169
+ throw new ShotError(`--base ${base} is not a URL`)
170
+ }
171
+ }
172
+
173
+ const STALE_TMP_MS = 60 * 60 * 1000
174
+
175
+ /** A pid is alive when signal 0 reaches it (EPERM: it exists, we just may not signal it). */
176
+ function pidAlive(pid: number): boolean {
177
+ try {
178
+ process.kill(pid, 0)
179
+ return true
180
+ } catch (error) {
181
+ return (error as NodeJS.ErrnoException).code === 'EPERM'
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Removes `<home>/tmp-<pid>-*` render dirs a killed run left behind: older than an hour AND owned
187
+ * by a pid that is gone (a name without a pid, from an older run, goes by age alone). Never follows
188
+ * a symlink, and an entry that vanishes, dangles or is a plain file is skipped, never fatal.
189
+ */
190
+ export function sweepStaleTmp(
191
+ home: string,
192
+ now: Date,
193
+ alive: (pid: number) => boolean = pidAlive,
194
+ ): void {
195
+ let entries: string[]
196
+ try {
197
+ entries = readdirSync(home)
198
+ } catch {
199
+ return
200
+ }
201
+ for (const entry of entries) {
202
+ if (!entry.startsWith('tmp-')) continue
203
+ const path = join(home, entry)
204
+ try {
205
+ const stat = lstatSync(path)
206
+ if (!stat.isDirectory() || now.getTime() - stat.mtimeMs <= STALE_TMP_MS) continue
207
+ const pid = /^tmp-(\d+)-/.exec(entry)?.[1]
208
+ if (pid !== undefined && alive(Number(pid))) continue
209
+ rmSync(path, { recursive: true, force: true })
210
+ } catch {
211
+ // Gone already, or not ours to remove: the next run tries again.
212
+ }
213
+ }
214
+ }
215
+
216
+ /** An out dir moved aside while a swap ran. */
217
+ const asideOf = (dir: string): string => `${dir}.prev`
218
+
219
+ /** A swap killed between its two renames leaves `<out>.prev` and no `<out>`: put it back. */
220
+ export function recoverOut(dir: string): void {
221
+ if (lexists(asideOf(dir)) && !lexists(dir)) renameSync(asideOf(dir), dir)
222
+ }
223
+
224
+ /**
225
+ * Swaps the finished `tmp` render in for `out` (re-validated): old aside, new in, aside removed —
226
+ * a failure between the renames restores the old render. `last.json` is written last.
227
+ */
228
+ export function commitOut(
229
+ cwd: string,
230
+ out: string,
231
+ tmp: string,
232
+ routes: readonly string[],
233
+ now: Date,
234
+ ): void {
235
+ const dir = planOut(cwd, out)
236
+ const aside = asideOf(dir)
237
+ if (lexists(aside)) {
238
+ if (!isPreviousShot(aside))
239
+ throw new ShotError(`${relative(cwd, aside)} exists and is not a previous shot output`)
240
+ rmSync(aside, { recursive: true, force: true })
241
+ }
242
+ mkdirSync(dirname(dir), { recursive: true })
243
+ const hadOld = lexists(dir)
244
+ if (hadOld) renameSync(dir, aside)
245
+ try {
246
+ renameSync(tmp, dir)
247
+ } catch (error) {
248
+ if (hadOld) renameSync(aside, dir)
249
+ throw error
250
+ }
251
+ if (hadOld) rmSync(aside, { recursive: true, force: true })
252
+ const home = join(cwd, HOME)
253
+ mkdirSync(home, { recursive: true })
254
+ writeFileSync(join(home, '.gitignore'), '*\n')
255
+ const rel = relative(cwd, dir).split(sep).join('/')
256
+ writeFileSync(
257
+ join(home, 'last.json'),
258
+ JSON.stringify({ version: 1, at: now.toISOString(), out: rel, routes }, null, 2) + '\n',
259
+ )
260
+ }
261
+
262
+ /** One handler for SIGINT/SIGTERM: runs every stop (browser kill, server stop, temp cleanup), then exits. */
263
+ function exitOnSignal(stops: readonly (() => unknown)[]): () => void {
264
+ const exitWith = (code: number) => (): void => {
265
+ void Promise.allSettled(stops.map((stop) => stop())).finally(() => process.exit(code))
266
+ }
267
+ const [onInt, onTerm] = [exitWith(130), exitWith(143)]
268
+ // The Bun/Node typings disagree on the signal overloads; the events are plain EventEmitter ones.
269
+ const events: NodeJS.EventEmitter = process
270
+ events.once('SIGINT', onInt)
271
+ events.once('SIGTERM', onTerm)
272
+ return () => {
273
+ events.removeListener('SIGINT', onInt)
274
+ events.removeListener('SIGTERM', onTerm)
275
+ }
276
+ }
277
+
278
+ export async function shot(
279
+ flags: readonly string[],
280
+ cwd: string,
281
+ deps: ShotDeps = {},
282
+ ): Promise<number> {
283
+ const log = deps.log ?? ((line: string) => console.log(line))
284
+ const stops: (() => unknown)[] = []
285
+ const uninstall = exitOnSignal(stops)
286
+ try {
287
+ const args = parseShotArgs(flags)
288
+ const outDir = planOut(cwd, args.out)
289
+ recoverOut(outDir)
290
+ const pw: Playwright | null = (deps.resolve ?? resolvePlaywright)(cwd)
291
+ if (!pw) throw new ShotError(INSTALL_LINE)
292
+ const now = (deps.now ?? (() => new Date()))()
293
+ sweepStaleTmp(join(cwd, HOME), now)
294
+ const server = args.dist ? serveDist(resolve(cwd, args.dist)) : null
295
+ if (server) stops.push(server.stop)
296
+ let tmp = ''
297
+ stops.push(() => tmp && rmSync(tmp, { recursive: true, force: true }))
298
+ const base = server?.origin ?? args.base ?? ''
299
+ try {
300
+ // The browser is up BEFORE the out dir is touched: a failed launch leaves the last board intact.
301
+ const { anchors, shots, scale, scaleError } = await withBrowser(
302
+ pw,
303
+ (browser) => {
304
+ const home = join(cwd, HOME)
305
+ mkdirSync(home, { recursive: true })
306
+ writeFileSync(join(home, '.gitignore'), '*\n')
307
+ tmp = mkdtempSync(join(home, `tmp-${process.pid}-`))
308
+ mkdirSync(join(tmp, 'png'))
309
+ writeFileSync(join(tmp, '.gitignore'), '*\n')
310
+ return (deps.capture ?? capture)({
311
+ browser,
312
+ base,
313
+ routes: args.routes,
314
+ states: args.states,
315
+ pngDir: join(tmp, 'png'),
316
+ log,
317
+ })
318
+ },
319
+ { stops },
320
+ )
321
+ const metrics: ShotMetrics = {
322
+ version: 1,
323
+ generatedAt: now.toISOString(),
324
+ base: sanitizeBase(base),
325
+ routes: args.routes,
326
+ viewports: [...VIEWPORTS],
327
+ schemes: [...SCHEMES],
328
+ states: args.states,
329
+ scale,
330
+ ...(scaleError ? { scaleError } : {}),
331
+ anchors,
332
+ shots,
333
+ }
334
+ writeFileSync(join(tmp, 'metrics.json'), JSON.stringify(metrics, null, 2) + '\n')
335
+ writeFileSync(join(tmp, 'board.html'), buildBoard(metrics))
336
+ commitOut(cwd, args.out, tmp, args.routes, now)
337
+ const count = (status: string): number => shots.filter((s) => s.status === status).length
338
+ log(
339
+ `[shot] ${count('ok')} shots, ${count('not-declared')} not declared, ${count('skipped')} skipped, ${count('error')} failed → ${relative(cwd, outDir)}/board.html`,
340
+ )
341
+ if (count('error') > 0) {
342
+ console.error(`basalt-ui shot: ${count('error')} shot(s) failed; see board.html`)
343
+ return 1
344
+ }
345
+ return count('ok') === 0 ? 1 : 0
346
+ } finally {
347
+ if (tmp) rmSync(tmp, { recursive: true, force: true })
348
+ server?.stop()
349
+ }
350
+ } catch (error) {
351
+ if (!(error instanceof ShotError)) throw error
352
+ console.error(error.message)
353
+ return 1
354
+ } finally {
355
+ uninstall()
356
+ }
357
+ }
358
+
359
+ export { openContext } from './capture'
360
+ export { INSTALL_LINE, resolvePlaywright, withBrowser } from './playwright'
361
+ export { serveDist } from './serve'
362
+ export { VIEWPORT_SPECS } from './types'
@@ -0,0 +1,252 @@
1
+ // theme-allow-file raw-hex — canvas colour parsing and sRGB readings, not styling
2
+ // theme-allow-file raw-color-fn — reads the page's computed colours, never styles with them
3
+ /**
4
+ * `measureAnchor` runs in the page (Playwright sends its source: it must close over nothing) and
5
+ * returns raw readings; the contrast maths runs here in Node, where it is unit-testable.
6
+ */
7
+ import type { ContrastFailure, Measurement } from './types'
8
+
9
+ const linear = (v: number | undefined): number => {
10
+ const s = (v ?? 0) / 255
11
+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4
12
+ }
13
+ const luminance = (c: readonly number[]): number =>
14
+ 0.2126 * linear(c[0]) + 0.7152 * linear(c[1]) + 0.0722 * linear(c[2])
15
+
16
+ /** WCAG contrast ratio of two sRGB colours (channels 0–255). */
17
+ export function contrastRatio(a: readonly number[], b: readonly number[]): number {
18
+ const [hi, lo] = [luminance(a), luminance(b)].toSorted((x, y) => y - x)
19
+ return ((hi ?? 0) + 0.05) / ((lo ?? 0) + 0.05)
20
+ }
21
+
22
+ /** 3 for large text (≥ 24px, or ≥ 18.66px bold), else 4.5. */
23
+ export function contrastThreshold(fontSize: number, bold: boolean): number {
24
+ return fontSize >= 24 || (bold && fontSize >= 18.66) ? 3 : 4.5
25
+ }
26
+
27
+ export type TextReading = {
28
+ text: string
29
+ fg: number[]
30
+ bg: number[]
31
+ fontSize: number
32
+ bold: boolean
33
+ /** No opaque ancestor background was found: `bg` is white by assumption. */
34
+ assumedWhite: boolean
35
+ }
36
+ /** A computed `border-top-left-radius` as the page read it, with the box it rounds. */
37
+ export type RawRadius = { value: string; width: number; height: number }
38
+ export type Reading = Omit<Measurement, 'contrast' | 'radius' | 'nested'> & {
39
+ radius: RawRadius
40
+ nested: { path: string; radius: RawRadius; padding: Measurement['padding'] }[]
41
+ texts: TextReading[]
42
+ }
43
+
44
+ /**
45
+ * A radius in px, or `'full'` when it rounds the box completely: a percentage of 50 or more
46
+ * (`50%` is a circle/pill however the box is shaped), or a px radius of at least half the shorter
47
+ * side (`9999px`). A zero-size box has nothing to round: 0. A smaller percentage stays a number,
48
+ * resolved against the shorter side — the radius a reader sees on a wide, short box.
49
+ */
50
+ export function radiusReading({ value, width, height }: RawRadius): number | 'full' {
51
+ const first = value.trim()
52
+ const n = Number.parseFloat(first)
53
+ if (width <= 0 || height <= 0 || !Number.isFinite(n) || n <= 0) return 0
54
+ if (first.endsWith('%'))
55
+ return n >= 50 ? 'full' : Math.round((n / 100) * Math.min(width, height) * 100) / 100
56
+ if (n >= Math.min(width, height) / 2) return 'full'
57
+ return Math.round(n * 100) / 100
58
+ }
59
+
60
+ const hex = (c: readonly number[]): string =>
61
+ '#' +
62
+ c
63
+ .slice(0, 3)
64
+ .map((n) => Math.round(n).toString(16).padStart(2, '0'))
65
+ .join('')
66
+
67
+ /**
68
+ * Contrast per text reading: `min` over all, `failures` below the WCAG AA threshold. The threshold
69
+ * is tested on the UNROUNDED ratio; only the stored value is rounded.
70
+ */
71
+ export function finishMeasurement({ texts, radius, nested, ...rest }: Reading): Measurement {
72
+ const failures: ContrastFailure[] = []
73
+ let min: number | null = null
74
+ for (const t of texts) {
75
+ const exact = contrastRatio(t.fg, t.bg)
76
+ const ratio = Math.round(exact * 100) / 100
77
+ min = min === null ? ratio : Math.min(min, ratio)
78
+ if (exact < contrastThreshold(t.fontSize, t.bold)) {
79
+ failures.push({ text: t.text, ratio, fg: hex(t.fg), bg: hex(t.bg), fontSize: t.fontSize })
80
+ }
81
+ }
82
+ const backdrop = texts.some((t) => t.assumedWhite) ? ({ backdrop: 'assumed-white' } as const) : {}
83
+ return {
84
+ ...rest,
85
+ radius: radiusReading(radius),
86
+ nested: nested.map((n) => ({ ...n, radius: radiusReading(n.radius) })),
87
+ contrast: { min, failures, ...backdrop },
88
+ }
89
+ }
90
+
91
+ /* oxlint-disable unicorn/consistent-function-scoping -- the helpers below are serialised into the page with it: no outer scope */
92
+ export function measureAnchor(root: Element): Reading {
93
+ const px = (v: string | number): number => Math.round(parseFloat(String(v)) * 100) / 100
94
+ const sides = (s: CSSStyleDeclaration, p: 'padding'): Measurement['padding'] => ({
95
+ top: px(s[`${p}Top`]),
96
+ right: px(s[`${p}Right`]),
97
+ bottom: px(s[`${p}Bottom`]),
98
+ left: px(s[`${p}Left`]),
99
+ })
100
+ const ctx = document.createElement('canvas').getContext('2d', { willReadFrequently: true })
101
+ if (!ctx) throw new Error('no 2d canvas context: cannot read colours')
102
+ const parsed = new Map<string, number[]>()
103
+ const paint = (start: string, css: string): number[] => {
104
+ ctx.clearRect(0, 0, 1, 1)
105
+ ctx.fillStyle = start
106
+ ctx.fillStyle = css
107
+ ctx.fillRect(0, 0, 1, 1)
108
+ return Array.from(ctx.getImageData(0, 0, 1, 1).data)
109
+ }
110
+ // Any CSS colour syntax (oklch, color-mix, …) → sRGBA, by letting the canvas parse it. An
111
+ // unparseable value leaves the start colour in place, so two different starts disagree.
112
+ const rgba = (css: string): number[] => {
113
+ const known = parsed.get(css)
114
+ if (known) return known
115
+ const onBlack = paint('#000000', css)
116
+ const onWhite = paint('#ffffff', css)
117
+ if (onBlack.some((v, i) => v !== onWhite[i])) throw new Error(`unparseable colour: ${css}`)
118
+ const out = [onBlack[0] ?? 0, onBlack[1] ?? 0, onBlack[2] ?? 0, (onBlack[3] ?? 0) / 255]
119
+ parsed.set(css, out)
120
+ return out
121
+ }
122
+ const over = (top: number[], under: number[]): number[] => {
123
+ const a = top[3] ?? 1
124
+ return [0, 1, 2, 3].map((i) => (i === 3 ? 1 : (top[i] ?? 0) * a + (under[i] ?? 0) * (1 - a)))
125
+ }
126
+ const visible = (el: Element): CSSStyleDeclaration | null => {
127
+ const s = getComputedStyle(el)
128
+ const r = el.getBoundingClientRect()
129
+ return s.visibility === 'hidden' || s.display === 'none' || s.opacity === '0' || r.width === 0
130
+ ? null
131
+ : s
132
+ }
133
+ /** The effective background: layers up to the first opaque ancestor (html/body included), composited. */
134
+ const backdrop = (el: Element): { color: number[]; assumedWhite: boolean } => {
135
+ const layers: number[][] = []
136
+ let opaque = false
137
+ for (let n: Element | null = el; n && !opaque; n = n.parentElement) {
138
+ const c = rgba(getComputedStyle(n).backgroundColor)
139
+ if ((c[3] ?? 0) > 0) layers.push(c)
140
+ opaque = (c[3] ?? 0) >= 0.99
141
+ }
142
+ const color = layers.toReversed().reduce((under, c) => over(c, under), [255, 255, 255, 1])
143
+ return { color, assumedWhite: !opaque }
144
+ }
145
+
146
+ const cs = getComputedStyle(root)
147
+ const rect = root.getBoundingClientRect()
148
+ const widest = Math.max(
149
+ ...['Top', 'Right', 'Bottom', 'Left'].map((e) =>
150
+ px(cs.getPropertyValue(`border-${e.toLowerCase()}-width`)),
151
+ ),
152
+ )
153
+
154
+ // gap: the first flex/grid box (breadth-first) that actually spaces its children.
155
+ let gap = { row: 0, column: 0 }
156
+ const queue: Element[] = [root]
157
+ for (let i = 0; i < queue.length && i < 80; i++) {
158
+ const item = queue[i]
159
+ if (!item) break
160
+ const s = getComputedStyle(item)
161
+ const row = px(s.rowGap) || 0
162
+ const column = px(s.columnGap) || 0
163
+ if ((s.display.includes('flex') || s.display.includes('grid')) && (row > 0 || column > 0)) {
164
+ gap = { row, column }
165
+ break
166
+ }
167
+ queue.push(...Array.from(item.children))
168
+ }
169
+
170
+ const fontSizes = new Set<number>()
171
+ const texts: Reading['texts'] = []
172
+ const painted: [number, number][] = []
173
+ const nested: Reading['nested'] = []
174
+ const pathOf = (el: Element): string => {
175
+ const parts: string[] = []
176
+ for (let n: Element | null = el; n && n !== root; n = n.parentElement) {
177
+ const cls = n.classList.item(0)
178
+ parts.unshift(n.tagName.toLowerCase() + (cls ? `.${cls}` : ''))
179
+ }
180
+ return parts.join(' > ')
181
+ }
182
+ const range = document.createRange()
183
+ for (const el of [root, ...Array.from(root.querySelectorAll('*'))]) {
184
+ const s = visible(el)
185
+ if (!s) continue
186
+ const r = el.getBoundingClientRect()
187
+ const hasBg = (rgba(s.backgroundColor)[3] ?? 0) > 0
188
+ const hasBorder = ['Top', 'Right', 'Bottom', 'Left'].some(
189
+ (e) => px(s.getPropertyValue(`border-${e.toLowerCase()}-width`)) > 0,
190
+ )
191
+ if (el !== root && (hasBg || hasBorder) && nested.length < 60) {
192
+ nested.push({
193
+ path: pathOf(el),
194
+ radius: { value: s.borderTopLeftRadius, width: px(r.width), height: px(r.height) },
195
+ padding: sides(s, 'padding'),
196
+ })
197
+ }
198
+ // Wrappers that span the anchor are layout, not content: only smaller painted boxes count.
199
+ if (
200
+ el !== root &&
201
+ (/^(svg|img|canvas|video|input|textarea)$/i.test(el.tagName) ||
202
+ ((hasBg || hasBorder) && r.height < rect.height * 0.9))
203
+ ) {
204
+ painted.push([r.top, r.bottom])
205
+ }
206
+ const text = Array.from(el.childNodes).filter(
207
+ (n) => n.nodeType === Node.TEXT_NODE && n.textContent?.trim(),
208
+ )
209
+ if (text.length === 0) continue
210
+ const size = px(s.fontSize)
211
+ fontSizes.add(size)
212
+ for (const node of text) {
213
+ range.selectNodeContents(node)
214
+ const tr = range.getBoundingClientRect()
215
+ painted.push([tr.top, tr.bottom])
216
+ }
217
+ const back = backdrop(el)
218
+ texts.push({
219
+ text: (text[0]?.textContent ?? '').trim().slice(0, 40),
220
+ fg: over(rgba(s.color), back.color),
221
+ bg: back.color,
222
+ assumedWhite: back.assumedWhite,
223
+ fontSize: size,
224
+ bold: parseInt(s.fontWeight, 10) >= 700,
225
+ })
226
+ }
227
+
228
+ // emptyRatio: the largest vertical run (edges included) with nothing painted in it.
229
+ const top = rect.top
230
+ const bottom = rect.bottom
231
+ let cursor = top
232
+ let longest = 0
233
+ for (const [a, b] of painted.toSorted((x, y) => x[0] - y[0])) {
234
+ longest = Math.max(longest, Math.min(a, bottom) - cursor)
235
+ cursor = Math.max(cursor, Math.min(b, bottom))
236
+ }
237
+ longest = Math.max(longest, bottom - cursor)
238
+ const emptyRatio =
239
+ rect.height > 0 ? Math.round((Math.max(longest, 0) / rect.height) * 1000) / 1000 : 1
240
+
241
+ return {
242
+ box: { width: px(rect.width), height: px(rect.height) },
243
+ padding: sides(cs, 'padding'),
244
+ gap,
245
+ radius: { value: cs.borderTopLeftRadius, width: px(rect.width), height: px(rect.height) },
246
+ borderWidth: widest,
247
+ fontSizes: [...fontSizes].toSorted((a, b) => a - b),
248
+ nested,
249
+ emptyRatio,
250
+ texts,
251
+ }
252
+ }