@behavioral-agentic-design-system/core 0.40.0 → 0.45.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 (148) hide show
  1. package/README.md +2 -0
  2. package/package.json +41 -9
  3. package/scripts/a11y-lint.cjs +66 -3
  4. package/scripts/check-spec.mjs +73 -0
  5. package/scripts/deal-directions.mjs +186 -0
  6. package/scripts/health-report.mjs +23 -3
  7. package/scripts/lib/counted-lint.mjs +100 -0
  8. package/scripts/lib/marketing-library.mjs +129 -0
  9. package/scripts/lib/on-system.mjs +249 -0
  10. package/scripts/lib/random.mjs +22 -0
  11. package/scripts/lib/spec-parse.d.mts +25 -0
  12. package/scripts/lib/spec-parse.mjs +188 -0
  13. package/scripts/lib/tells.mjs +128 -0
  14. package/scripts/lint-css-vars.mjs +175 -0
  15. package/scripts/lint-html-nesting.mjs +116 -0
  16. package/scripts/lint-live-ctas.mjs +138 -0
  17. package/scripts/lint-slop.mjs +25 -1
  18. package/scripts/on-system-score.mjs +95 -0
  19. package/scripts/slop-rules.mjs +1 -1
  20. package/scripts/source-images.mjs +180 -0
  21. package/scripts/ux-tells.mjs +78 -0
  22. package/scripts/wcag-audit.cjs +72 -5
  23. package/src/api/brand-colors.ts +3 -0
  24. package/src/api/brand-fonts.ts +3 -0
  25. package/src/api/brand-mark.ts +6 -1
  26. package/src/api/dev-write-guard.ts +53 -0
  27. package/src/api/layers/file.ts +7 -4
  28. package/src/api/onboarding-extract.ts +85 -30
  29. package/src/api/onboarding.ts +3 -0
  30. package/src/api/save-tokens.ts +3 -0
  31. package/src/app/layout.tsx +6 -0
  32. package/src/app/opengraph-image.tsx +5 -0
  33. package/src/app/preview/canvas/page.tsx +12 -0
  34. package/src/app/preview/components/page.tsx +2003 -2
  35. package/src/app/preview/studio/blank-screen.tsx +143 -0
  36. package/src/app/preview/studio/page.tsx +7 -0
  37. package/src/app/shell.tsx +168 -49
  38. package/src/components/Foundations/Motion.stories.tsx +1 -0
  39. package/src/components/canvas/canvas.tsx +458 -0
  40. package/src/components/canvas/layout.ts +72 -0
  41. package/src/components/canvas/parse-canvas.ts +32 -0
  42. package/src/components/canvas/sample.ts +90 -0
  43. package/src/components/canvas/spec-frame.tsx +43 -0
  44. package/src/components/canvas/types.ts +33 -0
  45. package/src/components/customize/design-controls.tsx +16 -1
  46. package/src/components/docs-tab.tsx +7 -7
  47. package/src/components/home-recent.tsx +73 -0
  48. package/src/components/home-tab.tsx +13 -13
  49. package/src/components/layers-tab.tsx +2 -2
  50. package/src/components/markdown-preview.tsx +60 -12
  51. package/src/components/studio/control-panel.tsx +299 -0
  52. package/src/components/studio/control-row.tsx +77 -0
  53. package/src/components/studio/preview-frame.tsx +165 -0
  54. package/src/components/studio/preview-pane.tsx +247 -0
  55. package/src/components/studio/studio.tsx +158 -0
  56. package/src/components/studio/types.ts +218 -0
  57. package/src/components/studio/use-studio-tweaks.ts +128 -0
  58. package/src/components/studio/use-studio-view-state.ts +72 -0
  59. package/src/components/ui/anchor.tsx +37 -3
  60. package/src/components/ui/attachment.tsx +211 -0
  61. package/src/components/ui/autocomplete.tsx +1 -1
  62. package/src/components/ui/chart.tsx +3 -0
  63. package/src/components/ui/code.tsx +1 -1
  64. package/src/components/ui/color-picker.tsx +21 -5
  65. package/src/components/ui/data-table.tsx +64 -3
  66. package/src/components/ui/date-field.tsx +1 -1
  67. package/src/components/ui/editable.tsx +1 -0
  68. package/src/components/ui/faceted-filter.tsx +187 -0
  69. package/src/components/ui/gauge-chart.tsx +252 -0
  70. package/src/components/ui/heatmap.tsx +256 -0
  71. package/src/components/ui/index.ts +9 -0
  72. package/src/components/ui/infinite-scroll.tsx +103 -0
  73. package/src/components/ui/inline-edit.tsx +175 -0
  74. package/src/components/ui/json-input.tsx +351 -0
  75. package/src/components/ui/month-picker.tsx +1 -1
  76. package/src/components/ui/navigation-progress.tsx +281 -0
  77. package/src/components/ui/number-input.tsx +27 -7
  78. package/src/components/ui/otp-input.tsx +208 -0
  79. package/src/components/ui/password-input.tsx +2 -1
  80. package/src/components/ui/password-strength-input.tsx +288 -0
  81. package/src/components/ui/phone-input.tsx +274 -0
  82. package/src/components/ui/pill.tsx +140 -0
  83. package/src/components/ui/popover.tsx +27 -4
  84. package/src/components/ui/scroll-progress.tsx +100 -0
  85. package/src/components/ui/search-input.tsx +1 -1
  86. package/src/components/ui/snackbar.tsx +393 -0
  87. package/src/components/ui/sortable-list.tsx +342 -0
  88. package/src/components/ui/squircle.tsx +1 -1
  89. package/src/components/ui/table.tsx +1 -1
  90. package/src/components/ui/tags-input.tsx +1 -1
  91. package/src/components/ui/timer.tsx +1 -0
  92. package/src/components/ui/tour.tsx +1 -3
  93. package/src/components/ui/transfer-list.tsx +13 -26
  94. package/src/components/ui/week-picker.tsx +1 -1
  95. package/src/components/ui/year-picker.tsx +1 -1
  96. package/src/data/component-added.json +958 -0
  97. package/src/data/docs-index.ts +36 -0
  98. package/src/hooks/use-global-mono-font.ts +1 -0
  99. package/src/hooks/use-global-primary-color.ts +1 -0
  100. package/src/hooks/use-global-sans-font.ts +1 -0
  101. package/src/hooks/use-global-serif-font.ts +1 -0
  102. package/src/hooks/use-global-type-scale.ts +17 -2
  103. package/src/hooks/use-mobile.ts +2 -0
  104. package/src/hooks/use-sync-type-scale.ts +7 -11
  105. package/src/lib/clamp.ts +2 -0
  106. package/src/lib/spec-parse.ts +4 -0
  107. package/src/lib/svg-sanitize.ts +19 -9
  108. package/src/stories/Anchor.stories.tsx +54 -0
  109. package/src/stories/Attachment.stories.tsx +189 -0
  110. package/src/stories/Autocomplete.stories.tsx +2 -0
  111. package/src/stories/Canvas.stories.tsx +45 -0
  112. package/src/stories/Chart.stories.tsx +4 -0
  113. package/src/stories/Code.stories.tsx +1 -0
  114. package/src/stories/ColorPicker.stories.tsx +41 -0
  115. package/src/stories/DataTable.stories.tsx +30 -0
  116. package/src/stories/DateField.stories.tsx +21 -0
  117. package/src/stories/Editable.stories.tsx +2 -0
  118. package/src/stories/FacetedFilter.stories.tsx +197 -0
  119. package/src/stories/GaugeChart.stories.tsx +169 -0
  120. package/src/stories/Heatmap.stories.tsx +172 -0
  121. package/src/stories/InfiniteScroll.stories.tsx +225 -0
  122. package/src/stories/InlineEdit.stories.tsx +106 -0
  123. package/src/stories/JsonInput.stories.tsx +212 -0
  124. package/src/stories/MarkdownPreview.stories.tsx +53 -0
  125. package/src/stories/MonthPicker.stories.tsx +21 -0
  126. package/src/stories/NavigationProgress.stories.tsx +159 -0
  127. package/src/stories/NumberInput.stories.tsx +26 -0
  128. package/src/stories/OtpInput.stories.tsx +110 -0
  129. package/src/stories/PasswordInput.stories.tsx +4 -0
  130. package/src/stories/PasswordStrengthInput.stories.tsx +211 -0
  131. package/src/stories/PhoneInput.stories.tsx +127 -0
  132. package/src/stories/Pill.stories.tsx +201 -0
  133. package/src/stories/Popover.stories.tsx +29 -1
  134. package/src/stories/Portal.stories.tsx +3 -1
  135. package/src/stories/ScrollProgress.stories.tsx +117 -0
  136. package/src/stories/SearchInput.stories.tsx +2 -0
  137. package/src/stories/Snackbar.stories.tsx +315 -0
  138. package/src/stories/SortableList.stories.tsx +263 -0
  139. package/src/stories/Squircle.stories.tsx +1 -0
  140. package/src/stories/Table.stories.tsx +1 -0
  141. package/src/stories/TagsInput.stories.tsx +2 -0
  142. package/src/stories/Timer.stories.tsx +26 -0
  143. package/src/stories/Tour.stories.tsx +1 -0
  144. package/src/stories/TransferList.stories.tsx +4 -0
  145. package/src/stories/WeekPicker.stories.tsx +21 -0
  146. package/src/stories/YearPicker.stories.tsx +21 -0
  147. package/src/stories/story-groups.json +33 -16
  148. package/src/tokens.json +82 -54
