basalt-ui 2.20.0 → 2.21.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 (132) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/MIGRATING.md +129 -12
  3. package/agent/agents/basalt-design-reviewer.md +22 -5
  4. package/agent/rules/basalt-tokens.md +2 -2
  5. package/agent/skills/basalt-design/SKILL.md +10 -23
  6. package/agent/skills/basalt-design/references/anti-defaults.md +24 -0
  7. package/agent/skills/basalt-design/references/catalogue.md +48 -0
  8. package/agent/skills/basalt-design/references/concept.md +36 -0
  9. package/agent/skills/basalt-design/references/encoding-rules.md +45 -0
  10. package/agent/skills/basalt-design/references/stat-tile.md +24 -0
  11. package/agent/templates/AGENTS-block.md.tpl +3 -3
  12. package/configs/oxlint-plugin.js +1 -0
  13. package/dist/charts/ChartCard.d.ts +6 -2
  14. package/dist/charts/ChartCard.d.ts.map +1 -1
  15. package/dist/charts/ChartCard.js +4 -0
  16. package/dist/charts/state.d.ts +5 -0
  17. package/dist/charts/state.d.ts.map +1 -1
  18. package/dist/charts/state.js +2 -0
  19. package/dist/cli/check-theme.d.ts.map +1 -1
  20. package/dist/cli/check-theme.js +3 -0
  21. package/dist/cli/help.d.ts.map +1 -1
  22. package/dist/cli/help.js +3 -2
  23. package/dist/cli/index.d.ts +4 -2
  24. package/dist/cli/index.d.ts.map +1 -1
  25. package/dist/cli/index.js +27 -15
  26. package/dist/cli/init.d.ts.map +1 -1
  27. package/dist/cli/init.js +3 -2
  28. package/dist/cli/shot/capture.d.ts.map +1 -1
  29. package/dist/cli/shot/capture.js +6 -1
  30. package/dist/cli/shot/detect.d.ts +51 -0
  31. package/dist/cli/shot/detect.d.ts.map +1 -0
  32. package/dist/cli/shot/detect.js +396 -0
  33. package/dist/cli/shot/index.d.ts.map +1 -1
  34. package/dist/cli/shot/index.js +7 -4
  35. package/dist/cli/shot/measure.d.ts +2 -0
  36. package/dist/cli/shot/measure.d.ts.map +1 -1
  37. package/dist/cli/shot/measure.js +2 -0
  38. package/dist/cli/shot/types.d.ts +4 -1
  39. package/dist/cli/shot/types.d.ts.map +1 -1
  40. package/dist/cli/shot/types.js +2 -0
  41. package/dist/cli/sync.d.ts +2 -0
  42. package/dist/cli/sync.d.ts.map +1 -1
  43. package/dist/cli/sync.js +2 -2
  44. package/dist/common/retry-button.d.ts +12 -0
  45. package/dist/common/retry-button.d.ts.map +1 -0
  46. package/dist/common/retry-button.js +22 -0
  47. package/dist/common/retry-button.module.css +58 -0
  48. package/dist/common/retry-button.module.css.d.ts +8 -0
  49. package/dist/dashboard/bar-list.d.ts +5 -2
  50. package/dist/dashboard/bar-list.d.ts.map +1 -1
  51. package/dist/dashboard/bar-list.js +2 -2
  52. package/dist/dashboard/meter-model.d.ts +34 -6
  53. package/dist/dashboard/meter-model.d.ts.map +1 -1
  54. package/dist/dashboard/meter-model.js +44 -13
  55. package/dist/dashboard/meter-parts.d.ts.map +1 -1
  56. package/dist/dashboard/meter-parts.js +167 -135
  57. package/dist/dashboard/meter.d.ts +11 -7
  58. package/dist/dashboard/meter.d.ts.map +1 -1
  59. package/dist/dashboard/meter.js +5 -1
  60. package/dist/dashboard/meter.module.css +18 -65
  61. package/dist/dashboard/meter.module.css.d.ts +2 -7
  62. package/dist/dashboard/query-state.d.ts +1 -1
  63. package/dist/dashboard/query-state.d.ts.map +1 -1
  64. package/dist/dashboard/query-state.js +3 -2
  65. package/dist/dashboard/stat-card.d.ts.map +1 -1
  66. package/dist/dashboard/stat-card.js +2 -1
  67. package/dist/dashboard/stat-strip.d.ts +17 -0
  68. package/dist/dashboard/stat-strip.d.ts.map +1 -1
  69. package/dist/dashboard/stat-strip.js +35 -5
  70. package/dist/dashboard/stat-strip.module.css +97 -14
  71. package/dist/dashboard/stat-strip.module.css.d.ts +4 -0
  72. package/dist/dashboard/visual-slot.d.ts +2 -0
  73. package/dist/dashboard/visual-slot.d.ts.map +1 -0
  74. package/dist/dashboard/visual-slot.js +5 -0
  75. package/dist/guard/index.d.ts +15 -2
  76. package/dist/guard/index.d.ts.map +1 -1
  77. package/dist/guard/index.js +14 -0
  78. package/dist/guard/palette.d.ts +51 -0
  79. package/dist/guard/palette.d.ts.map +1 -0
  80. package/dist/guard/palette.js +190 -0
  81. package/dist/guard/series-file.d.ts +15 -0
  82. package/dist/guard/series-file.d.ts.map +1 -0
  83. package/dist/guard/series-file.js +29 -0
  84. package/dist/guard/types.d.ts +3 -3
  85. package/dist/guard/types.d.ts.map +1 -1
  86. package/dist/surfaces.d.ts +1 -1
  87. package/dist/surfaces.d.ts.map +1 -1
  88. package/dist/surfaces.js +2 -0
  89. package/dist/theme/controls.module.css +10 -0
  90. package/dist/theme/index.d.ts.map +1 -1
  91. package/dist/theme/index.js +18 -0
  92. package/dist/tokens/oklab.d.ts +28 -0
  93. package/dist/tokens/oklab.d.ts.map +1 -0
  94. package/dist/tokens/oklab.js +73 -0
  95. package/llms.txt +7 -5
  96. package/package.json +1 -1
  97. package/src/charts/ChartCard.tsx +9 -1
  98. package/src/charts/state.tsx +9 -0
  99. package/src/cli/check-theme.ts +3 -0
  100. package/src/cli/help.ts +18 -1
  101. package/src/cli/index.ts +48 -17
  102. package/src/cli/init.ts +2 -1
  103. package/src/cli/shot/capture.ts +15 -2
  104. package/src/cli/shot/detect.ts +533 -0
  105. package/src/cli/shot/index.ts +8 -4
  106. package/src/cli/shot/measure.ts +4 -0
  107. package/src/cli/shot/types.ts +5 -1
  108. package/src/cli/sync.ts +4 -2
  109. package/src/common/retry-button.module.css +58 -0
  110. package/src/common/retry-button.module.css.d.ts +8 -0
  111. package/src/common/retry-button.tsx +29 -0
  112. package/src/dashboard/bar-list.tsx +11 -8
  113. package/src/dashboard/meter-model.ts +91 -20
  114. package/src/dashboard/meter-parts.tsx +155 -115
  115. package/src/dashboard/meter.module.css +18 -65
  116. package/src/dashboard/meter.module.css.d.ts +2 -7
  117. package/src/dashboard/meter.tsx +18 -8
  118. package/src/dashboard/query-state.tsx +4 -7
  119. package/src/dashboard/stat-card.tsx +4 -1
  120. package/src/dashboard/stat-strip.module.css +97 -14
  121. package/src/dashboard/stat-strip.module.css.d.ts +4 -0
  122. package/src/dashboard/stat-strip.tsx +85 -5
  123. package/src/dashboard/visual-slot.ts +8 -0
  124. package/src/guard/index.ts +16 -4
  125. package/src/guard/palette.ts +261 -0
  126. package/src/guard/series-file.ts +51 -0
  127. package/src/guard/types.ts +3 -2
  128. package/src/surfaces.ts +2 -0
  129. package/src/theme/__snapshots__/plain-theme.test.ts.snap +82 -48
  130. package/src/theme/controls.module.css +10 -0
  131. package/src/theme/index.ts +26 -0
  132. package/src/tokens/oklab.ts +97 -0
