basalt-ui 2.17.0 → 2.18.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 +18 -0
- package/MIGRATING.md +44 -12
- package/agent/skills/basalt-design/SKILL.md +1 -1
- package/dist/cli/help.d.ts +1 -0
- package/dist/cli/help.d.ts.map +1 -1
- package/dist/cli/help.js +8 -2
- package/dist/cli/shot/capture.d.ts +12 -1
- package/dist/cli/shot/capture.d.ts.map +1 -1
- package/dist/cli/shot/capture.js +72 -10
- package/dist/cli/shot/index.d.ts +10 -1
- package/dist/cli/shot/index.d.ts.map +1 -1
- package/dist/cli/shot/index.js +40 -5
- package/dist/cli/shot/real-data.d.ts +35 -0
- package/dist/cli/shot/real-data.d.ts.map +1 -0
- package/dist/cli/shot/real-data.js +120 -0
- package/dist/cli/shot/serve.d.ts +2 -2
- package/dist/cli/shot/serve.d.ts.map +1 -1
- package/dist/cli/shot/serve.js +16 -2
- package/dist/dashboard/bar-list.d.ts +29 -0
- package/dist/dashboard/bar-list.d.ts.map +1 -0
- package/dist/dashboard/bar-list.js +52 -0
- package/dist/dashboard/bar-list.module.css +73 -0
- package/dist/dashboard/bar-list.module.css.d.ts +16 -0
- package/dist/dashboard/index.d.ts +2 -0
- package/dist/dashboard/index.d.ts.map +1 -1
- package/dist/dashboard/index.js +4 -0
- package/dist/dashboard/meter-model.d.ts +78 -0
- package/dist/dashboard/meter-model.d.ts.map +1 -0
- package/dist/dashboard/meter-model.js +91 -0
- package/dist/dashboard/meter-parts.d.ts +42 -0
- package/dist/dashboard/meter-parts.d.ts.map +1 -0
- package/dist/dashboard/meter-parts.js +163 -0
- package/dist/dashboard/meter.d.ts +112 -0
- package/dist/dashboard/meter.d.ts.map +1 -0
- package/dist/dashboard/meter.js +43 -0
- package/dist/dashboard/meter.module.css +150 -0
- package/dist/dashboard/meter.module.css.d.ts +28 -0
- package/dist/dashboard/scale.d.ts +9 -0
- package/dist/dashboard/scale.d.ts.map +1 -0
- package/dist/dashboard/scale.js +10 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -1
- package/dist/tokens/derive.d.ts +11 -1
- package/dist/tokens/derive.d.ts.map +1 -1
- package/dist/tokens/derive.js +9 -24
- package/dist/tokens/status-text.d.ts +26 -0
- package/dist/tokens/status-text.d.ts.map +1 -0
- package/dist/tokens/status-text.js +68 -0
- package/llms.txt +32 -3
- package/package.json +1 -1
- package/src/cli/help.ts +22 -2
- package/src/cli/shot/capture.ts +98 -9
- package/src/cli/shot/index.ts +50 -4
- package/src/cli/shot/real-data.ts +165 -0
- package/src/cli/shot/serve.ts +28 -3
- package/src/dashboard/bar-list.module.css +73 -0
- package/src/dashboard/bar-list.module.css.d.ts +16 -0
- package/src/dashboard/bar-list.tsx +112 -0
- package/src/dashboard/index.ts +2 -0
- package/src/dashboard/meter-model.ts +161 -0
- package/src/dashboard/meter-parts.tsx +223 -0
- package/src/dashboard/meter.module.css +150 -0
- package/src/dashboard/meter.module.css.d.ts +28 -0
- package/src/dashboard/meter.tsx +162 -0
- package/src/dashboard/scale.ts +13 -0
- package/src/index.ts +4 -0
- package/src/tokens/derive.ts +19 -31
- package/src/tokens/status-text.ts +85 -0
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/** Flags that point `shot` at a real, authenticated app: seeded localStorage and a proxied API. */
|
|
2
|
+
import { readFileSync } from 'node:fs'
|
|
3
|
+
import { resolve } from 'node:path'
|
|
4
|
+
|
|
5
|
+
import { ShotError } from './playwright'
|
|
6
|
+
|
|
7
|
+
export type ApiRoute = { prefix: string; origin: string }
|
|
8
|
+
export type Pair = readonly [name: string, value: string]
|
|
9
|
+
export type Source = { env: Readonly<Record<string, string | undefined>>; cwd: string }
|
|
10
|
+
|
|
11
|
+
/** `<name>=<value>` split at the first `=`; errors name the flag, never the text (it may hold a secret). */
|
|
12
|
+
function splitPair(flag: string, raw: string): Pair {
|
|
13
|
+
const at = raw.indexOf('=')
|
|
14
|
+
if (at <= 0) throw new ShotError(`--${flag} expects <name>=<value>`)
|
|
15
|
+
return [raw.slice(0, at), raw.slice(at + 1)]
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** `@env:NAME` or `@file:path`: a secret never sits in argv, so there is no literal form. */
|
|
19
|
+
function resolveValue(flag: string, raw: string, src: Source): string {
|
|
20
|
+
const [, kind, ref = ''] = /^@(env|file):(.*)$/s.exec(raw) ?? []
|
|
21
|
+
let value: string | undefined
|
|
22
|
+
if (kind === 'env') value = Object.hasOwn(src.env, ref) ? src.env[ref] : undefined
|
|
23
|
+
else if (kind === 'file') {
|
|
24
|
+
try {
|
|
25
|
+
value = readFileSync(resolve(src.cwd, ref), 'utf8').trim()
|
|
26
|
+
} catch {
|
|
27
|
+
throw new ShotError(`--${flag}: cannot read @file:${ref}`)
|
|
28
|
+
}
|
|
29
|
+
} else throw new ShotError(`--${flag} takes @env:NAME or @file:path, never a literal`)
|
|
30
|
+
if (!value) throw new ShotError(`--${flag}: ${raw} is empty`)
|
|
31
|
+
return value
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export const parseStorage = (list: readonly string[], src: Source): Pair[] =>
|
|
35
|
+
list.map((raw) => {
|
|
36
|
+
const [key, value] = splitPair('local-storage', raw)
|
|
37
|
+
return [key, resolveValue('local-storage', value, src)]
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
const NOT_FORWARDED = new Set(['host', 'origin', 'referer', 'connection', 'content-length'])
|
|
41
|
+
const HEADER_NAME = /^[!#$%&'*+.^_`|~\w-]+$/
|
|
42
|
+
const HEADER_VALUE = /^[\t\x20-\x7e]*$/
|
|
43
|
+
|
|
44
|
+
/** `--header` pairs: a valid, forwardable name and a value that cannot split the request. */
|
|
45
|
+
export const parseHeaders = (list: readonly string[], src: Source): Pair[] =>
|
|
46
|
+
list.map((raw) => {
|
|
47
|
+
const [name, value] = splitPair('header', raw)
|
|
48
|
+
if (!HEADER_NAME.test(name) || NOT_FORWARDED.has(name.toLowerCase()))
|
|
49
|
+
throw new ShotError(`--header ${name}: not a header shot can send`)
|
|
50
|
+
const resolved = resolveValue('header', value, src)
|
|
51
|
+
if (!HEADER_VALUE.test(resolved))
|
|
52
|
+
throw new ShotError(`--header ${name}: value has characters a header cannot carry`)
|
|
53
|
+
return [name, resolved]
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
const LOOPBACK = new Set(['127.0.0.1', 'localhost', '[::1]'])
|
|
57
|
+
|
|
58
|
+
/** `--api <prefix>=<origin>`; with any secret configured (`--header`, `--local-storage`), a remote origin must be https. */
|
|
59
|
+
export function parseApi(list: readonly string[], secrets: boolean): ApiRoute[] {
|
|
60
|
+
return list.map((raw) => {
|
|
61
|
+
const [given, target] = splitPair('api', raw)
|
|
62
|
+
const prefix = given.replace(/\/+$/, '')
|
|
63
|
+
if (!prefix.startsWith('/'))
|
|
64
|
+
throw new ShotError('--api prefix must start with "/" and name a path, not "/"')
|
|
65
|
+
let url: URL
|
|
66
|
+
try {
|
|
67
|
+
url = new URL(target ?? '')
|
|
68
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new Error('protocol')
|
|
69
|
+
} catch {
|
|
70
|
+
throw new ShotError('--api <prefix>=<origin>: origin must be an http(s) URL')
|
|
71
|
+
}
|
|
72
|
+
if (secrets && url.protocol !== 'https:' && !LOOPBACK.has(url.hostname))
|
|
73
|
+
throw new ShotError(
|
|
74
|
+
`--api ${prefix}: with a secret configured (--header, --local-storage) the origin must be https (loopback excepted)`,
|
|
75
|
+
)
|
|
76
|
+
return { prefix, origin: url.origin }
|
|
77
|
+
})
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const NOT_RETURNED = ['content-encoding', 'content-length', 'transfer-encoding']
|
|
81
|
+
const READ_ONLY = new Set(['GET', 'HEAD'])
|
|
82
|
+
/** A status that means the page shows something other than the app's data: a redirect, a missing resource, a failure, a refusal. */
|
|
83
|
+
const UNTRUSTED = (status: number): boolean =>
|
|
84
|
+
status >= 500 ||
|
|
85
|
+
(status >= 300 && status < 400) ||
|
|
86
|
+
status === 401 ||
|
|
87
|
+
status === 403 ||
|
|
88
|
+
status === 404
|
|
89
|
+
const TIMEOUT_MS = 20_000
|
|
90
|
+
|
|
91
|
+
export type ApiProxy = {
|
|
92
|
+
handle: (req: Request) => Promise<Response | null>
|
|
93
|
+
/** The calls since the last drain that make a board untrustworthy: a 3xx, 401, 403, 404, 5xx or no answer. */
|
|
94
|
+
drain: () => string[]
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* The static server's API hook: a GET/HEAD under a prefix goes to `<origin><path>?<query>` with the
|
|
99
|
+
* `--header` values added, except on a navigation; any other method is a 405 unless `allowWrites`.
|
|
100
|
+
* Anything else is null (served from `--dist`). Every non-2xx or failed call is logged by method,
|
|
101
|
+
* path and status or error class, never a header or a query.
|
|
102
|
+
*/
|
|
103
|
+
export function apiProxy(
|
|
104
|
+
api: readonly ApiRoute[],
|
|
105
|
+
headers: readonly Pair[],
|
|
106
|
+
opts: { log: (line: string) => void; allowWrites?: boolean; timeoutMs?: number },
|
|
107
|
+
): ApiProxy {
|
|
108
|
+
let problems: string[] = []
|
|
109
|
+
const handle = async (req: Request): Promise<Response | null> => {
|
|
110
|
+
const url = new URL(req.url)
|
|
111
|
+
const route = api.find(
|
|
112
|
+
(r) => url.pathname === r.prefix || url.pathname.startsWith(r.prefix + '/'),
|
|
113
|
+
)
|
|
114
|
+
if (!route) return null
|
|
115
|
+
// Method, prefix and depth only: path segments can hold identifiers, so they never reach a log.
|
|
116
|
+
const depth = url.pathname.slice(route.prefix.length).split('/').filter(Boolean).length
|
|
117
|
+
const label = `${req.method} ${route.prefix} +${depth}`
|
|
118
|
+
if (!opts.allowWrites && !READ_ONLY.has(req.method)) {
|
|
119
|
+
opts.log(`[shot] api ${label} blocked: read-only run (--api-allow-writes lifts it)`)
|
|
120
|
+
return new Response('read-only', { status: 405 })
|
|
121
|
+
}
|
|
122
|
+
const out = new Headers()
|
|
123
|
+
for (const [name, value] of req.headers) if (!NOT_FORWARDED.has(name)) out.set(name, value)
|
|
124
|
+
const navigating =
|
|
125
|
+
req.headers.get('sec-fetch-mode') === 'navigate' ||
|
|
126
|
+
req.headers.get('sec-fetch-dest') === 'document'
|
|
127
|
+
if (!navigating) for (const [name, value] of headers) out.set(name, value)
|
|
128
|
+
try {
|
|
129
|
+
const res = await fetch(route.origin + url.pathname + url.search, {
|
|
130
|
+
method: req.method,
|
|
131
|
+
headers: out,
|
|
132
|
+
redirect: 'manual',
|
|
133
|
+
signal: AbortSignal.timeout(opts.timeoutMs ?? TIMEOUT_MS),
|
|
134
|
+
...(READ_ONLY.has(req.method) ? {} : { body: await req.arrayBuffer() }),
|
|
135
|
+
})
|
|
136
|
+
if (!res.ok) opts.log(`[shot] api ${label} → ${res.status}`)
|
|
137
|
+
if (UNTRUSTED(res.status)) problems.push(`${label} ${res.status}`)
|
|
138
|
+
const back = new Headers(res.headers)
|
|
139
|
+
for (const name of NOT_RETURNED) back.delete(name)
|
|
140
|
+
return new Response(res.body, { status: res.status, headers: back })
|
|
141
|
+
} catch (error) {
|
|
142
|
+
const kind = error instanceof Error ? error.name : 'Error'
|
|
143
|
+
opts.log(`[shot] api ${label} failed: ${kind}`)
|
|
144
|
+
problems.push(`${label} ${kind}`)
|
|
145
|
+
return new Response('proxy error', { status: 502 })
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return {
|
|
149
|
+
handle,
|
|
150
|
+
drain: () => {
|
|
151
|
+
const seen = problems
|
|
152
|
+
problems = []
|
|
153
|
+
return seen
|
|
154
|
+
},
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** The page global the seed script reports through: `origin`, or the keys it could not set. */
|
|
159
|
+
export const SEED_FLAG = '__shotSeedFailed'
|
|
160
|
+
|
|
161
|
+
/** The init script that seeds localStorage, only on `origin` and only for an absent key (a token the app rotates survives), before any page script runs. */
|
|
162
|
+
export const seedScript = (entries: readonly Pair[], origin: string): string =>
|
|
163
|
+
`(()=>{if(location.origin!==${JSON.stringify(origin)}){globalThis.${SEED_FLAG}='origin';return}` +
|
|
164
|
+
`const f=[];for(const [k,v] of ${JSON.stringify(entries)}){try{if(localStorage.getItem(k)===null)localStorage.setItem(k,v)}catch{f.push(k)}}` +
|
|
165
|
+
`if(f.length)globalThis.${SEED_FLAG}=f.join(',')})()`
|
package/src/cli/shot/serve.ts
CHANGED
|
@@ -3,8 +3,28 @@ import { join, normalize, resolve, sep } from 'node:path'
|
|
|
3
3
|
|
|
4
4
|
import { ShotError } from './playwright'
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
const FETCH_MODES = new Set(['cors', 'same-origin', 'navigate'])
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* With a proxy live only the shot's own page may reach this port: its Host, no foreign Origin, no
|
|
10
|
+
* cross-site request, and no cross-origin no-Origin request (a `no-cors` image or form from another
|
|
11
|
+
* local page). A same-origin `no-cors` load (the app's own stylesheet) is fine.
|
|
12
|
+
*/
|
|
13
|
+
function fromOwnBrowser(req: Request, own: string): boolean {
|
|
14
|
+
const origin = req.headers.get('origin')
|
|
15
|
+
const mode = req.headers.get('sec-fetch-mode')
|
|
16
|
+
const site = req.headers.get('sec-fetch-site')
|
|
17
|
+
if (req.headers.get('host') !== own) return false
|
|
18
|
+
if (origin !== null) return origin === `http://${own}`
|
|
19
|
+
if (site === 'cross-site') return false
|
|
20
|
+
return mode === null || FETCH_MODES.has(mode) || site === 'same-origin'
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Static server for a built SPA dir: real files as-is, extensionless misses fall back to index.html; `proxy` answers first. */
|
|
24
|
+
export function serveDist(
|
|
25
|
+
distDir: string,
|
|
26
|
+
proxy?: (req: Request) => Promise<Response | null>,
|
|
27
|
+
): { origin: string; stop: () => void } {
|
|
8
28
|
const root = resolve(distDir)
|
|
9
29
|
if (!existsSync(root) || !statSync(root).isDirectory()) {
|
|
10
30
|
throw new ShotError(`--dist ${distDir} is not a directory`)
|
|
@@ -20,8 +40,13 @@ export function serveDist(distDir: string): { origin: string; stop: () => void }
|
|
|
20
40
|
const server = Bun.serve({
|
|
21
41
|
port: 0,
|
|
22
42
|
hostname: '127.0.0.1',
|
|
23
|
-
fetch(req) {
|
|
43
|
+
async fetch(req) {
|
|
24
44
|
try {
|
|
45
|
+
// With a proxy live, only the shot's own browser may talk to this port (no DNS rebinding, no other page).
|
|
46
|
+
const own = `127.0.0.1:${server.port}`
|
|
47
|
+
if (proxy && !fromOwnBrowser(req, own)) return new Response('forbidden', { status: 403 })
|
|
48
|
+
const proxied = await proxy?.(req)
|
|
49
|
+
if (proxied) return proxied
|
|
25
50
|
const file = fileFor(new URL(req.url).pathname)
|
|
26
51
|
return file
|
|
27
52
|
? new Response(Bun.file(file), { headers: { 'cache-control': 'no-store' } })
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* BarList — ranked rows on one shared scale (docs/waves/design-parity/SPEC.md § 6.4). The bar sits
|
|
3
|
+
* BEHIND the label and value; the row never wraps: the label truncates, the value is nowrap.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
.root {
|
|
7
|
+
display: flex;
|
|
8
|
+
flex-direction: column;
|
|
9
|
+
gap: var(--vx-space-stack-xs, 0.25rem);
|
|
10
|
+
margin: 0;
|
|
11
|
+
padding: 0;
|
|
12
|
+
list-style: none;
|
|
13
|
+
min-width: 0;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
.row {
|
|
17
|
+
position: relative;
|
|
18
|
+
display: flex;
|
|
19
|
+
align-items: center;
|
|
20
|
+
gap: var(--vx-space-control-gap, 0.375rem);
|
|
21
|
+
min-width: 0;
|
|
22
|
+
min-height: calc(var(--vx-space-control-height-widget, 1.5rem) * var(--mantine-scale, 1));
|
|
23
|
+
padding-inline: var(--vx-space-stack-sm);
|
|
24
|
+
font-size: var(--vx-text-sm);
|
|
25
|
+
color: var(--vx-ink);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
.bar {
|
|
29
|
+
position: absolute;
|
|
30
|
+
inset-block: 0;
|
|
31
|
+
inset-inline-start: 0;
|
|
32
|
+
border-radius: var(--vx-radius-fine);
|
|
33
|
+
background: color-mix(in srgb, var(--vx-line) 30%, transparent);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
.leader {
|
|
37
|
+
background: color-mix(in srgb, var(--vx-accent) 28%, transparent);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
.label {
|
|
41
|
+
position: relative;
|
|
42
|
+
flex: 1 1 0;
|
|
43
|
+
min-width: 0;
|
|
44
|
+
overflow: hidden;
|
|
45
|
+
text-overflow: ellipsis;
|
|
46
|
+
white-space: nowrap;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
.value {
|
|
50
|
+
position: relative;
|
|
51
|
+
flex: none;
|
|
52
|
+
font-family: var(--basalt-font-mono);
|
|
53
|
+
text-align: end;
|
|
54
|
+
white-space: nowrap;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
.secondary {
|
|
58
|
+
position: relative;
|
|
59
|
+
flex: none;
|
|
60
|
+
font-family: var(--basalt-font-mono);
|
|
61
|
+
font-size: var(--vx-text-xs);
|
|
62
|
+
color: var(--vx-muted);
|
|
63
|
+
white-space: nowrap;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
.empty {
|
|
67
|
+
font-size: var(--vx-text-sm);
|
|
68
|
+
color: var(--vx-muted);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
.skeletonRow {
|
|
72
|
+
height: calc(var(--vx-space-control-height-widget, 1.5rem) * var(--mantine-scale, 1));
|
|
73
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Typed CSS-module declaration (the S4 CSS-modules path). Named string props — not an index
|
|
3
|
+
* signature — so dot access stays verbatim under the package's strict flags.
|
|
4
|
+
*/
|
|
5
|
+
declare const classes: {
|
|
6
|
+
readonly root: string
|
|
7
|
+
readonly row: string
|
|
8
|
+
readonly bar: string
|
|
9
|
+
readonly leader: string
|
|
10
|
+
readonly label: string
|
|
11
|
+
readonly value: string
|
|
12
|
+
readonly secondary: string
|
|
13
|
+
readonly empty: string
|
|
14
|
+
readonly skeletonRow: string
|
|
15
|
+
}
|
|
16
|
+
export default classes
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* BarList — a ranked list: label, an inline bar on ONE shared scale, a mono right-aligned value and
|
|
3
|
+
* an optional muted secondary value. Choose it for "top N" (the bar ranks by length before anything
|
|
4
|
+
* is read). Intended for 5–10 rows; past 10 use a table with an inline `Meter` cell. An HTML/CSS
|
|
5
|
+
* primitive, not a chart kind.
|
|
6
|
+
*
|
|
7
|
+
* Colour law: bars are neutral. `accentLeader` (opt-in) lets the top row take the accent — the
|
|
8
|
+
* leader bar, and nothing else. Each value is rendered as text, never only a bar length.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* import { BarList } from 'basalt-ui'
|
|
12
|
+
*
|
|
13
|
+
* // Recovery contributors on a fixed 0–100 scale, the qualitative level as the secondary value:
|
|
14
|
+
* <BarList label="Recovery contributors" max={100} items={[{ label: 'Sleep', value: 82, secondary: 'Good' }]} />
|
|
15
|
+
*
|
|
16
|
+
* <BarList
|
|
17
|
+
* label="Top projects by tokens"
|
|
18
|
+
* items={[{ label: 'argo', value: 1840, secondary: '41%' }, { label: 'rb', value: 920 }]}
|
|
19
|
+
* format={compact}
|
|
20
|
+
* accentLeader
|
|
21
|
+
* />
|
|
22
|
+
*/
|
|
23
|
+
import { Skeleton, VisuallyHidden } from '@mantine/core'
|
|
24
|
+
import type { ReactNode } from 'react'
|
|
25
|
+
import { cx } from '../common/props'
|
|
26
|
+
import type { BasaltProps } from '../common/props'
|
|
27
|
+
import classes from './bar-list.module.css'
|
|
28
|
+
import { asText, barPercent } from './scale'
|
|
29
|
+
|
|
30
|
+
type BarListItem = { label: string; value: number; secondary?: ReactNode; key?: string }
|
|
31
|
+
|
|
32
|
+
export type BarListProps = BasaltProps & {
|
|
33
|
+
/** Accessible name of the list. Required. */
|
|
34
|
+
label: string
|
|
35
|
+
/** Rows in display order (sort them yourself; the list does not reorder). */
|
|
36
|
+
items: readonly BarListItem[]
|
|
37
|
+
/** Formats each value. Default: the number as written. */
|
|
38
|
+
format?: (value: number) => string
|
|
39
|
+
/** Scale end shared by every bar. Default: the largest value. */
|
|
40
|
+
max?: number
|
|
41
|
+
/** The first row's bar takes the accent. Off by default. */
|
|
42
|
+
accentLeader?: boolean
|
|
43
|
+
/** Renders row-shaped skeletons. */
|
|
44
|
+
loading?: boolean
|
|
45
|
+
/** Skeleton rows while loading. Default 5. */
|
|
46
|
+
loadingRows?: number
|
|
47
|
+
/** Muted line shown when `items` is empty. */
|
|
48
|
+
emptyText?: string
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function BarList({
|
|
52
|
+
label,
|
|
53
|
+
items,
|
|
54
|
+
format = asText,
|
|
55
|
+
max,
|
|
56
|
+
accentLeader = false,
|
|
57
|
+
loading = false,
|
|
58
|
+
loadingRows = 5,
|
|
59
|
+
emptyText = 'No data',
|
|
60
|
+
className,
|
|
61
|
+
style,
|
|
62
|
+
}: BarListProps) {
|
|
63
|
+
if (loading) {
|
|
64
|
+
return (
|
|
65
|
+
<div className={cx(classes.root, className)} style={style} aria-busy="true">
|
|
66
|
+
<VisuallyHidden>{`Loading ${label}`}</VisuallyHidden>
|
|
67
|
+
{Array.from({ length: loadingRows }, (_, i) => (
|
|
68
|
+
<Skeleton key={i} className={classes.skeletonRow} data-bar-skeleton />
|
|
69
|
+
))}
|
|
70
|
+
</div>
|
|
71
|
+
)
|
|
72
|
+
}
|
|
73
|
+
if (items.length === 0) {
|
|
74
|
+
return (
|
|
75
|
+
<output className={cx(classes.root, className)} style={style} aria-label={label}>
|
|
76
|
+
<span className={classes.empty}>{emptyText}</span>
|
|
77
|
+
</output>
|
|
78
|
+
)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const scale =
|
|
82
|
+
max ?? items.reduce((top, i) => (Number.isFinite(i.value) ? Math.max(top, i.value) : top), 0)
|
|
83
|
+
return (
|
|
84
|
+
// The explicit role is deliberate: `list-style: none` makes Safari/VoiceOver drop the implicit one.
|
|
85
|
+
// oxlint-disable-next-line jsx-a11y/no-redundant-roles
|
|
86
|
+
<ul className={cx(classes.root, className)} style={style} role="list" aria-label={label}>
|
|
87
|
+
{items.map((item, i) => {
|
|
88
|
+
const isLeader = accentLeader && i === 0
|
|
89
|
+
return (
|
|
90
|
+
<li key={item.key ?? `${item.label}-${i}`} className={classes.row}>
|
|
91
|
+
{/* theme-allow hidden-inline-style — the width is the row's data (a % of the shared scale), not styling */}
|
|
92
|
+
<span
|
|
93
|
+
className={cx(classes.bar, isLeader && classes.leader)}
|
|
94
|
+
style={{ width: `${barPercent(item.value, scale)}%` }}
|
|
95
|
+
data-bar-leader={isLeader ? '' : undefined}
|
|
96
|
+
aria-hidden
|
|
97
|
+
/>
|
|
98
|
+
<span className={classes.label} title={item.label}>
|
|
99
|
+
{item.label}
|
|
100
|
+
</span>
|
|
101
|
+
<span className={classes.value}>
|
|
102
|
+
{Number.isFinite(item.value) ? format(item.value) : '—'}
|
|
103
|
+
</span>
|
|
104
|
+
{item.secondary !== undefined && (
|
|
105
|
+
<span className={classes.secondary}>{item.secondary}</span>
|
|
106
|
+
)}
|
|
107
|
+
</li>
|
|
108
|
+
)
|
|
109
|
+
})}
|
|
110
|
+
</ul>
|
|
111
|
+
)
|
|
112
|
+
}
|
package/src/dashboard/index.ts
CHANGED
|
@@ -5,3 +5,5 @@ export { StatCard, type StatCardBreakdownRow, type StatCardSparklineSize } from
|
|
|
5
5
|
export { StatGroup } from './stat-group'
|
|
6
6
|
export { EmptyState } from './empty-state'
|
|
7
7
|
export { SettingsSection, SettingsRow, DangerZone } from './settings-section'
|
|
8
|
+
export { Meter, type MeterProps } from './meter'
|
|
9
|
+
export { BarList, type BarListProps } from './bar-list'
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Meter's pure model: everything the component shows, computed from numbers (no DOM, no React).
|
|
3
|
+
* Internal — `meter.tsx` and `meter-parts.tsx` render what this returns.
|
|
4
|
+
*/
|
|
5
|
+
import { clamp01, toPct } from './scale'
|
|
6
|
+
|
|
7
|
+
export type MeterSegment = { value: number; label: string; color?: string; forecast?: boolean }
|
|
8
|
+
export type MeterZone = { from: number; to: number; label: string; color?: string }
|
|
9
|
+
|
|
10
|
+
/** A fill on the track, as fractions (0–1) of the span. */
|
|
11
|
+
export type Part = {
|
|
12
|
+
readonly start: number
|
|
13
|
+
readonly size: number
|
|
14
|
+
readonly color: string | undefined
|
|
15
|
+
readonly forecast: boolean
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
type Format = (value: number) => string
|
|
19
|
+
|
|
20
|
+
export const isReading = (n: number | null | undefined): n is number =>
|
|
21
|
+
typeof n === 'number' && Number.isFinite(n)
|
|
22
|
+
|
|
23
|
+
/** The track's span. A track that ends at or before its start falls back to 1 and is `valid: false`. */
|
|
24
|
+
export function spanOf(min: number, max: number): { span: number; valid: boolean } {
|
|
25
|
+
return max > min ? { span: max - min, valid: true } : { span: 1, valid: false }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function ariaValues(reading: number, min: number, max: number, format: Format) {
|
|
29
|
+
return {
|
|
30
|
+
role: 'meter',
|
|
31
|
+
'aria-valuenow': Math.min(max, Math.max(min, reading)),
|
|
32
|
+
'aria-valuemin': min,
|
|
33
|
+
'aria-valuemax': max,
|
|
34
|
+
'aria-valuetext': format(reading),
|
|
35
|
+
} as const
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The ONE place segment amounts are sanitised: a negative or non-finite amount is 0. The painted
|
|
40
|
+
* track, the captions and `aria-valuenow` all derive from what this returns.
|
|
41
|
+
*/
|
|
42
|
+
export function normalizeSegments(segments: readonly MeterSegment[]): MeterSegment[] {
|
|
43
|
+
return segments.map((s) => ({ ...s, value: Number.isFinite(s.value) ? Math.max(0, s.value) : 0 }))
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Segment amounts (already normalised) accumulate from `min`; a part never passes the track end. */
|
|
47
|
+
export function layoutSegments(segments: readonly MeterSegment[], span: number): Part[] {
|
|
48
|
+
let cursor = 0
|
|
49
|
+
return segments.map((s) => {
|
|
50
|
+
const size = Math.max(0, Math.min(clamp01(s.value / span), 1 - cursor))
|
|
51
|
+
const forecast = s.forecast === true
|
|
52
|
+
// A forecast stays the lighter neutral: a colour would turn the committed/forecast pair into hue.
|
|
53
|
+
const part = { start: cursor, size, color: forecast ? undefined : s.color, forecast }
|
|
54
|
+
cursor += size
|
|
55
|
+
return part
|
|
56
|
+
})
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** `from` is inclusive; a value on the last band's `to` belongs to that band. */
|
|
60
|
+
export function findHoldingZone(zones: readonly MeterZone[], value: number): MeterZone | undefined {
|
|
61
|
+
const end = Math.max(...zones.map((z) => z.to))
|
|
62
|
+
return zones.find((z) => value >= z.from && (value < z.to || (value === z.to && z.to === end)))
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** A zone band as left edge + width in percent, clipped to the track. */
|
|
66
|
+
export function zoneBand(zone: MeterZone, min: number, span: number) {
|
|
67
|
+
const lo = clamp01((zone.from - min) / span)
|
|
68
|
+
const hi = clamp01((zone.to - min) / span)
|
|
69
|
+
return { start: toPct(lo), width: toPct(hi - lo) }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const segmentText = (s: MeterSegment, format: Format): string =>
|
|
73
|
+
`${s.label} ${format(s.value)}${s.forecast === true ? ' (forecast)' : ''}`
|
|
74
|
+
|
|
75
|
+
export type BarInput = {
|
|
76
|
+
reading: number
|
|
77
|
+
min: number
|
|
78
|
+
max: number
|
|
79
|
+
format: Format
|
|
80
|
+
segments?: readonly MeterSegment[] | undefined
|
|
81
|
+
zones?: readonly MeterZone[] | undefined
|
|
82
|
+
target?: number | undefined
|
|
83
|
+
color?: string | undefined
|
|
84
|
+
forecastCaption?: string | undefined
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export type BarModel = {
|
|
88
|
+
span: number
|
|
89
|
+
/** Fills, or none when the track is drawn as zones. */
|
|
90
|
+
parts: readonly Part[]
|
|
91
|
+
/** Percent where the first forecast part starts; absent when the forecast opens the track. */
|
|
92
|
+
boundaryPct: number | undefined
|
|
93
|
+
forecastText: string | null
|
|
94
|
+
markerPct: number | undefined
|
|
95
|
+
targetPct: number | undefined
|
|
96
|
+
startText: string
|
|
97
|
+
endText: string | null
|
|
98
|
+
describedByText: string | null
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function endCaptionText(reading: number, target: number | undefined, format: Format) {
|
|
102
|
+
if (target === undefined) return null
|
|
103
|
+
if (reading > target) return `Target ${format(target)} · ${format(reading - target)} over`
|
|
104
|
+
return `Target ${format(target)}`
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function fillParts(input: BarInput, span: number, zoned: boolean): Part[] {
|
|
108
|
+
if (zoned) return []
|
|
109
|
+
if (input.segments !== undefined) return layoutSegments(input.segments, span)
|
|
110
|
+
const fill = { value: input.reading - input.min, label: '' }
|
|
111
|
+
return layoutSegments([input.color === undefined ? fill : { ...fill, color: input.color }], span)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Segments are amounts accumulated from `min`, so the reading is `min` plus their sum. */
|
|
115
|
+
export const segmentReading = (segments: readonly MeterSegment[], min: number): number =>
|
|
116
|
+
segments.reduce((sum, s) => sum + s.value, min)
|
|
117
|
+
|
|
118
|
+
export function modelBar(input: BarInput): BarModel {
|
|
119
|
+
const { reading, min, max, format, segments, zones, target } = input
|
|
120
|
+
const { span } = spanOf(min, max)
|
|
121
|
+
const zoned = zones !== undefined && zones.length > 0
|
|
122
|
+
const holding = zoned ? findHoldingZone(zones, reading) : undefined
|
|
123
|
+
|
|
124
|
+
const parts = fillParts(input, span, zoned)
|
|
125
|
+
const firstForecast = parts.findIndex((p) => p.forecast)
|
|
126
|
+
const forecastLabels =
|
|
127
|
+
segments?.filter((s) => s.forecast === true).map((s) => `${s.label} ${format(s.value)}`) ?? []
|
|
128
|
+
|
|
129
|
+
const zoneText = !zoned
|
|
130
|
+
? []
|
|
131
|
+
: [
|
|
132
|
+
...zones.map((z) => `${z.label} ${format(z.from)} to ${format(z.to)}`),
|
|
133
|
+
holding === undefined
|
|
134
|
+
? `${format(reading)} is outside every zone`
|
|
135
|
+
: `${format(reading)} is in ${holding.label}`,
|
|
136
|
+
]
|
|
137
|
+
const describedBy = [
|
|
138
|
+
...(segments?.map((s) => segmentText(s, format)) ?? []),
|
|
139
|
+
...zoneText,
|
|
140
|
+
...(target === undefined ? [] : [`Target ${format(target)}`]),
|
|
141
|
+
]
|
|
142
|
+
|
|
143
|
+
return {
|
|
144
|
+
span,
|
|
145
|
+
parts,
|
|
146
|
+
boundaryPct: firstForecast > 0 ? toPct(parts[firstForecast]?.start ?? 0) : undefined,
|
|
147
|
+
forecastText:
|
|
148
|
+
forecastLabels.length === 0
|
|
149
|
+
? null
|
|
150
|
+
: (input.forecastCaption ?? `Forecast: ${forecastLabels.join(', ')}`),
|
|
151
|
+
markerPct: zoned ? toPct((reading - min) / span) : undefined,
|
|
152
|
+
targetPct: target === undefined ? undefined : toPct((target - min) / span),
|
|
153
|
+
startText: holding === undefined ? format(reading) : `${holding.label} · ${format(reading)}`,
|
|
154
|
+
endText: endCaptionText(reading, target, format),
|
|
155
|
+
describedByText: describedBy.length > 0 ? describedBy.join('; ') : null,
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The ring's one arc, as a fraction of the circumference. */
|
|
160
|
+
export const ringFraction = (reading: number, min: number, max: number): number =>
|
|
161
|
+
clamp01((reading - min) / spanOf(min, max).span)
|