@@ -19,6 +19,7 @@ import { Button } from "./button"
19
19
  import { Checkbox } from "./checkbox"
20
20
  import {
21
21
  Table,
22
+ TableCaption,
22
23
  TableHeader,
23
24
  TableBody,
24
25
  TableRow,
@@ -72,6 +73,17 @@ export interface DataTableProps<TData> extends VariantProps<typeof cellVariants>
72
73
  * definition if needed.
73
74
  */
74
75
  rowSelection?: boolean
76
+ /**
77
+ * Fires with the selected rows' data whenever the selection changes (not on
78
+ * mount), so a "Delete selected" bar can act on them. Needs `rowSelection`.
79
+ */
80
+ onRowSelectionChange?: (rows: TData[]) => void
81
+ /**
82
+ * Stable id for a row. Without it, rows are identified by array index, so
83
+ * after a refetch or re-sort of `data` the selection can land on different
84
+ * records. Pass a primary key when rows have one.
85
+ */
86
+ getRowId?: (row: TData, index: number) => string
75
87
  /**
76
88
  * Callback fired when a data row is clicked. Does NOT constitute a
77
89
  * selection — pair with rowSelection for accessible multi-select. When
@@ -95,6 +107,13 @@ export interface DataTableProps<TData> extends VariantProps<typeof cellVariants>
95
107
  * height when `stickyHeader` is true. Defaults to `"400px"`.
96
108
  */
97
109
  scrollHeight?: string
110
+ /**
111
+ * Accessible label announced by screen readers as the table's region name.
112
+ * Also rendered as a visually hidden `<caption>` so assistive tech can
113
+ * identify the table's purpose (WCAG 1.3.1). Required when more than one
114
+ * table appears on a page; strongly recommended otherwise.
115
+ */
116
+ caption?: string
98
117
  className?: string
99
118
  }