@@ -0,0 +1,58 @@
1
+ /*
2
+ * The one Retry. ErrorState (Mantine, StatCard / pages), ChartCard's placeholder and a strip cell's
3
+ * error all render this, so the three read as one button. It is a plain element because `./charts`
4
+ * resolves with no Mantine, and it is styled to be a Mantine `size="xs" variant="default"` Button
5
+ * reading the same `--vx-*` tokens the theme binds that button to: panel fill (elevated on hover), no
6
+ * border, `shadow-raised`, the control radius, the xs type size, the theme's inline padding step and
7
+ * Mantine's 30px xs height. `--mantine-scale` carries the app's scale knob, 1 where Mantine is absent.
8
+ */
9
+ .retry {
10
+ display: inline-flex;
11
+ align-items: center;
12
+ justify-content: center;
13
+ flex: none;
14
+ box-sizing: border-box;
15
+ height: calc(1.875rem * var(--mantine-scale, 1));
16
+ padding-block: 0;
17
+ padding-inline: calc(var(--vx-space-stack-md, 0.75rem) * var(--mantine-scale, 1));
18
+ border: calc(0.0625rem * var(--mantine-scale, 1)) solid transparent;
19
+ border-radius: var(--vx-radius-ctrl);
20
+ background: var(--vx-surface-panel);
21
+ box-shadow: var(--vx-shadow-raised);
22
+ color: var(--mantine-color-default-color, var(--vx-ink));
23
+ font: inherit;
24
+ font-size: var(--vx-text-xs);
25
+ font-weight: 500;
26
+ line-height: 1;
27
+ white-space: nowrap;
28
+ cursor: pointer;
29
+ user-select: none;
30
+ transition: box-shadow 120ms ease;
31
+ }
32
+
33
+ .retry:focus-visible {
34
+ outline: calc(0.125rem * var(--mantine-scale, 1)) solid
35
+ var(--mantine-primary-color-filled, var(--vx-accent-fill));
36
+ outline-offset: calc(0.125rem * var(--mantine-scale, 1));
37
+ }
38
+
39
+ /* Hover is a pointer affordance: a touch tap would leave it stuck on. */
40
+ @media (hover: hover) {
41
+ .retry:hover:not(:disabled) {
42
+ background: var(--vx-surface-elevated);
43
+ }
44
+ }
45
+
46
+ /* Busy is Mantine's disabled paint: its own disabled colour and background, flat, no border. */
47
+ .retry:disabled {
48
+ background: var(--mantine-color-disabled, var(--vx-surface-subtle));
49
+ color: var(--mantine-color-disabled-color, var(--vx-muted));
50
+ box-shadow: none;
51
+ cursor: not-allowed;
52
+ }
53
+
54
+ @media (prefers-reduced-motion: reduce) {
55
+ .retry {
56
+ transition: none;
57
+ }
58
+ }
@@ -0,0 +1,8 @@
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 retry: string
7
+ }
8
+ export default classes
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The one Retry button of the shared error anatomy (status dot + word + message + Retry). Internal:
3
+ * `ErrorState`, `ChartCard`'s placeholder and a strip cell's error all render it, so they cannot
4
+ * drift. Mantine-free — `./charts` uses it with no `@mantine/*` installed.
5
+ */
6
+ import type { ReactElement } from 'react'
7
+ import classes from './retry-button.module.css'
8
+
9
+ export function RetryButton({
10
+ onClick,
11
+ retrying = false,
12
+ }: {
13
+ onClick: () => void
14
+ /** A refetch is in flight: inert and marked busy. */
15
+ retrying?: boolean
16
+ }): ReactElement {
17
+ return (
18
+ <button
19
+ type="button"
20
+ className={classes.retry}
21
+ data-basalt-retry=""
22
+ disabled={retrying}
23
+ {...(retrying && { 'aria-busy': true })}
24
+ onClick={onClick}
25
+ >
26
+ Retry
27
+ </button>
28
+ )
29
+ }
@@ -8,8 +8,9 @@
8
8
  * A row may carry its own `max` (points of 40 / 35 / 25): its bar fills value / row.max and the value
