@behavioral-agentic-design-system/core 0.39.1 → 0.42.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 (115) hide show
  1. package/README.md +2 -0
  2. package/package.json +26 -5
  3. package/scripts/a11y-lint.cjs +88 -8
  4. package/scripts/bads-components.mjs +118 -0
  5. package/scripts/build-tokens.cjs +133 -12
  6. package/scripts/check-stories.mjs +1 -1
  7. package/scripts/health-report.mjs +16 -2
  8. package/scripts/lint-component-source.mjs +100 -0
  9. package/scripts/lint-microanimation.mjs +267 -0
  10. package/scripts/lint-slop.mjs +25 -1
  11. package/scripts/size-audit.cjs +79 -0
  12. package/scripts/source-of-truth.cjs +58 -0
  13. package/scripts/ux-smoke.mjs +438 -0
  14. package/scripts/wcag-audit.cjs +121 -6
  15. package/src/api/layers/file.ts +1 -0
  16. package/src/app/opengraph-image.tsx +5 -0
  17. package/src/app/preview/components/page.tsx +2237 -2
  18. package/src/app/shell.tsx +17 -16
  19. package/src/components/Foundations/Motion.stories.tsx +1 -0
  20. package/src/components/customize/brand-mark-section.tsx +4 -2
  21. package/src/components/customize/design-controls.tsx +17 -2
  22. package/src/components/customize/discipline-section.tsx +3 -6
  23. package/src/components/customize/font-pickers.tsx +1 -1
  24. package/src/components/customize/letter-spacing.tsx +1 -1
  25. package/src/components/customize/save-bar.tsx +2 -2
  26. package/src/components/customize/theme-io.tsx +7 -7
  27. package/src/components/customize/type-scale.tsx +1 -1
  28. package/src/components/customize-tab.tsx +7 -4
  29. package/src/components/home-tab.tsx +3 -0
  30. package/src/components/studio/studio.tsx +153 -0
  31. package/src/components/ui/accordion.tsx +7 -0
  32. package/src/components/ui/alert.tsx +1 -0
  33. package/src/components/ui/anchor.tsx +37 -3
  34. package/src/components/ui/announcement-bar.tsx +256 -0
  35. package/src/components/ui/attachment.tsx +211 -0
  36. package/src/components/ui/badge.tsx +1 -0
  37. package/src/components/ui/callout.tsx +218 -0
  38. package/src/components/ui/chart.tsx +5 -14
  39. package/src/components/ui/code.tsx +1 -1
  40. package/src/components/ui/color-picker.tsx +2 -2
  41. package/src/components/ui/format-relative-time.tsx +139 -0
  42. package/src/components/ui/gauge-chart.tsx +238 -0
  43. package/src/components/ui/grid.tsx +255 -0
  44. package/src/components/ui/heatmap.tsx +256 -0
  45. package/src/components/ui/icon.tsx +108 -0
  46. package/src/components/ui/index.ts +17 -0
  47. package/src/components/ui/infinite-scroll.tsx +103 -0
  48. package/src/components/ui/json-input.tsx +351 -0
  49. package/src/components/ui/navigation-progress.tsx +281 -0
  50. package/src/components/ui/number-input.tsx +1 -4
  51. package/src/components/ui/page-header.tsx +63 -0
  52. package/src/components/ui/password-input.tsx +2 -1
  53. package/src/components/ui/password-strength-input.tsx +288 -0
  54. package/src/components/ui/pill.tsx +140 -0
  55. package/src/components/ui/popover.tsx +27 -4
  56. package/src/components/ui/portal.tsx +111 -0
  57. package/src/components/ui/presence.tsx +172 -0
  58. package/src/components/ui/progress-stack.tsx +258 -0
  59. package/src/components/ui/scroll-progress.tsx +100 -0
  60. package/src/components/ui/select.tsx +89 -4
  61. package/src/components/ui/separator.tsx +1 -0
  62. package/src/components/ui/slider.tsx +83 -3
  63. package/src/components/ui/snackbar.tsx +393 -0
  64. package/src/components/ui/sortable-list.tsx +342 -0
  65. package/src/components/ui/sparkline.tsx +2 -14
  66. package/src/components/ui/squircle.tsx +1 -1
  67. package/src/components/ui/table.tsx +1 -1
  68. package/src/components/ui/textarea.tsx +28 -1
  69. package/src/components/ui/tour.tsx +1 -3
  70. package/src/data/docs-index.ts +25 -0
  71. package/src/hooks/use-reduced-motion.ts +6 -0
  72. package/src/lib/clamp.ts +2 -0
  73. package/src/stories/Accordion.stories.tsx +59 -0
  74. package/src/stories/Alert.stories.tsx +3 -1
  75. package/src/stories/Anchor.stories.tsx +54 -0
  76. package/src/stories/AnnouncementBar.stories.tsx +261 -0
  77. package/src/stories/Attachment.stories.tsx +189 -0
  78. package/src/stories/Badge.stories.tsx +3 -0
  79. package/src/stories/Calendar.stories.tsx +1 -1
  80. package/src/stories/Callout.stories.tsx +219 -0
  81. package/src/stories/Chart.stories.tsx +8 -0
  82. package/src/stories/Code.stories.tsx +1 -0
  83. package/src/stories/ColorPicker.stories.tsx +24 -0
  84. package/src/stories/FormatRelativeTime.stories.tsx +116 -0
  85. package/src/stories/GaugeChart.stories.tsx +163 -0
  86. package/src/stories/Grid.stories.tsx +197 -0
  87. package/src/stories/Heatmap.stories.tsx +172 -0
  88. package/src/stories/Icon.stories.tsx +175 -0
  89. package/src/stories/InfiniteScroll.stories.tsx +225 -0
  90. package/src/stories/JsonInput.stories.tsx +212 -0
  91. package/src/stories/MultiSelect.stories.tsx +1 -1
  92. package/src/stories/NavigationProgress.stories.tsx +159 -0
  93. package/src/stories/NumberInput.stories.tsx +1 -0
  94. package/src/stories/PageHeader.stories.tsx +102 -0
  95. package/src/stories/PasswordInput.stories.tsx +4 -0
  96. package/src/stories/PasswordStrengthInput.stories.tsx +211 -0
  97. package/src/stories/Pill.stories.tsx +201 -0
  98. package/src/stories/Popover.stories.tsx +29 -1
  99. package/src/stories/Portal.stories.tsx +191 -0
  100. package/src/stories/Presence.stories.tsx +228 -0
  101. package/src/stories/ProgressStack.stories.tsx +287 -0
  102. package/src/stories/ScrollProgress.stories.tsx +117 -0
  103. package/src/stories/Select.stories.tsx +25 -0
  104. package/src/stories/Separator.stories.tsx +3 -0
  105. package/src/stories/Slider.stories.tsx +54 -5
  106. package/src/stories/Snackbar.stories.tsx +315 -0
  107. package/src/stories/SortableList.stories.tsx +263 -0
  108. package/src/stories/Sparkline.stories.tsx +3 -0
  109. package/src/stories/Squircle.stories.tsx +1 -0
  110. package/src/stories/Table.stories.tsx +1 -0
  111. package/src/stories/Textarea.stories.tsx +18 -0
  112. package/src/stories/Tour.stories.tsx +1 -0
  113. package/src/stories/story-groups.json +26 -6
  114. package/src/styles.css +133 -12
  115. package/LICENSE +0 -21