100
119
 
@@ -201,11 +220,14 @@ function DataTable<TData>({
201
220
  sorting: sortingEnabled = true,
202
221
  pagination: paginationOptions,
203
222
  rowSelection: rowSelectionEnabled = false,
223
+ onRowSelectionChange,
224
+ getRowId,
204
225
  onRowClick,
205
226
  emptyMessage = "No results.",
206
227
  stickyHeader = false,
207
228
  scrollHeight = "400px",
208
229
  density = "comfortable",
230
+ caption,
209
231
  className,
210
232
  }: DataTableProps<TData>) {
211
233
  const [sortingState, setSortingState] = React.useState<SortingState>([])
@@ -231,6 +253,7 @@ function DataTable<TData>({
231
253
  },
232
254
  enableSorting: sortingEnabled,
233
255
  enableRowSelection: rowSelectionEnabled,
256
+ getRowId,
234
257
  onSortingChange: setSortingState,
235
258
  onRowSelectionChange: setRowSelectionState,
236
259
  getCoreRowModel: getCoreRowModel(),
@@ -245,6 +268,22 @@ function DataTable<TData>({
245
268
  },
246
269
  })
247
270
 
271
+ // Report the selected rows' data. A ref keeps an inline callback from re-running the effect, and the
272
+ // first run is skipped so mounting does not announce an empty selection.
273
+ const onRowSelectionChangeRef = React.useRef(onRowSelectionChange)
274
+ onRowSelectionChangeRef.current = onRowSelectionChange
275
+ const selectionMounted = React.useRef(false)
276
+ React.useEffect(() => {
277
+ if (!selectionMounted.current) {
278
+ selectionMounted.current = true
279
+ return
280
+ }
281
+ onRowSelectionChangeRef.current?.(
282
+ table.getSelectedRowModel().rows.map((r) => r.original)
283
+ )
284
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- table is stable; the selection state is the trigger
285
+ }, [rowSelectionState])
286
+
248
287
  const cellClass = cellVariants({ density })
249
288
 
250
289
  return (
@@ -252,13 +291,23 @@ function DataTable<TData>({
252
291
  data-slot="data-table"
253
292
  className={cn("rounded-md border bg-card overflow-hidden", className)}
254
293
  >
255
- {/* Scrollable table wrapper */}
256
- <div className="overflow-x-auto">
294
+ {/* Scrollable table wrapper — tabIndex makes the region keyboard-reachable
295
+ (WCAG 2.1.1 + axe scrollable-region-focusable). aria-label surfaces the
296
+ caption text as the region name for screen readers. */}
297
+ <div
298
+ className="overflow-x-auto"
299
+ tabIndex={0}
300
+ role="region"
301
+ aria-label={caption ?? "Data table"}
302
+ >
257
303
  <Table
258
304
  role="grid"
259
305
  wrapperClassName={stickyHeader ? "overflow-y-auto" : undefined}
260
306
  wrapperStyle={stickyHeader ? { maxHeight: scrollHeight } : undefined}
261
307
  >
308
+ {caption ? (
309
+ <TableCaption className="sr-only">{caption}</TableCaption>
310
+ ) : null}
262
311
  <TableHeader className={stickyHeader ? "sticky top-0 z-10 bg-card" : undefined}>
263
312
  {table.getHeaderGroups().map((headerGroup) => (
264
313
  <TableRow key={headerGroup.id}>
@@ -336,7 +385,19 @@ function DataTable<TData>({
336
385
  onRowClick && "cursor-pointer",
337
386
  row.getIsSelected() && "bg-muted"
338
387
  )}
339
- onClick={onRowClick ? () => onRowClick(row.original) : undefined}
388
+ onClick={
389
+ onRowClick
390
+ ? (event) => {
391
+ // A click on a control inside the row (the select checkbox, a link, an action
392
+ // button) belongs to that control, not to the row.
393
+ const hit = (event.target as HTMLElement).closest(
394
+ "a, button, input, label, select, textarea, [role='checkbox'], [role='button']"
395
+ )
396
+ if (hit && event.currentTarget.contains(hit)) return
397
+ onRowClick(row.original)
398
+ }
399
+ : undefined
400
+ }
340
401
  >
341
402
  {row.getVisibleCells().map((cell) => (
342
403
  <TableCell
@@ -65,7 +65,7 @@ function DateField({
65
65
  className,
66
66
  id,
67
67
  }: DateFieldProps) {
68
- const isControlled = value !== undefined
68
+ const isControlled = value !== undefined || onValueChange !== undefined
69
69
  const [internalValue, setInternalValue] = React.useState<Date | undefined>(
70
70
  isValidDate(defaultValue) ? atMidnight(defaultValue) : undefined
71
71
  )
@@ -151,6 +151,7 @@ function Editable({
151
151
  }
152
152
  if (
153
153
  e.key === "Enter" &&
154
+ !e.nativeEvent.isComposing &&
154
155
  (submitMode === "enter" || submitMode === "both")
155
156
  ) {
156
157
  e.preventDefault()
@@ -0,0 +1,187 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import { PlusCircleIcon, XCircleIcon } from "lucide-react"
5
+
6
+ import { cn } from "../../lib/utils"
7
+ import { Badge } from "./badge"
8
+ import { Button } from "./button"
9
+ import { Checkbox } from "./checkbox"
10
+ import { Popover, PopoverContent, PopoverTrigger } from "./popover"
11
+ import { Separator } from "./separator"
12
+ import {
13
+ Command,
14
+ CommandEmpty,
15
+ CommandGroup,
16
+ CommandInput,
17
+ CommandItem,
18
+ CommandList,
19
+ CommandSeparator,
20
+ } from "./command"
21
+
22
+ export interface FacetedFilterOption {
23
+ label: string
24
+ value: string
25
+ icon?: React.ComponentType<{ className?: string }>
26
+ count?: number
27
+ }
28
+
29
+ export interface FacetedFilterProps {
30
+ title: string
31
+ options: FacetedFilterOption[]
32
+ selectedValues?: Set<string>
33
+ onSelectionChange?: (values: Set<string>) => void
34
+ className?: string
35
+ }
36
+
37
+ export function FacetedFilter({
38
+ title,
39
+ options,
40
+ selectedValues = new Set(),
41
+ onSelectionChange,
42
+ className,
43
+ }: FacetedFilterProps) {
44
+ const selectedCount = selectedValues.size
45
+
46
+ function toggleValue(value: string) {
47
+ const next = new Set(selectedValues)
48
+ if (next.has(value)) {
49
+ next.delete(value)
50
+ } else {
51
+ next.add(value)
52
+ }
53
+ onSelectionChange?.(next)
54
+ }
55
+
56
+ function clearSelection() {
57
+ onSelectionChange?.(new Set())
58
+ }
59
+
60
+ return (
61
+ <Popover>
62
+ <PopoverTrigger asChild>
63
+ <Button
64
+ variant="outline"
65
+ size="sm"
66
+ aria-label={
67
+ selectedCount > 0
68
+ ? `${title}: ${selectedCount} selected`
69
+ : `Filter by ${title}`
70
+ }
71
+ className={cn("h-8 gap-1.5 border-dashed", className)}
72
+ >
73
+ <PlusCircleIcon strokeWidth={1.5} className="size-4 shrink-0" />
74
+ <span>{title}</span>
75
+ {selectedCount > 0 && (
76
+ <>
77
+ <Separator orientation="vertical" className="h-4" />
78
+ {selectedCount > 2 ? (
79
+ <Badge
80
+ variant="secondary"
81
+ size="sm"
82
+ className="rounded-sm px-1 font-normal"
83
+ >
84
+ {selectedCount} selected
85
+ </Badge>
86
+ ) : (
87
+ <div className="flex gap-1">
88
+ {Array.from(selectedValues).map((val) => (
89
+ <Badge
90
+ key={val}
91
+ variant="secondary"
92
+ size="sm"
93
+ className="rounded-sm px-1 font-normal"
94
+ >
95
+ {options.find((o) => o.value === val)?.label ?? val}
96
+ </Badge>
97
+ ))}
98
+ </div>
99
+ )}
100
+ </>
101
+ )}
102
+ </Button>
103
+ </PopoverTrigger>
104
+ <PopoverContent
105
+ className="w-[220px] p-0"
106
+ align="start"
107
+ sideOffset={6}
108
+ >
109
+ <Command aria-label={`${title} filter options`}>
110
+ <CommandInput placeholder={`Search ${title.toLowerCase()}…`} />
111
+ <CommandList>
112
+ <CommandEmpty>No results.</CommandEmpty>
113
+ <CommandGroup>
114
+ {options.map((option) => {
115
+ const isSelected = selectedValues.has(option.value)
116
+ const Icon = option.icon
117
+ return (
118
+ <CommandItem
119
+ key={option.value}
120
+ value={option.value}
121
+ onSelect={() => toggleValue(option.value)}
122
+ className="gap-2"
123
+ style={{
124
+ transitionProperty: "color, background-color",
125
+ transitionDuration: "var(--duration-fast)",
126
+ transitionTimingFunction: "var(--ease-out)",
127
+ }}
128
+ >
129
+ {/* Decorative, not the real control: CommandItem's onSelect above is
130
+ what toggles selection and is what gets the roving cmdk focus. A
131
+ second focusable/interactive checkbox nested in the same row would
132
+ double the controls a screen reader announces for one choice. This
133
+ still has to be the real Checkbox primitive, not a hand-rolled
134
+ lookalike (see CLAUDE.md -> "Primitive visual parity") — tabIndex,
135
+ pointer-events, and aria-hidden are what make an otherwise-real,
136
+ otherwise-interactive component safe to use purely as a visual. */}
137
+ <Checkbox
138
+ size="sm"
139
+ checked={isSelected}
140
+ tabIndex={-1}
141
+ aria-hidden
142
+ className={cn(
143
+ "pointer-events-none",
144
+ !isSelected && "opacity-50 [.group_&]:opacity-100"
145
+ )}
146
+ />
147
+ {Icon && (
148
+ <Icon className="size-4 shrink-0 text-muted-foreground" />
149
+ )}
150
+ <span className="flex-1 truncate">{option.label}</span>
151
+ {option.count !== undefined && (
152
+ <span
153
+ className="ml-auto font-mono text-xs tabular-nums text-muted-foreground"
154
+ aria-label={`${option.count} items`}
155
+ >
156
+ {option.count}
157
+ </span>
158
+ )}
159
+ </CommandItem>
160
+ )
161
+ })}
162
+ </CommandGroup>
163
+ {selectedCount > 0 && (
164
+ <>
165
+ <CommandSeparator />
166
+ <CommandGroup>
167
+ <CommandItem
168
+ onSelect={clearSelection}
169
+ className="justify-center gap-1.5 text-muted-foreground"
170
+ style={{
171
+ transitionProperty: "color, background-color",
172
+ transitionDuration: "var(--duration-fast)",
173
+ transitionTimingFunction: "var(--ease-out)",
174
+ }}
175
+ >
176
+ <XCircleIcon strokeWidth={1.5} className="size-4" />
177
+ Clear filters
178
+ </CommandItem>
179
+ </CommandGroup>
180
+ </>
181
+ )}
182
+ </CommandList>
183
+ </Command>
184
+ </PopoverContent>
185
+ </Popover>
186
+ )
187
+ }
@@ -0,0 +1,252 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import { ResponsiveContainer, PieChart, Pie } from "recharts"
5
+
6
+ import { cn } from "../../lib/utils"
7
+ import { prefersReducedMotion } from "../../hooks/use-reduced-motion"
8
+
9
+ // Arc geometry. Recharts measures angles counter-clockwise from 3 o'clock, so
10
+ // starting at 225° (lower-left) and sweeping down to -45° (lower-right) draws
11
+ // a 270° dial with a 90° opening at the bottom — the classic speedometer
12
+ // shape. Both the background track and the value fill share the same start
13
+ // angle so they stay concentric and aligned.
14
+ const START_ANGLE = 225
15
+ const SWEEP = 270
16
+ const END_ANGLE = START_ANGLE - SWEEP
17
+
18
+ // A 270° arc leaves the bottom quarter of the bounding circle empty. Nudging
19
+ // the center down and sizing the radius to fit keeps the visible dial
20
+ // optically centered in its box instead of floating high.
21
+ const CENTER_Y = "55%"
22
+ const OUTER_RADIUS = "90%"
23
+ const INNER_RADIUS = "72%"
24
+
25
+ // Pixel heights per size. The chart is a square dial, so height is the
26
+ // controlling dimension; width follows the container.
27
+ const SIZE_PX = {
28
+ sm: 120,
29
+ md: 160,
30
+ lg: 200,
31
+ xl: 240,
32
+ } as const
33
+
34
+ // Center value type size per dial size. Chosen so the number sits inside the
35
+ // inner hole with breathing room: text-lg (25px) in a ~75px hole, up to
36
+ // text-3xl (49px) in a ~150px hole. text-3xl is the top of BADS' body tier;
37
+ // the marketing tier (text-4xl = 36px) is smaller and never belongs here.
38
+ const VALUE_TEXT_CLASS = {
39
+ sm: "text-lg",
40
+ md: "text-xl",
41
+ lg: "text-2xl",
42
+ xl: "text-3xl",
43
+ } as const
44
+
45
+ // Single-datum series: a Pie with one entry draws one sector spanning its
46
+ // full startAngle→endAngle range. Both layers reuse this, so the track is the
47
+ // full sweep and the value layer just shortens its endAngle.
48
+ const ARC_DATA = [{ value: 1 }]
49
+
50
+ export type GaugeChartSize = keyof typeof SIZE_PX
51
+
52
+ export interface GaugeChartProps
53
+ extends Omit<React.ComponentProps<"div">, "children"> {
54
+ /** The reading to display. Clamped to the `[min, max]` range for the arc. */
55
+ value: number
56
+ /** Lower bound of the range. Defaults to 0. */
57
+ min?: number
58
+ /** Upper bound of the range. Defaults to 100. */
59
+ max?: number
60
+ /**
61
+ * Short caption rendered under the value in the center of the dial
62
+ * ("CPU usage", "Story coverage"). Also becomes the default accessible
63
+ * name when no `aria-label` is supplied.
64
+ */
65
+ label?: string
66
+ /**
67
+ * Dial size. Controls pixel height (sm 120, md 160, lg 200, xl 240) and the
68
+ * center value's type size. Defaults to `"md"`.
69
+ */
70
+ size?: GaugeChartSize
71
+ /**
72
+ * Fill color for the value arc. Accepts any CSS color or `var()` reference.
73
+ * Defaults to `var(--chart-1)` — pass `var(--chart-2)`…`var(--chart-5)` to
74
+ * distinguish several gauges in the same view. The background track always
75
+ * uses `var(--muted)` so the data is the only saturated mark on the canvas.
76
+ */
77
+ color?: string
78
+ /**
79
+ * Formats the center value and the announced `aria-valuetext`. Defaults to
80
+ * an integer via `Intl.NumberFormat` so a fork's locale is respected.
81
+ */
82
+ formatValue?: (value: number) => string
83
+ }
84
+
85
+ const defaultFormatValue = (value: number) =>
86
+ new Intl.NumberFormat(undefined, { maximumFractionDigits: 0 }).format(value)
87
+
88
+ /**
89
+ * Radial arc dial for a single reading within a known range — CPU load,
90
+ * storage used, a health score, a completion percentage. A quiet
91
+ * `--muted` track sweeps 270°; the value arc in a `--chart-*` color fills the
92
+ * proportion of that sweep the reading represents, and the formatted value
93
+ * (plus an optional label) sits in the center hole.
94
+ *
95
+ * Semantically this is a `role="meter"` (ARIA 1.2): a determinate measurement
96
+ * of where a value sits between min and max, the same contract the linear
97
+ * `Meter` primitive uses. `aria-valuenow` / `aria-valuemin` / `aria-valuemax`
98
+ * are only valid on range roles, so the wrapper is not `role="img"` — an
99
+ * `img` carrying value attributes fails axe's `aria-allowed-attr`.
100
+ *
101
+ * Built on Recharts 3.x (already a BADS peer dependency) with the same
102
+ * ResizeObserver mount-gate as `ChartContainer` and `Sparkline`, so the chart
103
+ * never mounts at -1×-1 during SSR and paints invisible.
104
+ */
105
+ function GaugeChart({
106
+ value,
107
+ min = 0,
108
+ max = 100,
109
+ label,
110
+ size = "md",
111
+ color = "var(--chart-1)",
112
+ formatValue = defaultFormatValue,
113
+ className,
114
+ style,
115
+ "aria-label": ariaLabel,
116
+ ...props
117
+ }: GaugeChartProps) {
118
+ // ResizeObserver gate — same pattern as ChartContainer and Sparkline.
119
+ const containerRef = React.useRef<HTMLDivElement | null>(null)
120
+ const [hasSize, setHasSize] = React.useState(false)
121
+
122
+ // Read reduced-motion synchronously at mount rather than via the reactive
123
+ // `useReducedMotion()` hook. That hook intentionally starts `false` on
124
+ // every render (SSR-safe) and corrects itself a tick later via its own
125
+ // effect — fine for components whose SSR output doesn't depend on it, but
126
+ // this chart's entire Pie subtree is already gated behind `hasSize` (which
127
+ // is `false` during SSR and the first client paint), so there is no
128
+ // server/client mismatch risk in reading the real preference immediately.
129
+ // Without this, `isAnimationActive` starts `true`, react-smooth begins
130
+ // tweening the value arc from a zero-width sector, and when the hook's
131
+ // effect flips it to `false` a tick later — mid-tween — Recharts freezes
132
+ // on whatever near-zero angle it had already interpolated to instead of
133
+ // jumping to the final one, so the arc never recovers to its correct
134
+ // angle. Reading the preference up front means `isAnimationActive` is
135
+ // right from the component's very first animation frame, so this race
136
+ // never opens. (Confirmed via repeated headless capture — see PR.)
137
+ const [animate] = React.useState(() => !prefersReducedMotion())
138
+
139
+ React.useEffect(() => {
140
+ const el = containerRef.current
141
+ if (!el) return
142
+ const observer = new ResizeObserver((entries) => {
143
+ for (const entry of entries) {
144
+ const { width, height } = entry.contentRect
145
+ setHasSize(width > 0 && height > 0)
146
+ }
147
+ })
148
+ observer.observe(el)
149
+ return () => observer.disconnect()
150
+ }, [])
151
+
152
+ // Guard a degenerate range (min === max) so the division below can't
153
+ // produce NaN, then clamp so an out-of-range reading pins to an end of the
154
+ // dial instead of wrapping around it.
155
+ const range = max - min
156
+ const fraction =
157
+ range > 0 ? Math.min(1, Math.max(0, (value - min) / range)) : 0
158
+ const valueEndAngle = START_ANGLE - fraction * SWEEP
159
+
160
+ const height = SIZE_PX[size]
161
+ const formatted = formatValue(value)
162
+ const valueText = `${formatted} out of ${formatValue(max)}`
163
+
164
+ return (
165
+ <div
166
+ ref={containerRef}
167
+ data-slot="gauge-chart"
168
+ data-size={size}
169
+ role="meter"
170
+ aria-label={ariaLabel ?? label ?? "Gauge"}
171
+ aria-valuenow={value}
172
+ aria-valuemin={min}
173
+ aria-valuemax={max}
174
+ aria-valuetext={valueText}
175
+ className={cn("relative block w-full", className)}
176
+ style={{ height, ...style }}
177
+ {...props}
178
+ >
179
+ {hasSize ? (
180
+ <ResponsiveContainer width="100%" height="100%">
181
+ <PieChart margin={{ top: 0, right: 0, bottom: 0, left: 0 }}>
182
+ {/* Background track — the quiet chrome. Static, never animated. */}
183
+ <Pie
184
+ data={ARC_DATA}
185
+ dataKey="value"
186
+ cx="50%"
187
+ cy={CENTER_Y}
188
+ innerRadius={INNER_RADIUS}
189
+ outerRadius={OUTER_RADIUS}
190
+ startAngle={START_ANGLE}
191
+ endAngle={END_ANGLE}
192
+ cornerRadius="50%"
193
+ fill="var(--muted)"
194
+ stroke="none"
195
+ isAnimationActive={false}
196
+ />
197
+ {/* Value arc — the only saturated mark on the canvas. Skipped at
198
+ zero so Recharts never draws a zero-angle sector. */}
199
+ {fraction > 0 ? (
200
+ <Pie
201
+ data={ARC_DATA}
202
+ dataKey="value"
203
+ cx="50%"
204
+ cy={CENTER_Y}
205
+ innerRadius={INNER_RADIUS}
206
+ outerRadius={OUTER_RADIUS}
207
+ startAngle={START_ANGLE}
208
+ endAngle={valueEndAngle}
209
+ cornerRadius="50%"
210
+ fill={color}
211
+ stroke="none"
212
+ isAnimationActive={animate}
213
+ animationDuration={700}
214
+ animationEasing="ease-out"
215
+ />
216
+ ) : null}
217
+ </PieChart>
218
+ </ResponsiveContainer>
219
+ ) : null}
220
+
221
+ {/* Center readout. Absolutely positioned over the dial's center (which
222
+ sits at CENTER_Y, not 50%). aria-hidden because the wrapper already
223
+ announces the value via aria-valuetext — otherwise AT reads it twice.
224
+ min-w-0 + truncate on the label is the long-label overflow contract:
225
+ a localized caption can be 2× longer than the English one. */}
226
+ <div
227
+ aria-hidden="true"
228
+ className="pointer-events-none absolute left-1/2 flex w-[60%] min-w-0 -translate-x-1/2 -translate-y-1/2 flex-col items-center text-center"
229
+ style={{ top: CENTER_Y }}
230
+ >
231
+ <span
232
+ className={cn(
233
+ "font-semibold leading-none tabular-nums text-foreground",
234
+ VALUE_TEXT_CLASS[size]
235
+ )}
236
+ >
237
+ {formatted}
238
+ </span>
239
+ {label ? (
240
+ <span
241
+ className="mt-1 w-full truncate text-xs text-muted-foreground"
242
+ title={label}
243
+ >
244
+ {label}
245
+ </span>
246
+ ) : null}
247
+ </div>
248
+ </div>
249
+ )
250
+ }
251
+
252
+ export { GaugeChart }