9
9
  * column reads "32 / 40". The shared scale — `max` prop, else the largest value — is computed over the
10
10
  * rows WITHOUT their own `max` only. A row's `tick` (on that row's scale) draws a hairline across the
11
- * bar, named for assistive tech. `variant="thin"` puts the label on its own line above a thin bar with
12
- * the value right-aligned on the label line.
11
+ * bar, named for assistive tech. The default (`variant="thin"`) puts the label on its own line above a
12
+ * thin bar with the value right-aligned on the label line; `variant="inline"` is the older heavy track
13
+ * with the label inside it.
13
14
  *
14
15
  * Thin rows sit flush: no inline inset on the label or the rail.
15
16
  *
@@ -22,10 +23,9 @@
22
23
  * // Recovery contributors on a fixed 0–100 scale, the qualitative level as the secondary value:
23
24
  * <BarList label="Recovery contributors" max={100} items={[{ label: 'Sleep', value: 82, secondary: 'Good' }]} />
24
25
  *
25
- * // Points of different maxima, thin rows, a threshold tick ("32 / 40 pts"; the tick is named for AT):
26
+ * // Points of different maxima, a threshold tick ("32 / 40 pts"; the tick is named for AT):
26
27
  * <BarList
27
28
  * label="Recovery contributors"
28
- * variant="thin"
29
29
  * format={(n, part) => (part === 'max' ? `${n} pts` : String(n))}
30
30
  * items={[{ label: 'Sleep', value: 32, max: 40, tick: 30, tickLabel: 'Target' }, { label: 'HRV', value: 14, max: 35 }]}
31
31
  * />