@@ -0,0 +1,281 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+
5
+ import { cn } from "../../lib/utils"
6
+
7
+ // NavigationProgress — the thin bar at the top of the viewport that fills
8
+ // while a route change or a long request is in flight. The YouTube / GitHub /
9
+ // Next.js "nprogress" pattern.
10
+ //
11
+ // Peer parity: Mantine `@mantine/nprogress` (NavigationProgress component +
12
+ // imperative `nprogress.start/set/increment/decrement/stop/complete/reset`
13
+ // store). Demand signal: the 21st.dev "react loading bar" cluster.
14
+ //
15
+ // How this differs from the other progress primitives
16
+ // ---------------------------------------------------
17
+ // - Progress → an in-flow determinate bar owned by its parent.
18
+ // - ScrollProgress → tracks how far the page is scrolled.
19
+ // - LoadingOverlay → blocks a region while it loads.
20
+ // - NavigationProgress → fixed to the top edge, app-global, driven from
21
+ // OUTSIDE React by whatever knows a navigation started (a router hook,
22
+ // a fetch wrapper), with the trickle-then-complete lifecycle built in.
23
+ //
24
+ // The store is module-level on purpose: a route hook has no component to
25
+ // reach into, so `navigationProgress.start()` must be callable from anywhere.
26
+ // Mount the component ONCE per document (the preview tabs are iframes, each
27
+ // its own document, so one per tab is correct there).
28
+ //
29
+ // Accessibility
30
+ // -------------
31
+ // - `role="progressbar"` with aria-valuenow while active; `aria-hidden`
32
+ // while inactive so an idle 0% bar is never announced.
33
+ // - Non-modal, `pointer-events-none`, never focused.
34
+ // - Nothing is announced on start/complete (Mantine parity) — the page's own
35
+ // content change is the announcement; a second live region would double up.
36
+ //
37
+ // Motion is pattern (c): the root transitions opacity (show/fade) and the bar
38
+ // transitions width, both on var(--duration-base) / var(--ease-out). The
39
+ // settle-then-fade timers read --duration-base from :root at call time, so
40
+ // the JS lifecycle follows the same token as the CSS and a fork retuning
41
+ // motion retunes both. Reduced motion collapses the CSS transitions via the
42
+ // base layer; the bar still reports its value.
43
+
44
+ interface NavigationProgressState {
45
+ /** 0–100. */
46
+ progress: number
47
+ /** Visible and (unless stopped) trickling. */
48
+ active: boolean
49
+ }
50
+
51
+ const SERVER_SNAPSHOT: NavigationProgressState = { progress: 0, active: false }
52
+
53
+ let state: NavigationProgressState = SERVER_SNAPSHOT
54
+ const listeners = new Set<() => void>()
55
+ let trickleTimer: ReturnType<typeof setInterval> | null = null
56
+ let settleTimer: ReturnType<typeof setTimeout> | null = null
57
+ let resetTimer: ReturnType<typeof setTimeout> | null = null
58
+
59
+ // Configured by the mounted component's props; defaults match the component.
60
+ const settings = { initialProgress: 8, stepInterval: 500 }
61
+
62
+ function emit(next: Partial<NavigationProgressState>) {
63
+ state = { ...state, ...next }
64
+ for (const listener of listeners) listener()
65
+ }
66
+
67
+ function subscribe(listener: () => void) {
68
+ listeners.add(listener)
69
+ return () => {
70
+ listeners.delete(listener)
71
+ }
72
+ }
73
+
74
+ function getSnapshot() {
75
+ return state
76
+ }
77
+
78
+ function getServerSnapshot() {
79
+ return SERVER_SNAPSHOT
80
+ }
81
+
82
+ function clamp(value: number) {
83
+ return Math.min(100, Math.max(0, value))
84
+ }
85
+
86
+ function clearTrickle() {
87
+ if (trickleTimer) clearInterval(trickleTimer)
88
+ trickleTimer = null
89
+ }
90
+
91
+ function clearSettle() {
92
+ if (settleTimer) clearTimeout(settleTimer)
93
+ if (resetTimer) clearTimeout(resetTimer)
94
+ settleTimer = null
95
+ resetTimer = null
96
+ }
97
+
98
+ // Deterministic trickle (Mantine randomizes; a fixed ladder keeps snapshots
99
+ // stable). Slows as it approaches the 90% ceiling, never reaches it.
100
+ function trickleStep(progress: number) {
101
+ if (progress < 20) return progress + 10
102
+ if (progress < 50) return progress + 5
103
+ if (progress < 80) return progress + 2
104
+ if (progress < 90) return progress + 0.5
105
+ return progress
106
+ }
107
+
108
+ /**
109
+ * Reads a `--duration-*` token from `:root` as milliseconds so the JS
110
+ * lifecycle follows the same token as the CSS transitions. Falls back when
111
+ * there is no document (SSR) or the token is missing.
112
+ */
113
+ function readDurationMs(token: string, fallback: number) {
114
+ if (typeof document === "undefined") return fallback
115
+ const raw = getComputedStyle(document.documentElement)
116
+ .getPropertyValue(token)
117
+ .trim()
118
+ if (!raw) return fallback
119
+ const value = Number.parseFloat(raw)
120
+ if (Number.isNaN(value)) return fallback
121
+ return raw.endsWith("ms") ? value : value * 1000
122
+ }
123
+
124
+ /**
125
+ * Imperative store. Router-agnostic — call it from a route-change hook, a
126
+ * fetch wrapper, a form submit, anywhere. Safe to call before the component
127
+ * mounts (the state is picked up on mount) and on the server (no-ops).
128
+ */
129
+ const navigationProgress = {
130
+ /** Show the bar and trickle toward 90%. Restarts the trickle if already active. */
131
+ start() {
132
+ clearTrickle()
133
+ clearSettle()
134
+ emit({
135
+ active: true,
136
+ progress: Math.max(state.progress, clamp(settings.initialProgress)),
137
+ })
138
+ trickleTimer = setInterval(() => {
139
+ emit({ progress: trickleStep(state.progress) })
140
+ }, settings.stepInterval)
141
+ },
142
+ /** Jump to a value (0–100) without changing visibility. */
143
+ set(value: number) {
144
+ emit({ progress: clamp(value) })
145
+ },
146
+ increment(by = 5) {
147
+ emit({ progress: clamp(state.progress + by) })
148
+ },
149
+ decrement(by = 5) {
150
+ emit({ progress: clamp(state.progress - by) })
151
+ },
152
+ /** Pause the trickle; the bar stays where it is. `start()` resumes. */
153
+ stop() {
154
+ clearTrickle()
155
+ },
156
+ /**
157
+ * Fill to 100%, let the width transition settle for one --duration-base,
158
+ * fade out over another, then reset to 0 while invisible.
159
+ */
160
+ complete() {
161
+ clearTrickle()
162
+ clearSettle()
163
+ emit({ active: true, progress: 100 })
164
+ const duration = readDurationMs("--duration-base", 200)
165
+ settleTimer = setTimeout(() => {
166
+ emit({ active: false })
167
+ resetTimer = setTimeout(() => {
168
+ emit({ progress: 0 })
169
+ }, duration)
170
+ }, duration)
171
+ },
172
+ /** Hide immediately and clear every timer. */
173
+ reset() {
174
+ clearTrickle()
175
+ clearSettle()
176
+ emit({ active: false, progress: 0 })
177
+ },
178
+ }
179
+
180
+ /**
181
+ * Subscribes to the store. Use it in a component that renders the state
182
+ * (a "Loading…" label, a disabled nav) — for firing the lifecycle from
183
+ * non-React code, call `navigationProgress.*` directly.
184
+ */
185
+ function useNavigationProgress() {
186
+ const snapshot = React.useSyncExternalStore(
187
+ subscribe,
188
+ getSnapshot,
189
+ getServerSnapshot
190
+ )
191
+ return { ...snapshot, ...navigationProgress }
192
+ }
193
+
194
+ const sizeClass = {
195
+ sm: "h-0.5",
196
+ md: "h-1",
197
+ lg: "h-1.5",
198
+ } as const
199
+
200
+ export interface NavigationProgressProps
201
+ extends Omit<React.ComponentProps<"div">, "children"> {
202
+ /** Bar thickness: sm 2px, md 4px (default), lg 6px. */
203
+ size?: keyof typeof sizeClass
204
+ /** Bar color — any CSS color. Defaults to the brand `var(--primary)`. */
205
+ color?: string
206
+ /**
207
+ * Where `start()` lands (0–100). Default 8 — a bar that starts at 0 is
208
+ * invisible for the first trickle step.
209
+ */
210
+ initialProgress?: number
211
+ /** Milliseconds between trickle steps. Default 500. */
212
+ stepInterval?: number
213
+ /** Accessible name. Default "Page loading". */
214
+ label?: string
215
+ }
216
+
217
+ /**
218
+ * The bar. Mount once per document, near the root. Reads the module store;
219
+ * drive it with `navigationProgress.start()` / `.complete()` or the
220
+ * `useNavigationProgress()` hook.
221
+ */
222
+ function NavigationProgress({
223
+ size = "md",
224
+ color = "var(--primary)",
225
+ initialProgress = 8,
226
+ stepInterval = 500,
227
+ label = "Page loading",
228
+ className,
229
+ style,
230
+ ...props
231
+ }: NavigationProgressProps) {
232
+ const { progress, active } = useNavigationProgress()
233
+
234
+ // Props configure the store; the store drives every call site.
235
+ React.useEffect(() => {
236
+ settings.initialProgress = initialProgress
237
+ settings.stepInterval = stepInterval
238
+ }, [initialProgress, stepInterval])
239
+
240
+ // Leave nothing running if the only bar unmounts mid-navigation.
241
+ React.useEffect(() => () => navigationProgress.reset(), [])
242
+
243
+ const motion: React.CSSProperties = {
244
+ transitionDuration: "var(--duration-base)",
245
+ transitionTimingFunction: "var(--ease-out)",
246
+ }
247
+
248
+ return (
249
+ <div
250
+ data-slot="navigation-progress"
251
+ data-state={active ? "active" : "inactive"}
252
+ data-size={size}
253
+ role="progressbar"
254
+ aria-label={label}
255
+ aria-valuemin={0}
256
+ aria-valuemax={100}
257
+ aria-valuenow={Math.round(progress)}
258
+ aria-hidden={active ? undefined : true}
259
+ className={cn(
260
+ "pointer-events-none fixed inset-x-0 top-0 z-50 opacity-0 transition-opacity",
261
+ "data-[state=active]:opacity-100",
262
+ sizeClass[size],
263
+ className
264
+ )}
265
+ style={{ ...motion, ...style }}
266
+ {...props}
267
+ >
268
+ <div
269
+ data-slot="navigation-progress-bar"
270
+ className="h-full rounded-r-full transition-[width]"
271
+ style={{
272
+ ...motion,
273
+ width: `${progress}%`,
274
+ backgroundColor: color,
275
+ }}
276
+ />
277
+ </div>
278
+ )
279
+ }
280
+
281
+ export { NavigationProgress, navigationProgress, useNavigationProgress }
@@ -5,6 +5,7 @@ import { cva, type VariantProps } from "class-variance-authority";
5
5
  import { Minus, Plus } from "lucide-react";
