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.
- package/CHANGELOG.md +66 -0
- package/MIGRATING.md +42 -12
- package/agent/agents/basalt-design-reviewer.md +83 -0
- package/agent/rules/basalt-batteries.md +1 -2
- package/agent/rules/basalt-charts.md +1 -1
- package/agent/rules/basalt-controls.md +3 -3
- package/agent/rules/basalt-mantine.md +1 -2
- package/agent/rules/basalt-state.md +1 -2
- package/agent/rules/basalt-tokens.md +1 -3
- package/agent/skills/basalt-design/SKILL.md +26 -8
- package/agent/templates/AGENTS-block.md.tpl +7 -0
- package/configs/oxlint-plugin.js +39 -2
- package/configs/oxlint-plugin.test.ts +48 -0
- package/dist/agent/chat/thread-feed-row.d.ts.map +1 -1
- package/dist/agent/chat/thread-feed-row.js +2 -2
- package/dist/agent/chat/thread-message.d.ts.map +1 -1
- package/dist/agent/chat/thread-message.js +2 -2
- package/dist/agent/chat/thread-outcome-card.js +2 -2
- package/dist/charts/DualPanel.d.ts.map +1 -1
- package/dist/charts/DualPanel.js +1 -0
- package/dist/charts/compile.d.ts.map +1 -1
- package/dist/charts/compile.js +3 -2
- package/dist/charts/cursor.d.ts +10 -6
- package/dist/charts/cursor.d.ts.map +1 -1
- package/dist/charts/cursor.js +20 -13
- package/dist/charts/legend.d.ts +7 -6
- package/dist/charts/legend.d.ts.map +1 -1
- package/dist/charts/legend.js +3 -3
- package/dist/charts/panel.d.ts +2 -0
- package/dist/charts/panel.d.ts.map +1 -1
- package/dist/charts/panel.js +1 -0
- package/dist/cli/board-freshness.d.ts +25 -0
- package/dist/cli/board-freshness.d.ts.map +1 -0
- package/dist/cli/board-freshness.js +88 -0
- package/dist/cli/doctor.d.ts +2 -1
- package/dist/cli/doctor.d.ts.map +1 -1
- package/dist/cli/doctor.js +3 -1
- package/dist/cli/help.d.ts.map +1 -1
- package/dist/cli/help.js +9 -3
- package/dist/cli/index.d.ts +15 -1
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +57 -7
- package/dist/cli/init.d.ts.map +1 -1
- package/dist/cli/init.js +6 -1
- package/dist/cli/shot/board.d.ts +5 -0
- package/dist/cli/shot/board.d.ts.map +1 -0
- package/dist/cli/shot/board.js +96 -0
- package/dist/cli/shot/capture.d.ts +59 -0
- package/dist/cli/shot/capture.d.ts.map +1 -0
- package/dist/cli/shot/capture.js +473 -0
- package/dist/cli/shot/index.d.ts +45 -0
- package/dist/cli/shot/index.d.ts.map +1 -0
- package/dist/cli/shot/index.js +289 -0
- package/dist/cli/shot/measure.d.ts +28 -0
- package/dist/cli/shot/measure.d.ts.map +1 -0
- package/dist/cli/shot/measure.js +176 -0
- package/dist/cli/shot/playwright.d.ts +101 -0
- package/dist/cli/shot/playwright.d.ts.map +1 -0
- package/dist/cli/shot/playwright.js +60 -0
- package/dist/cli/shot/serve.d.ts +6 -0
- package/dist/cli/shot/serve.d.ts.map +1 -0
- package/dist/cli/shot/serve.js +33 -0
- package/dist/cli/shot/types.d.ts +97 -0
- package/dist/cli/shot/types.d.ts.map +1 -0
- package/dist/cli/shot/types.js +17 -0
- package/dist/cli/sync.d.ts.map +1 -1
- package/dist/cli/sync.js +2 -1
- package/dist/commands/notifications/center.d.ts.map +1 -1
- package/dist/commands/notifications/center.js +2 -11
- package/dist/controls/control-name.d.ts +27 -0
- package/dist/controls/control-name.d.ts.map +1 -0
- package/dist/controls/control-name.js +11 -0
- package/dist/controls/enum-filter.d.ts +3 -6
- package/dist/controls/enum-filter.d.ts.map +1 -1
- package/dist/controls/enum-filter.js +8 -4
- package/dist/controls/filter-base.d.ts +30 -0
- package/dist/controls/filter-base.d.ts.map +1 -0
- package/dist/controls/filter-base.js +0 -0
- package/dist/controls/filter-pill.d.ts +3 -1
- package/dist/controls/filter-pill.d.ts.map +1 -1
- package/dist/controls/filter-pill.js +2 -0
- package/dist/controls/filter-sheet.d.ts +0 -32
- package/dist/controls/filter-sheet.d.ts.map +1 -1
- package/dist/controls/filter-sheet.js +1 -28
- package/dist/controls/glyphs.d.ts +12 -0
- package/dist/controls/glyphs.d.ts.map +1 -1
- package/dist/controls/glyphs.js +23 -2
- package/dist/controls/index.d.ts +2 -1
- package/dist/controls/index.d.ts.map +1 -1
- package/dist/controls/multi-select-filter.d.ts +8 -3
- package/dist/controls/multi-select-filter.d.ts.map +1 -1
- package/dist/controls/multi-select-filter.js +27 -10
- package/dist/controls/number-filter.d.ts +3 -12
- package/dist/controls/number-filter.d.ts.map +1 -1
- package/dist/controls/number-filter.js +17 -6
- package/dist/controls/panel-row.d.ts +5 -8
- package/dist/controls/panel-row.d.ts.map +1 -1
- package/dist/controls/panel-row.js +3 -0
- package/dist/controls/range-filter.d.ts +14 -14
- package/dist/controls/range-filter.d.ts.map +1 -1
- package/dist/controls/range-filter.js +18 -41
- package/dist/controls/search-filter.d.ts +5 -2
- package/dist/controls/search-filter.d.ts.map +1 -1
- package/dist/controls/search-filter.js +74 -40
- package/dist/controls/select-filter.d.ts +2 -15
- package/dist/controls/select-filter.d.ts.map +1 -1
- package/dist/controls/sync-button.d.ts +0 -6
- package/dist/controls/sync-button.d.ts.map +1 -1
- package/dist/controls/sync-button.js +6 -36
- package/dist/controls/toggle-filter.d.ts +2 -2
- package/dist/controls/toggle-filter.d.ts.map +1 -1
- package/dist/controls/toggle-filter.js +3 -2
- package/dist/controls/view-tabs.d.ts +3 -4
- package/dist/controls/view-tabs.d.ts.map +1 -1
- package/dist/controls/view-tabs.js +24 -5
- package/dist/format/date.d.ts +43 -10
- package/dist/format/date.d.ts.map +1 -1
- package/dist/format/date.js +109 -18
- package/dist/format/index.d.ts +12 -11
- package/dist/format/index.d.ts.map +1 -1
- package/dist/format/index.js +11 -2
- package/dist/format/measure.d.ts +9 -9
- package/dist/format/measure.d.ts.map +1 -1
- package/dist/format/measure.js +19 -8
- package/dist/format/number.d.ts +35 -27
- package/dist/format/number.d.ts.map +1 -1
- package/dist/format/number.js +41 -20
- package/dist/format/shared.d.ts +38 -7
- package/dist/format/shared.d.ts.map +1 -1
- package/dist/format/shared.js +61 -13
- package/dist/provider/index.d.ts +13 -1
- package/dist/provider/index.d.ts.map +1 -1
- package/dist/provider/index.js +8 -0
- package/dist/surfaces.d.ts +2 -0
- package/dist/surfaces.d.ts.map +1 -1
- package/dist/surfaces.js +2 -0
- package/llms.txt +35 -14
- package/package.json +1 -1
- package/src/agent/chat/thread-feed-row.tsx +2 -2
- package/src/agent/chat/thread-message.tsx +2 -2
- package/src/agent/chat/thread-outcome-card.tsx +2 -2
- package/src/charts/DualPanel.tsx +1 -0
- package/src/charts/compile.ts +3 -2
- package/src/charts/cursor.ts +44 -27
- package/src/charts/legend.tsx +11 -8
- package/src/charts/panel.tsx +3 -0
- package/src/cli/board-freshness.ts +132 -0
- package/src/cli/doctor.ts +10 -1
- package/src/cli/help.ts +14 -2
- package/src/cli/index.ts +80 -10
- package/src/cli/init.ts +8 -1
- package/src/cli/shot/board.ts +154 -0
- package/src/cli/shot/capture.ts +650 -0
- package/src/cli/shot/index.ts +362 -0
- package/src/cli/shot/measure.ts +225 -0
- package/src/cli/shot/playwright.ts +152 -0
- package/src/cli/shot/serve.ts +35 -0
- package/src/cli/shot/types.ts +91 -0
- package/src/cli/sync.ts +2 -1
- package/src/commands/notifications/center.tsx +2 -14
- package/src/controls/control-name.ts +33 -0
- package/src/controls/enum-filter.tsx +29 -27
- package/src/controls/filter-base.ts +31 -0
- package/src/controls/filter-pill.tsx +4 -0
- package/src/controls/filter-sheet.tsx +0 -56
- package/src/controls/glyphs.tsx +45 -2
- package/src/controls/index.ts +2 -1
- package/src/controls/multi-select-filter.tsx +67 -43
- package/src/controls/number-filter.tsx +47 -47
- package/src/controls/panel-row.tsx +7 -8
- package/src/controls/range-filter.tsx +54 -78
- package/src/controls/search-filter.tsx +107 -54
- package/src/controls/select-filter.tsx +2 -18
- package/src/controls/sync-button.tsx +7 -40
- package/src/controls/toggle-filter.tsx +9 -7
- package/src/controls/view-tabs.tsx +41 -21
- package/src/format/date.ts +189 -36
- package/src/format/index.ts +12 -11
- package/src/format/measure.ts +29 -18
- package/src/format/number.ts +76 -37
- package/src/format/shared.ts +116 -25
- package/src/provider/index.tsx +23 -0
- package/src/surfaces.ts +5 -0
- package/dist/agent/chat/relative-time.d.ts +0 -27
- package/dist/agent/chat/relative-time.d.ts.map +0 -1
- package/dist/agent/chat/relative-time.js +0 -27
- package/src/agent/chat/relative-time.ts +0 -55
|
@@ -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,225 @@
|
|
|
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
|
+
export type Reading = Omit<Measurement, 'contrast'> & { texts: TextReading[] }
|
|
37
|
+
|
|
38
|
+
const hex = (c: readonly number[]): string =>
|
|
39
|
+
'#' +
|
|
40
|
+
c
|
|
41
|
+
.slice(0, 3)
|
|
42
|
+
.map((n) => Math.round(n).toString(16).padStart(2, '0'))
|
|
43
|
+
.join('')
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Contrast per text reading: `min` over all, `failures` below the WCAG AA threshold. The threshold
|
|
47
|
+
* is tested on the UNROUNDED ratio; only the stored value is rounded.
|
|
48
|
+
*/
|
|
49
|
+
export function finishMeasurement({ texts, ...rest }: Reading): Measurement {
|
|
50
|
+
const failures: ContrastFailure[] = []
|
|
51
|
+
let min: number | null = null
|
|
52
|
+
for (const t of texts) {
|
|
53
|
+
const exact = contrastRatio(t.fg, t.bg)
|
|
54
|
+
const ratio = Math.round(exact * 100) / 100
|
|
55
|
+
min = min === null ? ratio : Math.min(min, ratio)
|
|
56
|
+
if (exact < contrastThreshold(t.fontSize, t.bold)) {
|
|
57
|
+
failures.push({ text: t.text, ratio, fg: hex(t.fg), bg: hex(t.bg), fontSize: t.fontSize })
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const backdrop = texts.some((t) => t.assumedWhite) ? ({ backdrop: 'assumed-white' } as const) : {}
|
|
61
|
+
return { ...rest, contrast: { min, failures, ...backdrop } }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/* oxlint-disable unicorn/consistent-function-scoping -- the helpers below are serialised into the page with it: no outer scope */
|
|
65
|
+
export function measureAnchor(root: Element): Reading {
|
|
66
|
+
const px = (v: string | number): number => Math.round(parseFloat(String(v)) * 100) / 100
|
|
67
|
+
const sides = (s: CSSStyleDeclaration, p: 'padding'): Measurement['padding'] => ({
|
|
68
|
+
top: px(s[`${p}Top`]),
|
|
69
|
+
right: px(s[`${p}Right`]),
|
|
70
|
+
bottom: px(s[`${p}Bottom`]),
|
|
71
|
+
left: px(s[`${p}Left`]),
|
|
72
|
+
})
|
|
73
|
+
const ctx = document.createElement('canvas').getContext('2d', { willReadFrequently: true })
|
|
74
|
+
if (!ctx) throw new Error('no 2d canvas context: cannot read colours')
|
|
75
|
+
const parsed = new Map<string, number[]>()
|
|
76
|
+
const paint = (start: string, css: string): number[] => {
|
|
77
|
+
ctx.clearRect(0, 0, 1, 1)
|
|
78
|
+
ctx.fillStyle = start
|
|
79
|
+
ctx.fillStyle = css
|
|
80
|
+
ctx.fillRect(0, 0, 1, 1)
|
|
81
|
+
return Array.from(ctx.getImageData(0, 0, 1, 1).data)
|
|
82
|
+
}
|
|
83
|
+
// Any CSS colour syntax (oklch, color-mix, …) → sRGBA, by letting the canvas parse it. An
|
|
84
|
+
// unparseable value leaves the start colour in place, so two different starts disagree.
|
|
85
|
+
const rgba = (css: string): number[] => {
|
|
86
|
+
const known = parsed.get(css)
|
|
87
|
+
if (known) return known
|
|
88
|
+
const onBlack = paint('#000000', css)
|
|
89
|
+
const onWhite = paint('#ffffff', css)
|
|
90
|
+
if (onBlack.some((v, i) => v !== onWhite[i])) throw new Error(`unparseable colour: ${css}`)
|
|
91
|
+
const out = [onBlack[0] ?? 0, onBlack[1] ?? 0, onBlack[2] ?? 0, (onBlack[3] ?? 0) / 255]
|
|
92
|
+
parsed.set(css, out)
|
|
93
|
+
return out
|
|
94
|
+
}
|
|
95
|
+
const over = (top: number[], under: number[]): number[] => {
|
|
96
|
+
const a = top[3] ?? 1
|
|
97
|
+
return [0, 1, 2, 3].map((i) => (i === 3 ? 1 : (top[i] ?? 0) * a + (under[i] ?? 0) * (1 - a)))
|
|
98
|
+
}
|
|
99
|
+
const visible = (el: Element): CSSStyleDeclaration | null => {
|
|
100
|
+
const s = getComputedStyle(el)
|
|
101
|
+
const r = el.getBoundingClientRect()
|
|
102
|
+
return s.visibility === 'hidden' || s.display === 'none' || s.opacity === '0' || r.width === 0
|
|
103
|
+
? null
|
|
104
|
+
: s
|
|
105
|
+
}
|
|
106
|
+
/** The effective background: layers up to the first opaque ancestor (html/body included), composited. */
|
|
107
|
+
const backdrop = (el: Element): { color: number[]; assumedWhite: boolean } => {
|
|
108
|
+
const layers: number[][] = []
|
|
109
|
+
let opaque = false
|
|
110
|
+
for (let n: Element | null = el; n && !opaque; n = n.parentElement) {
|
|
111
|
+
const c = rgba(getComputedStyle(n).backgroundColor)
|
|
112
|
+
if ((c[3] ?? 0) > 0) layers.push(c)
|
|
113
|
+
opaque = (c[3] ?? 0) >= 0.99
|
|
114
|
+
}
|
|
115
|
+
const color = layers.toReversed().reduce((under, c) => over(c, under), [255, 255, 255, 1])
|
|
116
|
+
return { color, assumedWhite: !opaque }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const cs = getComputedStyle(root)
|
|
120
|
+
const rect = root.getBoundingClientRect()
|
|
121
|
+
const widest = Math.max(
|
|
122
|
+
...['Top', 'Right', 'Bottom', 'Left'].map((e) =>
|
|
123
|
+
px(cs.getPropertyValue(`border-${e.toLowerCase()}-width`)),
|
|
124
|
+
),
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
// gap: the first flex/grid box (breadth-first) that actually spaces its children.
|
|
128
|
+
let gap = { row: 0, column: 0 }
|
|
129
|
+
const queue: Element[] = [root]
|
|
130
|
+
for (let i = 0; i < queue.length && i < 80; i++) {
|
|
131
|
+
const item = queue[i]
|
|
132
|
+
if (!item) break
|
|
133
|
+
const s = getComputedStyle(item)
|
|
134
|
+
const row = px(s.rowGap) || 0
|
|
135
|
+
const column = px(s.columnGap) || 0
|
|
136
|
+
if ((s.display.includes('flex') || s.display.includes('grid')) && (row > 0 || column > 0)) {
|
|
137
|
+
gap = { row, column }
|
|
138
|
+
break
|
|
139
|
+
}
|
|
140
|
+
queue.push(...Array.from(item.children))
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const fontSizes = new Set<number>()
|
|
144
|
+
const texts: Reading['texts'] = []
|
|
145
|
+
const painted: [number, number][] = []
|
|
146
|
+
const nested: Measurement['nested'] = []
|
|
147
|
+
const pathOf = (el: Element): string => {
|
|
148
|
+
const parts: string[] = []
|
|
149
|
+
for (let n: Element | null = el; n && n !== root; n = n.parentElement) {
|
|
150
|
+
const cls = n.classList.item(0)
|
|
151
|
+
parts.unshift(n.tagName.toLowerCase() + (cls ? `.${cls}` : ''))
|
|
152
|
+
}
|
|
153
|
+
return parts.join(' > ')
|
|
154
|
+
}
|
|
155
|
+
const range = document.createRange()
|
|
156
|
+
for (const el of [root, ...Array.from(root.querySelectorAll('*'))]) {
|
|
157
|
+
const s = visible(el)
|
|
158
|
+
if (!s) continue
|
|
159
|
+
const r = el.getBoundingClientRect()
|
|
160
|
+
const hasBg = (rgba(s.backgroundColor)[3] ?? 0) > 0
|
|
161
|
+
const hasBorder = ['Top', 'Right', 'Bottom', 'Left'].some(
|
|
162
|
+
(e) => px(s.getPropertyValue(`border-${e.toLowerCase()}-width`)) > 0,
|
|
163
|
+
)
|
|
164
|
+
if (el !== root && (hasBg || hasBorder) && nested.length < 60) {
|
|
165
|
+
nested.push({
|
|
166
|
+
path: pathOf(el),
|
|
167
|
+
radius: px(s.borderTopLeftRadius),
|
|
168
|
+
padding: sides(s, 'padding'),
|
|
169
|
+
})
|
|
170
|
+
}
|
|
171
|
+
// Wrappers that span the anchor are layout, not content: only smaller painted boxes count.
|
|
172
|
+
if (
|
|
173
|
+
el !== root &&
|
|
174
|
+
(/^(svg|img|canvas|video|input|textarea)$/i.test(el.tagName) ||
|
|
175
|
+
((hasBg || hasBorder) && r.height < rect.height * 0.9))
|
|
176
|
+
) {
|
|
177
|
+
painted.push([r.top, r.bottom])
|
|
178
|
+
}
|
|
179
|
+
const text = Array.from(el.childNodes).filter(
|
|
180
|
+
(n) => n.nodeType === Node.TEXT_NODE && n.textContent?.trim(),
|
|
181
|
+
)
|
|
182
|
+
if (text.length === 0) continue
|
|
183
|
+
const size = px(s.fontSize)
|
|
184
|
+
fontSizes.add(size)
|
|
185
|
+
for (const node of text) {
|
|
186
|
+
range.selectNodeContents(node)
|
|
187
|
+
const tr = range.getBoundingClientRect()
|
|
188
|
+
painted.push([tr.top, tr.bottom])
|
|
189
|
+
}
|
|
190
|
+
const back = backdrop(el)
|
|
191
|
+
texts.push({
|
|
192
|
+
text: (text[0]?.textContent ?? '').trim().slice(0, 40),
|
|
193
|
+
fg: over(rgba(s.color), back.color),
|
|
194
|
+
bg: back.color,
|
|
195
|
+
assumedWhite: back.assumedWhite,
|
|
196
|
+
fontSize: size,
|
|
197
|
+
bold: parseInt(s.fontWeight, 10) >= 700,
|
|
198
|
+
})
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// emptyRatio: the largest vertical run (edges included) with nothing painted in it.
|
|
202
|
+
const top = rect.top
|
|
203
|
+
const bottom = rect.bottom
|
|
204
|
+
let cursor = top
|
|
205
|
+
let longest = 0
|
|
206
|
+
for (const [a, b] of painted.toSorted((x, y) => x[0] - y[0])) {
|
|
207
|
+
longest = Math.max(longest, Math.min(a, bottom) - cursor)
|
|
208
|
+
cursor = Math.max(cursor, Math.min(b, bottom))
|
|
209
|
+
}
|
|
210
|
+
longest = Math.max(longest, bottom - cursor)
|
|
211
|
+
const emptyRatio =
|
|
212
|
+
rect.height > 0 ? Math.round((Math.max(longest, 0) / rect.height) * 1000) / 1000 : 1
|
|
213
|
+
|
|
214
|
+
return {
|
|
215
|
+
box: { width: px(rect.width), height: px(rect.height) },
|
|
216
|
+
padding: sides(cs, 'padding'),
|
|
217
|
+
gap,
|
|
218
|
+
radius: px(cs.borderTopLeftRadius),
|
|
219
|
+
borderWidth: widest,
|
|
220
|
+
fontSizes: [...fontSizes].toSorted((a, b) => a - b),
|
|
221
|
+
nested,
|
|
222
|
+
emptyRatio,
|
|
223
|
+
texts,
|
|
224
|
+
}
|
|
225
|
+
}
|