@@ -69,8 +69,11 @@ export type BarListProps = BasaltProps & {
69
69
  format?: (value: number, part: 'value' | 'max') => string
70
70
  /** Scale end shared by rows without their own `max`. Default: the largest of those rows' values. */
71
71
  max?: number
72
- /** `thin`: label on its own line above a thin bar, value right-aligned on that line. */
73
- variant?: 'default' | 'thin'
72
+ /**
73
+ * `thin` (default): label on its own line above a thin bar, value right-aligned on that line.
74
+ * `inline`: the label sits inside a heavier track, the value outside it.
75
+ */
76
+ variant?: 'thin' | 'inline'
74
77
  /** The first row's bar takes the accent. Off by default. */
75
78
  accentLeader?: boolean
76
79
  /** Renders row-shaped skeletons. */
@@ -90,7 +93,7 @@ export function BarList({
90
93
  items,
91
94
  format = asText,
92
95
  max,
93
- variant = 'default',
96
+ variant = 'thin',
94
97
  accentLeader = false,
95
98
  loading = false,
96
99
  loadingRows = 5,
@@ -133,7 +136,7 @@ export function BarList({
133
136
  role="list"
134
137
  aria-label={label}
135
138
  data-secondary={hasSecondary ? '' : undefined}
136
- data-variant={thin ? 'thin' : undefined}
139
+ data-variant={variant}
137
140
  >
138
141
  {items.map((item, i) => {
139
142
  const isLeader = accentLeader && i === 0
@@ -6,7 +6,17 @@ import type { ReactNode } from 'react'
6
6
  import { clamp01, toPct } from './scale'
7
7
 
8
8
  export type MeterSegment = { value: number; label: string; color?: string; forecast?: boolean }
9
- export type MeterZone = { from: number; to: number; label: string; color?: string }
9
+ export type MeterZone = {
10
+ from: number
11
+ to: number
12
+ label: string
13
+ /**
14
+ * A shorter name for a narrow track. The row tries `label`, then `short`, and only then hides the
15
+ * name; the holding zone always shows its full `label`. The described-by text keeps `label`.
16
+ */
17
+ short?: string
18
+ color?: string
19
+ }
10
20
  /** A mark on the track at `at` (in the reading's units). A label is captioned beside it. */
11
21
  export type MeterTick = { at: number; label?: string }
12
22
 
@@ -27,8 +37,16 @@ export type Part = {
27
37
  /** One categorical part's caption: its position key, name, formatted amount and fill colour (`undefined` = neutral). */
28
38
  export type PartCaption = { key: string; label: string; text: string; color: string | undefined }
29
39
 
30
- /** One zone's name on the band: where its band starts (percent) and whether it holds the reading. */
31
- export type ZoneLabel = { key: string; label: string; startPct: number; holding: boolean }
40
+ /** One zone's name on the label row: its span's centre and width (percent) and whether it holds the reading. */
41
+ export type ZoneLabel = {
42
+ key: string
43
+ label: string
44
+ /** The fallback name, when the zone has one. */
45
+ short?: string
46
+ centrePct: number
47
+ widthPct: number
48
+ holding: boolean
49
+ }
32
50
 
33
51
  /**
34
52
  * What the caption row says. `reading`: the formatted reading; `parts`: categorical segments name
@@ -122,18 +140,66 @@ export const LABEL_SUBPIXEL = 0.5
122
140
  export type LabelBox = { left: number; right: number }
123
141
 
124
142
  /**
125
- * Whether every zone name fits on the band: inside `[0, rowWidth]` and clear of every other name
126
- * (pairwise, so a long name cannot hide behind a short one between it and a distant neighbour).
127
- * Boxes are relative to the row's own start edge.
143
+ * A label on the shared row: its measured box and, for a zone name, the span it must stay inside.
144
+ * The holding zone's name never hides for width: it ignores its span and is shifted into the row.
128
145
  */
129
- export function zoneLabelsFit(boxes: readonly LabelBox[], rowWidth: number): boolean {
130
- const sorted = boxes.toSorted((a, b) => a.left - b.left)
131
- return sorted.every(
132
- (a, i) =>
133
- a.left >= -LABEL_SUBPIXEL &&
134
- a.right <= rowWidth + LABEL_SUBPIXEL &&
135
- sorted.slice(i + 1).every((b) => a.right <= b.left + LABEL_SUBPIXEL),
136
- )
146
+ export type RowLabel = { box: LabelBox; span?: LabelBox; holding?: boolean; short?: LabelBox }
147
+
148
+ /** The placement of the row's labels, index-aligned with the input. */
149
+ export type RowPlacement = {
150
+ shown: boolean[]
151
+ /** Index-aligned with `shown`: the label shows as its `short` box rather than the full one. */
152
+ short: boolean[]
153
+ /** Pixels a shown label moves along the row's physical x axis to stay inside it (0 unless clamped). */
154
+ shift: number[]
155
+ }
156
+
157
+ /**
158
+ * Which labels of the row show, in input order. The holding zone's name claims its place first (it
159
+ * is the reading's verdict, so it never hides for width: it may spill past its span, shifted inside
160
+ * the row); the labels without a span (the end ticks) go next; every other zone name then shows only
161
+ * when it lies inside the row and its own span and clears every label already kept, trying its full
162
+ * name and then its `short` box. A hidden name is still named in the described-by text.
163
+ */
164
+ export function placeRowLabels(labels: readonly RowLabel[], rowWidth: number): RowPlacement {
165
+ const shown = labels.map(() => false)
166
+ const short = labels.map(() => false)
167
+ const shift = labels.map(() => 0)
168
+ const kept: LabelBox[] = []
169
+ const rank = (l: RowLabel) => (l.holding ? 0 : l.span ? 2 : 1)
170
+ const order = labels
171
+ .map((_, i) => i)
172
+ .toSorted((a, b) => rank(labels[a] as RowLabel) - rank(labels[b] as RowLabel))
173
+ const clears = (b: LabelBox) =>
174
+ !kept.some((k) => b.left < k.right - LABEL_SUBPIXEL && k.left < b.right - LABEL_SUBPIXEL)
175
+ for (const i of order) {
176
+ const label = labels[i] as RowLabel
177
+ const { span } = label
178
+ let box = label.box
179
+ if (label.holding) {
180
+ const width = box.right - box.left
181
+ const left = Math.max(0, Math.min(box.left, rowWidth - width))
182
+ shift[i] = left - box.left
183
+ box = { left, right: left + width }
184
+ if (!clears(box)) continue
185
+ shown[i] = true
186
+ kept.push(box)
187
+ continue
188
+ }
189
+ const fits = (b: LabelBox) =>
190
+ b.left >= -LABEL_SUBPIXEL &&
191
+ b.right <= rowWidth + LABEL_SUBPIXEL &&
192
+ (span === undefined ||
193
+ (b.left >= span.left - LABEL_SUBPIXEL && b.right <= span.right + LABEL_SUBPIXEL)) &&
194
+ clears(b)
195
+ const useShort = !fits(box) && label.short !== undefined && fits(label.short)
196
+ if (useShort) box = label.short as LabelBox
197
+ else if (!fits(box)) continue
198
+ shown[i] = true
199
+ short[i] = useShort
200
+ kept.push(box)
201
+ }
202
+ return { shown, short, shift }
137
203
  }
138
204
 
139
205
  /** A zone band as left edge + width in percent, clipped to the track. */
@@ -269,12 +335,17 @@ export function modelBar(input: BarInput): BarModel {
269
335
  partCaptions,
270
336
  zoneLabels: !zoned
271
337
  ? []
272
- : zones.map((z, i) => ({
273
- key: String(i),
274
- label: z.label,
275
- startPct: zoneBand(z, min, span).start,
276
- holding: z === holding,
277
- })),
338
+ : zones.map((z, i) => {
339
+ const band = zoneBand(z, min, span)
340
+ return {
341
+ key: String(i),
342
+ label: z.label,
343
+ ...(z.short !== undefined && { short: z.short }),
344
+ centrePct: band.start + band.width / 2,
345
+ widthPct: band.width,
346
+ holding: z === holding,
347
+ }
348
+ }),
278
349
  ticks,
279
350
  markerPct: zoned ? toPct((reading - min) / span) : undefined,
280
351
  targetPct: target === undefined ? undefined : toPct((target - min) / span),
@@ -1,7 +1,7 @@
1
1
  /** Meter's internal pieces: bar, ring, empty and loading. `meter.tsx` dispatches between them. */
2
2
  import { Skeleton, VisuallyHidden } from '@mantine/core'
3
- import { useId, useRef, useState } from 'react'
4
- import type { CSSProperties, HTMLAttributes, ReactNode, RefObject } from 'react'
3
+ import { useContext, useId, useRef, useState } from 'react'
4
+ import type { CSSProperties, ReactNode, RefObject } from 'react'
5
5
  import { useIsomorphicLayoutEffect } from '../common/isomorphic-layout-effect'
6
6
  import { cx } from '../common/props'
7
7
  import {
@@ -9,11 +9,20 @@ import {
9
9
  modelBar,
10
10
  ringFraction,
11
11
  startCaptionText,
12
+ placeRowLabels,
12
13
  zoneBand,
13
- zoneLabelsFit,
14
14
  } from './meter-model'
15
- import type { MeterSegment, MeterTick, MeterZone, Part, TickMark, ZoneLabel } from './meter-model'
15
+ import type {
16
+ MeterSegment,
17
+ MeterTick,
18
+ MeterZone,
19
+ Part,
20
+ RowLabel,
21
+ TickMark,
22
+ ZoneLabel,
23
+ } from './meter-model'
16
24
  import classes from './meter.module.css'
25
+ import { VisualSlotContext } from './visual-slot'
17
26
  import { toPct } from './scale'
18
27
 
19
28
  export type Shell = {
@@ -172,33 +181,72 @@ function zoneStyle(zone: MeterZone, index: number, count: number, min: number, s
172
181
  } satisfies CSSProperties
173
182
  }
174
183
 
175
- /**
176
- * Joins the names with a character no label carries, so the effect re-runs only when they change.
177
- * The holding zone is part of the key: its label is bolder, so a reading that crosses a boundary
178
- * changes widths with no row resize.
179
- */
180
- const labelsKey = (labels: readonly ZoneLabel[]) =>
181
- labels.map((l) => l.label + (l.holding ? '*' : '')).join('\u0000')
184
+ /** One label on the row: its span in percent of the row (a zone name) or none (an end tick). */
185
+ type RowSlot = { spanPct?: readonly [number, number]; holding?: boolean }
186
+
187
+ type RowLayout = { shown: boolean[]; short: boolean[]; shift: number[] }
188
+ const sameLayout = (a: RowLayout, b: RowLayout) =>
189
+ a.shown.length === b.shown.length &&
190
+ a.shown.every(
191
+ (v, i) => v === b.shown[i] && a.short[i] === b.short[i] && a.shift[i] === b.shift[i],
192
+ )
182
193
 
183
194
  /**
184
- * Whether the zone names fit on the band, re-measured when the row resizes, when web fonts finish
185
- * loading (a mono swap changes label widths without resizing the row) and when the names change.
186
- * Server markup shows the band; the list may appear after mount, when the measurement fails.
195
+ * Which row labels show, re-measured when the row resizes, when web fonts finish loading (a swap
196
+ * changes label widths without resizing the row) and when the labels change. Server markup shows
197
+ * every label; a name that does not fit its span (or clashes with a tick) hides after measuring.
198
+ * `slots` is index-aligned with the row's first children; the children after them are the short
199
+ * twins, `shortOf[n]` being the label index the n-th twin stands in for.
187
200
  */
188
- function useZoneLabelLayout(rowRef: RefObject<HTMLDivElement | null>, key: string): boolean {
189
- const [fits, setFits] = useState(true)
201
+ function useRowLabelLayout(
202
+ rowRef: RefObject<HTMLDivElement | null>,
203
+ slots: readonly RowSlot[],
204
+ shortOf: readonly number[],
205
+ key: string,
206
+ ): RowLayout {
207
+ const [layout, setLayout] = useState<RowLayout>({ shown: [], short: [], shift: [] })
208
+ const slotsRef = useRef(slots)
209
+ const shortOfRef = useRef(shortOf)
210
+ // Declared before the measuring effect so it reads this render's slots.
211
+ useIsomorphicLayoutEffect(() => {
212
+ slotsRef.current = slots
213
+ shortOfRef.current = shortOf
214
+ })
190
215
 
191
- // Keyed on a string of the names, not the `labels` array: the model rebuilds that every render.
216
+ // Keyed on a string of the labels, not the `slots` array: the model rebuilds that every render.
192
217
  useIsomorphicLayoutEffect(() => {
193
218
  const row = rowRef.current
194
219
  if (!row) return
195
220
  const measure = () => {
196
221
  const origin = row.getBoundingClientRect()
197
- const boxes = [...row.children].map((c) => {
222
+ const rtl = getComputedStyle(row).direction === 'rtl'
223
+ const edge = (pct: number) => (origin.width * (rtl ? 100 - pct : pct)) / 100
224
+ const children = [...row.children]
225
+ const labels: RowLabel[] = children.slice(0, slotsRef.current.length).map((c, i) => {
198
226
  const r = c.getBoundingClientRect()
199
- return { left: r.left - origin.left, right: r.right - origin.left }
227
+ const slot = slotsRef.current[i]
228
+ const pct = slot?.spanPct
229
+ const [a, b] = pct ? [edge(pct[0]), edge(pct[1])] : []
230
+ return {
231
+ box: { left: r.left - origin.left, right: r.right - origin.left },
232
+ ...(a !== undefined &&
233
+ b !== undefined && { span: { left: Math.min(a, b), right: Math.max(a, b) } }),
234
+ ...(slot?.holding && { holding: true }),
235
+ }
200
236
  })
201
- setFits(zoneLabelsFit(boxes, origin.width))
237
+ shortOfRef.current.forEach((labelIndex, n) => {
238
+ const r = children[slotsRef.current.length + n]?.getBoundingClientRect()
239
+ const label = labels[labelIndex]
240
+ if (r && label) label.short = { left: r.left - origin.left, right: r.right - origin.left }
241
+ })
242
+ const placed = placeRowLabels(labels, origin.width)
243
+ // The hook measures on the physical x axis; the margin is logical, so it flips with `dir`.
244
+ const next = {
245
+ shown: placed.shown,
246
+ short: placed.short,
247
+ shift: placed.shift.map((v) => (rtl ? -v : v)),
248
+ }
249
+ setLayout((prev) => (sameLayout(prev, next) ? prev : next))
202
250
  }
203
251
  measure()
204
252
  const observer = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(measure)
@@ -216,7 +264,7 @@ function useZoneLabelLayout(rowRef: RefObject<HTMLDivElement | null>, key: strin
216
264
  }
217
265
  }, [rowRef, key])
218
266
 
219
- return fits
267
+ return layout
220
268
  }
221
269
 
222
270
  /**
@@ -261,103 +309,88 @@ function ZoneReading({ pct, children }: { pct: number; children: ReactNode }) {
261
309
  )
262
310
  }
263
311
 
264
- function ZoneName({ label, ...rest }: { label: ZoneLabel } & HTMLAttributes<HTMLSpanElement>) {
265
- return (
266
- <span
267
- {...rest}
268
- className={cx(rest.className, label.holding && classes.zoneLabelHolding)}
269
- data-meter-zone-label={label.label}
270
- data-holding={label.holding || undefined}
271
- >
272
- {label.label}
273
- </span>
274
- )
275
- }
276
-
277
- /**
278
- * Names each zone under its band, the holding one in ink and a heavier weight. Labels sit
279
- * left-aligned at their band start; when two would overlap (or one would leave the row) the band
280
- * hides and the same names wrap as a list in zone order instead. The band stays laid out (hidden,
281
- * not removed) so a resize can measure it again. Decorative: the zone names and the holding zone
282
- * are in the described-by text.
283
- */
284
- function ZoneLabels({ labels }: { labels: readonly ZoneLabel[] }) {
285
- const rowRef = useRef<HTMLDivElement>(null)
286
- const fits = useZoneLabelLayout(rowRef, labelsKey(labels))
287
-
288
- return (
289
- <>
290
- <div
291
- ref={rowRef}
292
- className={classes.zoneBand}
293
- data-meter-zone-band
294
- data-collapsed={fits ? undefined : ''}
295
- aria-hidden
296
- >
297
- {labels.map((l) => (
298
- <ZoneName
299
- key={l.key}
300
- label={l}
301
- className={classes.zoneLabel}
302
- style={{ insetInlineStart: `${l.startPct}%` }}
303
- />
304
- ))}
305
- </div>
306
- {!fits && (
307
- <div className={classes.zoneList} data-meter-zone-list aria-hidden>
308
- {labels.map((l) => (
309
- <ZoneName key={l.key} label={l} className={classes.zoneListItem} />
310
- ))}
311
- </div>
312
- )}
313
- </>
314
- )
315
- }
316
-
317
312
  /** Ticks past the middle caption to the left of their mark, so a caption near the end stays on the row. */
318
313
  const TICK_LABEL_FLIP_PCT = 50
319
314
 
320
315
  /**
321
- * Captions the labelled ticks above the track, each hugging its mark. Same fit rule as the zone names:
322
- * when two would overlap (or one would leave the row) the band hides and the labels wrap as a list in
323
- * tick order. Decorative: the ticks are in the described-by text.
316
+ * The one label row: each zone name centred under its own span and the labelled ticks hugging their
317
+ * marks (the end ticks sit at the row's ends), all on one baseline. A name wider than its span, or
318
+ * clashing with a tick or a neighbour, hides (still laid out, so a resize can measure it again) and is
319
+ * still named in the described-by text; the holding zone is ink and heavier. Decorative.
324
320
  */
325
- function TickLabels({ ticks }: { ticks: readonly TickMark[] }) {
321
+ function LabelRow({ zones, ticks }: { zones: readonly ZoneLabel[]; ticks: readonly TickMark[] }) {
326
322
  const rowRef = useRef<HTMLDivElement>(null)
327
- const fits = useZoneLabelLayout(rowRef, ticks.map((t) => `${t.label}@${t.pct}`).join('\u0000'))
323
+ const slots: RowSlot[] = [
324
+ ...ticks.map((): RowSlot => ({})),
325
+ ...zones.map((z): RowSlot => ({
326
+ spanPct: [z.centrePct - z.widthPct / 2, z.centrePct + z.widthPct / 2],
327
+ holding: z.holding,
328
+ })),
329
+ ]
330
+ const key = [
331
+ ...ticks.map((t) => `${t.label}@${t.pct}`),
332
+ ...zones.map((z) => `${z.label}${z.holding ? '*' : ''}@${z.centrePct}`),
333
+ ].join('\u0000')
334
+ // The holding name never shortens, so its zone has no twin.
335
+ const twins = zones.flatMap((z, i) => (z.short !== undefined && !z.holding ? [i] : []))
336
+ const { shown, short, shift } = useRowLabelLayout(
337
+ rowRef,
338
+ slots,
339
+ twins.map((i) => ticks.length + i),
340
+ `${key}\u0001${twins.map((i) => zones[i]?.short).join('\u0000')}`,
341
+ )
342
+ const hidden = (i: number) => (shown[i] === false || short[i] === true ? '' : undefined)
343
+ const nudge = (i: number): CSSProperties =>
344
+ shift[i] ? { marginInlineStart: `${shift[i]}px` } : {}
328
345
  return (
329
- <div className={classes.tickLabels}>
330
- <div
331
- ref={rowRef}
332
- className={classes.tickBand}
333
- data-meter-tick-band
334
- data-collapsed={fits ? undefined : ''}
335
- aria-hidden
336
- >
337
- {ticks.map((t) => (
346
+ <div
347
+ ref={rowRef}
348
+ className={classes.labelRow}
349
+ {...(zones.length > 0 ? { 'data-meter-zone-band': '' } : { 'data-meter-tick-band': '' })}
350
+ aria-hidden
351
+ >
352
+ {ticks.map((t, i) => (
353
+ <span
354
+ key={`t${t.key}`}
355
+ className={classes.rowLabel}
356
+ data-meter-tick-label=""
357
+ data-hidden={hidden(i)}
358
+ style={
359
+ t.pct > TICK_LABEL_FLIP_PCT
360
+ ? { insetInlineEnd: `${100 - t.pct}%` }
361
+ : { insetInlineStart: `${t.pct}%` }
362
+ }
363
+ >
364
+ {t.label}
365
+ </span>
366
+ ))}
367
+ {zones.map((z, i) => (
368
+ <span
369
+ key={`z${z.key}`}
370
+ className={cx(classes.rowLabel, classes.zoneLabel, z.holding && classes.zoneLabelHolding)}
371
+ data-meter-zone-label={z.label}
372
+ data-holding={z.holding || undefined}
373
+ data-hidden={hidden(ticks.length + i)}
374
+ style={{ insetInlineStart: `${z.centrePct}%`, ...nudge(ticks.length + i) }}
375
+ >
376
+ {z.label}
377
+ </span>
378
+ ))}
379
+ {twins.map((zi) => {
380
+ const z = zones[zi] as ZoneLabel
381
+ const i = ticks.length + zi
382
+ return (
338
383
  <span
339
- key={t.key}
340
- className={classes.tickLabel}
341
- data-meter-tick-label=""
342
- style={
343
- t.pct > TICK_LABEL_FLIP_PCT
344
- ? { insetInlineEnd: `${100 - t.pct}%` }
345
- : { insetInlineStart: `${t.pct}%` }
346
- }
384
+ key={`s${z.key}`}
385
+ className={cx(classes.rowLabel, classes.zoneLabel)}
386
+ data-meter-zone-short={z.label}
387
+ data-hidden={short[i] === true ? undefined : ''}
388
+ style={{ insetInlineStart: `${z.centrePct}%`, ...nudge(i) }}
347
389
  >
348
- {t.label}
390
+ {z.short}
349
391
  </span>
350
- ))}
351
- </div>
352
- {!fits && (
353
- <div className={classes.zoneList} data-meter-tick-list aria-hidden>
354
- {ticks.map((t) => (
355
- <span key={t.key} className={classes.zoneListItem}>
356
- {t.label}
357
- </span>
358
- ))}
359
- </div>
360
- )}
392
+ )
393
+ })}
361
394
  </div>
362
395
  )
363
396
  }
@@ -383,23 +416,30 @@ export function MeterBar(props: {
383
416
  const describedId = useId()
384
417
  const model = modelBar(props)
385
418
  const compact = shell.row
386
- const start = compact ? null : startCaptionText(model, props.startCaption)
419
+ // A host that already shows the value as its hero (StatCard, a strip cell) owns the reading: a
420
+ // zoned track keeps its marker and zone labels but does not print the number a second time. A
421
+ // consumer's own `startCaption` is not the reading and still renders.
422
+ const hosted =
423
+ useContext(VisualSlotContext) &&
424
+ model.markerPct !== undefined &&
425
+ props.startCaption === undefined
426
+ const start = compact || hosted ? null : startCaptionText(model, props.startCaption)
387
427
  const end = compact ? null : props.endCaption === undefined ? model.endText : props.endCaption
388
428
  const anchored = model.markerPct !== undefined && start !== null
389
429
  const hasCaptions =
390
430
  (start !== null && !anchored) || end !== null || (!compact && model.forecastText !== null)
391
431
  const hasParts = !compact && model.partCaptions.length > 0
392
432
  const tickLabels = compact ? [] : model.ticks.filter((t) => t.label !== undefined)
433
+ const zoneLabels = compact ? [] : model.zoneLabels
393
434
  const describedBy =
394
435
  model.describedByText === null ? {} : ({ 'aria-describedby': describedId } as const)
395
436
 
396
437
  const root = rootProps(shell)
397
438
  return (
398
- <div
399
- {...root}
400
- className={cx(root.className, !compact && model.zoneLabels.length > 0 && classes.zoned)}
401
- >
402
- {tickLabels.length > 0 && <TickLabels ticks={tickLabels} />}
439
+ <div {...root} className={root.className}>
440
+ {tickLabels.length > 0 && zoneLabels.length === 0 && (
441
+ <LabelRow zones={zoneLabels} ticks={tickLabels} />
442
+ )}
403
443
  <div
404
444
  className={classes.trackBox}
405
445
  aria-label={label}
@@ -435,7 +475,7 @@ export function MeterBar(props: {
435
475
  ))}
436
476
  <Tick kind="target" className={classes.tick} pct={model.targetPct} />
437
477
  </div>
438
- {!compact && model.zoneLabels.length > 0 && <ZoneLabels labels={model.zoneLabels} />}
478
+ {zoneLabels.length > 0 && <LabelRow zones={zoneLabels} ticks={tickLabels} />}
439
479
  {anchored && <ZoneReading pct={model.markerPct ?? 0}>{start}</ZoneReading>}
440
480
  {model.describedByText !== null && (
441
481
  <VisuallyHidden id={describedId} className={classes.summary}>