6
6
 
7
7
  import { cn } from "../../lib/utils";
8
+ import { clamp } from "../../lib/clamp";
8
9
 
9
10
  // ─── Variants ─────────────────────────────────────────────────────────────────
10
11
 
@@ -51,10 +52,6 @@ export interface NumberInputProps
51
52
 
52
53
  // ─── Helpers ──────────────────────────────────────────────────────────────────
53
54
 
54
- function clamp(value: number, min: number, max: number) {
55
- return Math.min(Math.max(value, min), max);
56
- }
57
-
58
55
  // ─── NumberInput ──────────────────────────────────────────────────────────────
59
56
 
60
57
  function NumberInput({
@@ -0,0 +1,63 @@
1
+ import * as React from "react"
2
+ import { cn } from "../../lib/utils"
3
+
4
+ export interface PageHeaderProps {
5
+ /** Primary heading. Rendered as <h1> by default; use `asChild` on the heading slot if you need a different level. */
6
+ title: React.ReactNode
7
+ /** Supporting description rendered below the title at text-sm / muted-foreground. */
8
+ description?: React.ReactNode
9
+ /** Uppercase eyebrow kicker above the title — used for section category or breadcrumb-equivalent labels. */
10
+ eyebrow?: string
11
+ /** Right-aligned action slot: a Button, ButtonGroup, or any control. */
12
+ action?: React.ReactNode
13
+ /** Adds a bottom border that separates the header from its content region. */
14
+ bordered?: boolean
15
+ /** Pins the header to the top of its scroll container. */
16
+ sticky?: boolean
17
+ className?: string
18
+ }
19
+
20
+ function PageHeader({
21
+ title,
22
+ description,
23
+ eyebrow,
24
+ action,
25
+ bordered = false,
26
+ sticky = false,
27
+ className,
28
+ }: PageHeaderProps) {
29
+ return (
30
+ <div
31
+ data-slot="page-header"
32
+ className={cn(
33
+ "flex items-start justify-between gap-4",
34
+ bordered && "border-b border-border pb-6",
35
+ sticky && "sticky top-0 z-10 bg-background py-4",
36
+ className
37
+ )}
38
+ >
39
+ <div className="min-w-0 flex-1 space-y-1">
40
+ {eyebrow && (
41
+ <p className="text-xs font-medium uppercase tracking-widest text-muted-foreground">
42
+ {eyebrow}
43
+ </p>
44
+ )}
45
+ <h1 className="text-2xl font-semibold leading-tight tracking-tight text-foreground truncate">
46
+ {title}
47
+ </h1>
48
+ {description && (
49
+ <p className="text-sm text-muted-foreground leading-relaxed">
50
+ {description}
51
+ </p>
52
+ )}
53
+ </div>
54
+ {action && (
55
+ <div className="shrink-0 flex items-center gap-2">
56
+ {action}
57
+ </div>
58
+ )}
59
+ </div>
60
+ )
61
+ }
62
+
63
+ export { PageHeader }
@@ -159,8 +159,9 @@ function PasswordInput({
159
159
  aria-controls={inputId}
160
160
  data-slot="password-input-toggle"
161
161
  className={cn(
162
- "flex shrink-0 items-center text-muted-foreground",
162
+ "flex shrink-0 items-center rounded-sm text-muted-foreground outline-none",
163
163
  "hover:text-foreground",
164
+ "focus-visible:ring-[3px] focus-visible:ring-ring/50",
164
165
  "disabled:pointer-events-none",
165
166
  btnPadding
166
167
  )}
@@ -0,0 +1,288 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+
5
+ import { cn } from "../../lib/utils"
6
+ import { PasswordInput, type PasswordInputProps } from "./password-input"
7
+
8
+ // ─── Types ────────────────────────────────────────────────────────────────────
9
+
10
+ /** 0 = no input · 1 = weak · 2 = fair · 3 = good · 4 = strong */
11
+ export type PasswordStrength = 0 | 1 | 2 | 3 | 4
12
+
13
+ export interface PasswordStrengthInputProps
14
+ extends Omit<PasswordInputProps, "onChange" | "className"> {
15
+ /** Standard onChange forwarded to the underlying <input>. */
16
+ onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void
17
+ /**
18
+ * Custom strength calculator. Receives the raw value string and must return
19
+ * 0 (no input) | 1 (weak) | 2 (fair) | 3 (good) | 4 (strong).
20
+ *
21
+ * Default: built-in heuristic keyed off length + character variety.
22
+ * Replace via prop to wire zxcvbn, a backend scorer, or a rules list.
23
+ */
24
+ strengthFn?: (value: string) => PasswordStrength
25
+ /**
26
+ * Number of visual segments in the strength bar.
27
+ * @default 4
28
+ */
29
+ segments?: 3 | 4 | 5
30
+ /**
31
+ * Whether to render the strength label ("Weak", "Fair", "Good", "Strong").
32
+ * Label also carries the aria-live region so screen readers hear strength
33
+ * changes regardless of this prop.
34
+ * @default true
35
+ */
36
+ showLabel?: boolean
37
+ /**
38
+ * Whether to render the requirements hint list below the strength bar.
39
+ * @default false
40
+ */
41
+ showHints?: boolean
42
+ /** className on the outer wrapper div. */
43
+ className?: string
44
+ }
45
+
46
+ // ─── Default strength heuristic ───────────────────────────────────────────────
47
+
48
+ /**
49
+ * Returns 0–4 based on length + character-variety heuristics:
50
+ *
51
+ * | Score | Label | Criteria |
52
+ * |-------|--------|------------------------------------------------------|
53
+ * | 0 | — | Empty string |
54
+ * | 1 | Weak | Non-empty, none of the bonuses below |
55
+ * | 2 | Fair | ≥8 chars |
56
+ * | 3 | Good | ≥8 chars + uppercase/lowercase + digit |
57
+ * | 4 | Strong | ≥12 chars + uppercase/lowercase + digit + special |
58
+ *
59
+ * Pass your own `strengthFn` prop to use zxcvbn or a rules-based scorer.
60
+ */
61
+ export function defaultStrengthFn(value: string): PasswordStrength {
62
+ if (!value.length) return 0
63
+ let score = 0
64
+ if (value.length >= 8) score++
65
+ if (value.length >= 12) score++
66
+ if (/[A-Z]/.test(value) && /[a-z]/.test(value)) score++
67
+ if (/[0-9]/.test(value)) score++
68
+ if (/[^A-Za-z0-9]/.test(value)) score++
69
+ // Floor at 1 (weak) for any non-empty input; cap at 4 (strong).
70
+ return Math.min(4, Math.max(1, score)) as PasswordStrength
71
+ }
72
+
73
+ // ─── Static config ────────────────────────────────────────────────────────────
74
+
75
+ const STRENGTH_LABEL: Record<1 | 2 | 3 | 4, string> = {
76
+ 1: "Weak",
77
+ 2: "Fair",
78
+ 3: "Good",
79
+ 4: "Strong",
80
+ }
81
+
82
+ /**
83
+ * Segment and label colors, keyed by strength level.
84
+ *
85
+ * Uses `bg-[var(--token)]` for --success and --warning because those tokens
86
+ * are declared as oklch values; wrapping them in hsl() would silently fail.
87
+ * (Same pattern as Meter and Sonner.)
88
+ */
89
+ const STRENGTH_SEGMENT_BG: Record<1 | 2 | 3 | 4, string> = {
90
+ 1: "bg-destructive",
91
+ 2: "bg-[var(--warning)]",
92
+ 3: "bg-primary",
93
+ 4: "bg-[var(--success)]",
94
+ }
95
+
96
+ const STRENGTH_LABEL_COLOR: Record<1 | 2 | 3 | 4, string> = {
97
+ 1: "text-destructive",
98
+ 2: "text-[var(--warning)]",
99
+ 3: "text-primary",
100
+ 4: "text-[var(--success)]",
101
+ }
102
+
103
+ export const PASSWORD_HINTS = [
104
+ "At least 8 characters",
105
+ "Uppercase and lowercase letters",
106
+ "At least one number",
107
+ "At least one special character (!@#$…)",
108
+ "12 or more characters for maximum strength",
109
+ ] as const
110
+
111
+ // Segment transition — explicit properties, never transition-all.
112
+ const segmentMotion: React.CSSProperties = {
113
+ transitionProperty: "background-color",
114
+ transitionDuration: "var(--duration-base)",
115
+ transitionTimingFunction: "var(--ease-out)",
116
+ }
117
+
118
+ // ─── PasswordStrengthInput ────────────────────────────────────────────────────
119
+
120
+ /**
121
+ * PasswordInput with an inline segmented strength meter below the field.
122
+ *
123
+ * Composes BADS `PasswordInput` + a row of animated segment bars + a strength
124
+ * label. Strength is calculated from the live value via `strengthFn`; the
125
+ * built-in heuristic covers most signup/change-password surfaces. Override to
126
+ * wire zxcvbn or a backend scorer.
127
+ *
128
+ * ### Accessibility
129
+ * - Strength is conveyed by color **and** text (SC 1.4.1 — use of color).
130
+ * - The label carries `aria-live="polite"` + `aria-atomic="true"` so
131
+ * screen readers announce changes without the user having to query.
132
+ * - The input's `aria-describedby` is extended with the live-region id when
133
+ * there is text to describe.
134
+ *
135
+ * ### Peer parity
136
+ * Mantine `PasswordInput` (strength meter prop), shadcn/ui Auth block
137
+ * (password-strength composition), MUI docs (PasswordStrength example),
138
+ * Ark UI (PasswordInput + Meter composition).
139
+ *
140
+ * @example
141
+ * ```tsx
142
+ * // Uncontrolled — simplest usage on a signup form
143
+ * <PasswordStrengthInput
144
+ * placeholder="New password"
145
+ * autoComplete="new-password"
146
+ * showHints
147
+ * />
148
+ *
149
+ * // Controlled
150
+ * const [pw, setPw] = React.useState("")
151
+ * <PasswordStrengthInput
152
+ * value={pw}
153
+ * onChange={(e) => setPw(e.target.value)}
154
+ * autoComplete="new-password"
155
+ * />
156
+ * ```
157
+ */
158
+ export function PasswordStrengthInput({
159
+ value,
160
+ defaultValue = "",
161
+ onChange,
162
+ strengthFn = defaultStrengthFn,
163
+ segments = 4,
164
+ showLabel = true,
165
+ showHints = false,
166
+ id,
167
+ className,
168
+ "aria-describedby": consumerDescribedBy,
169
+ ...props
170
+ }: PasswordStrengthInputProps) {
171
+ const generatedId = React.useId()
172
+ const inputId = id ?? generatedId
173
+ const strengthRegionId = `${inputId}-strength`
174
+
175
+ // Uncontrolled path: track the raw value in local state so strength updates
176
+ // on every keystroke. Controlled path: strength is derived from `value` prop.
177
+ const [internalValue, setInternalValue] = React.useState(
178
+ typeof defaultValue === "string" ? defaultValue : ""
179
+ )
180
+ const isControlled = value !== undefined
181
+ const currentValue = isControlled ? String(value ?? "") : internalValue
182
+ const strength = strengthFn(currentValue)
183
+ const hasInput = currentValue.length > 0
184
+
185
+ function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
186
+ if (!isControlled) setInternalValue(e.target.value)
187
+ onChange?.(e)
188
+ }
189
+
190
+ // Merge caller's aria-describedby with the strength region id.
191
+ const mergedDescribedBy = [
192
+ consumerDescribedBy,
193
+ hasInput ? strengthRegionId : undefined,
194
+ ]
195
+ .filter(Boolean)
196
+ .join(" ") || undefined
197
+
198
+ // How many segments should appear filled at this strength level?
199
+ // round((strength / 4) * N) maps 0–4 evenly onto 0–N for any segment count.
200
+ const filledCount = hasInput ? Math.round((strength / 4) * segments) : 0
201
+
202
+ const strengthKey = strength as 1 | 2 | 3 | 4
203
+ const segmentColor =
204
+ hasInput && strength > 0 ? STRENGTH_SEGMENT_BG[strengthKey] : null
205
+
206
+ return (
207
+ <div
208
+ className={cn("flex flex-col gap-1.5", className)}
209
+ data-slot="password-strength-input"
210
+ >
211
+ <PasswordInput
212
+ id={inputId}
213
+ value={isControlled ? value : undefined}
214
+ defaultValue={isControlled ? undefined : (defaultValue as string)}
215
+ onChange={handleChange}
216
+ aria-describedby={mergedDescribedBy}
217
+ {...props}
218
+ />
219
+
220
+ {/* Segment bar — aria-hidden; the live region below carries the a11y signal */}
221
+ <div
222
+ role="presentation"
223
+ aria-hidden="true"
224
+ className="flex gap-1"
225
+ data-slot="strength-segments"
226
+ >
227
+ {Array.from({ length: segments }, (_, i) => {
228
+ const filled = i < filledCount
229
+ return (
230
+ <div
231
+ key={i}
232
+ data-slot="strength-segment"
233
+ data-filled={filled || undefined}
234
+ className={cn(
235
+ "h-1.5 flex-1 rounded-full",
236
+ filled && segmentColor ? segmentColor : "bg-border"
237
+ )}
238
+ style={segmentMotion}
239
+ />
240
+ )
241
+ })}
242
+ </div>
243
+
244
+ {/* Strength label + aria-live region */}
245
+ {showLabel && (
246
+ <p
247
+ id={strengthRegionId}
248
+ role="status"
249
+ aria-live="polite"
250
+ aria-atomic="true"
251
+ data-slot="strength-label"
252
+ className={cn(
253
+ "h-[1.25rem] text-sm font-medium leading-none",
254
+ !hasInput || strength === 0
255
+ ? "text-transparent select-none"
256
+ : STRENGTH_LABEL_COLOR[strengthKey]
257
+ )}
258
+ >
259
+ {hasInput && strength > 0 ? STRENGTH_LABEL[strengthKey] : " "}
260
+ </p>
261
+ )}
262
+
263
+ {/* Optional requirements hints */}
264
+ {showHints && (
265
+ <ul
266
+ data-slot="strength-hints"
267
+ className="mt-0.5 space-y-1"
268
+ aria-label="Password requirements"
269
+ >
270
+ {PASSWORD_HINTS.map((hint) => (
271
+ <li
272
+ key={hint}
273
+ className="flex items-center gap-2 text-sm text-muted-foreground"
274
+ >
275
+ <span
276
+ className="size-1.5 shrink-0 rounded-full bg-current opacity-30"
277
+ aria-hidden="true"
278
+ />
279
+ {hint}
280
+ </li>
281
+ ))}
282
+ </ul>
283
+ )}
284
+ </div>
285
+ )
286
+ }
287
+
288
+ PasswordStrengthInput.displayName = "PasswordStrengthInput"