@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
@@ -0,0 +1,351 @@
1
+ "use client"
2
+
3
+ // JsonInput needs useState/useCallback for parse state, so it cannot be a
4
+ // server component. See the note in button.tsx on why the simpler primitives
5
+ // that only forward callbacks can stay server-renderable.
6
+ import * as React from "react"
7
+ import { cva, type VariantProps } from "class-variance-authority"
8
+ import { AlertCircle, CheckCircle2, WrapText } from "lucide-react"
9
+
10
+ import { cn } from "../../lib/utils"
11
+ import { Textarea } from "./textarea"
12
+ import { Button } from "./button"
13
+
14
+ // ─── Types ────────────────────────────────────────────────────────────────────
15
+
16
+ export interface JsonInputProps
17
+ extends Omit<
18
+ React.ComponentProps<typeof Textarea>,
19
+ "aria-invalid" | "value" | "defaultValue" | "onChange" | "onError"
20
+ > {
21
+ /** Controlled string value (raw JSON text). */
22
+ value?: string
23
+ /** Uncontrolled default value. */
24
+ defaultValue?: string
25
+ /** Fires on every keystroke with the raw text — same contract as Textarea onChange. */
26
+ onChange?: (e: React.ChangeEvent<HTMLTextAreaElement>) => void
27
+ /**
28
+ * Fires whenever the value is valid JSON, with the parsed result.
29
+ * Not called when the field is empty or contains invalid JSON.
30
+ */
31
+ onValidChange?: (parsed: unknown) => void
32
+ /**
33
+ * Fires whenever the validation state changes.
34
+ * Receives the error message (string) when invalid, or null when valid/empty.
35
+ */
36
+ onError?: (error: string | null) => void
37
+ /**
38
+ * When to run validation.
39
+ * - `"change"` (default) — on every keystroke; shows errors as the user types
40
+ * - `"blur"` — validates only when the field loses focus
41
+ */
42
+ validateOn?: "change" | "blur"
43
+ /**
44
+ * Show a "Format" button that auto-pretty-prints the JSON on click.
45
+ * The button is inside the field area and calls JSON.stringify(parse, null, 2).
46
+ * Default `true`.
47
+ */
48
+ showFormatButton?: boolean
49
+ /**
50
+ * Number of spaces to use when formatting JSON. Default 2.
51
+ * Passed to `JSON.stringify(parsed, null, indent)`.
52
+ */
53
+ formatIndent?: number
54
+ /**
55
+ * Error message to display. When provided, this overrides the built-in
56
+ * JSON.parse error message. Useful for server-side validation feedback.
57
+ * Pass `null` to clear an external error.
58
+ */
59
+ externalError?: string | null
60
+ /** Size variant — matches Textarea sizes. */
61
+ size?: "sm" | "default" | "lg" | "xl"
62
+ }
63
+
64
+ // ─── Helpers ──────────────────────────────────────────────────────────────────
65
+
66
+ /**
67
+ * Try to parse a string as JSON. Returns {ok, parsed, error}.
68
+ * Empty string is treated as "not entered yet" — ok is undefined (neutral).
69
+ */
70
+ function parseJson(
71
+ text: string
72
+ ): { ok: true; parsed: unknown } | { ok: false; error: string } | { ok: undefined } {
73
+ if (text.trim() === "") return { ok: undefined }
74
+ try {
75
+ return { ok: true, parsed: JSON.parse(text) }
76
+ } catch (err) {
77
+ const raw = err instanceof Error ? err.message : "Invalid JSON"
78
+ // Trim the "JSON Parse error:" / "SyntaxError: " prefix noise some engines add.
79
+ const cleaned = raw.replace(/^JSON Parse error:\s*/i, "").replace(/^SyntaxError:\s*/i, "")
80
+ return { ok: false, error: cleaned }
81
+ }
82
+ }
83
+
84
+ function formatJson(text: string, indent: number): string {
85
+ try {
86
+ return JSON.stringify(JSON.parse(text), null, indent)
87
+ } catch {
88
+ return text
89
+ }
90
+ }
91
+
92
+ // ─── JsonInput ────────────────────────────────────────────────────────────────
93
+
94
+ /**
95
+ * JsonInput — a `<Textarea>` specialized for JSON text entry. Validates on
96
+ * every keystroke (or on blur) and shows an inline error when the text is not
97
+ * valid JSON. Fires `onValidChange(parsed)` whenever valid JSON is present.
98
+ * An optional "Format" button auto-indents the content.
99
+ *
100
+ * Peer parity: Mantine JsonInput (textarea + JSON.parse validation + error msg
101
+ * + optional formatOnBlur prop), Ant Design's config-panel pattern, shadcn
102
+ * JSON config examples. T1 tier.
103
+ *
104
+ * Accessibility
105
+ * -------------
106
+ * - `aria-invalid="true"` is set on the `<textarea>` when the value contains
107
+ * invalid JSON. The Textarea component uses this for its destructive ring.
108
+ * - The error message is a `role="status"` region (aria-live="polite") so screen readers announce it
109
+ * when it appears. The alert id is added to the textarea's
110
+ * `aria-describedby` so the validation message is associated with the field.
111
+ * - The optional "Format" button has a descriptive aria-label.
112
+ *
113
+ * Motion
114
+ * ------
115
+ * Pattern (c) — the Textarea already carries `transition-[color,box-shadow]`
116
+ * on the ring; the status icon fades in/out via `transition-opacity` +
117
+ * `var(--duration-fast)` / `var(--ease-out)`. The error message slides down
118
+ * with `data-[visible=true]:animate-in data-[visible=true]:slide-in-from-top-1`
119
+ * (existing BADS keyframes, pattern a).
120
+ */
121
+ export function JsonInput({
122
+ value: controlledValue,
123
+ defaultValue,
124
+ onChange,
125
+ onValidChange,
126
+ onError,
127
+ validateOn = "change",
128
+ showFormatButton = true,
129
+ formatIndent = 2,
130
+ externalError,
131
+ size,
132
+ className,
133
+ disabled,
134
+ placeholder = '{"key": "value"}',
135
+ ...props
136
+ }: JsonInputProps) {
137
+ const errorId = React.useId()
138
+
139
+ // ── Controlled / uncontrolled state ───────────────────────────────────────
140
+ const isControlled = controlledValue !== undefined
141
+ const [internalValue, setInternalValue] = React.useState<string>(defaultValue ?? "")
142
+ const text = isControlled ? controlledValue : internalValue
143
+
144
+ // ── Parse state ───────────────────────────────────────────────────────────
145
+ // "dirty" tracks whether the user has ever typed (don't show errors on first
146
+ // paint of an empty field or an already-valid initial value).
147
+ const [dirty, setDirty] = React.useState<boolean>(
148
+ () => !!defaultValue || !!controlledValue
149
+ )
150
+ const [parseResult, setParseResult] = React.useState<
151
+ ReturnType<typeof parseJson>
152
+ >(() => parseJson(text ?? ""))
153
+
154
+ // ── Callbacks ─────────────────────────────────────────────────────────────
155
+ const prevErrorRef = React.useRef<string | null | undefined>(undefined)
156
+ const prevValidRef = React.useRef<unknown>(undefined)
157
+
158
+ function runValidation(raw: string) {
159
+ const result = parseJson(raw)
160
+ setParseResult(result)
161
+
162
+ // Fire onValidChange only when the parsed value actually changes.
163
+ if (result.ok === true) {
164
+ if (result.parsed !== prevValidRef.current) {
165
+ prevValidRef.current = result.parsed
166
+ onValidChange?.(result.parsed)
167
+ }
168
+ } else {
169
+ prevValidRef.current = undefined
170
+ }
171
+
172
+ // Fire onError when error state changes.
173
+ const error = result.ok === false ? result.error : null
174
+ if (error !== prevErrorRef.current) {
175
+ prevErrorRef.current = error
176
+ onError?.(error)
177
+ }
178
+ }
179
+
180
+ function handleChange(e: React.ChangeEvent<HTMLTextAreaElement>) {
181
+ const raw = e.target.value
182
+ if (!isControlled) setInternalValue(raw)
183
+ setDirty(true)
184
+ if (validateOn === "change") runValidation(raw)
185
+ onChange?.(e)
186
+ }
187
+
188
+ function handleBlur(e: React.FocusEvent<HTMLTextAreaElement>) {
189
+ if (validateOn === "blur") {
190
+ setDirty(true)
191
+ runValidation(text ?? "")
192
+ }
193
+ props.onBlur?.(e)
194
+ }
195
+
196
+ function handleFormat() {
197
+ if (!text) return
198
+ const formatted = formatJson(text, formatIndent)
199
+ if (!isControlled) setInternalValue(formatted)
200
+ // Synthesize a change event so the controlled consumer can update too.
201
+ const nativeInput = textareaRef.current
202
+ if (nativeInput) {
203
+ const descriptor = Object.getOwnPropertyDescriptor(
204
+ HTMLTextAreaElement.prototype,
205
+ "value"
206
+ )
207
+ descriptor?.set?.call(nativeInput, formatted)
208
+ nativeInput.dispatchEvent(new Event("input", { bubbles: true }))
209
+ // Also call onChange directly to match normal input behaviour.
210
+ const syntheticEvent = {
211
+ target: nativeInput,
212
+ currentTarget: nativeInput,
213
+ } as React.ChangeEvent<HTMLTextAreaElement>
214
+ onChange?.(syntheticEvent)
215
+ }
216
+ runValidation(formatted)
217
+ }
218
+
219
+ const textareaRef = React.useRef<HTMLTextAreaElement>(null)
220
+
221
+ // Sync parse state when the controlled value changes externally.
222
+ React.useEffect(() => {
223
+ if (isControlled) {
224
+ runValidation(controlledValue ?? "")
225
+ }
226
+ // eslint-disable-next-line react-hooks/exhaustive-deps
227
+ }, [controlledValue])
228
+
229
+ // ── Derived ────────────────────────────────────────────────────────────────
230
+ // Resolve effective error (external prop overrides internal parse result).
231
+ const internalError = parseResult.ok === false ? parseResult.error : null
232
+ const effectiveError = externalError !== undefined ? externalError : internalError
233
+ const showError = dirty && !!effectiveError
234
+ const showValid = dirty && parseResult.ok === true && !externalError
235
+ const isEmpty = !text || text.trim() === ""
236
+
237
+ // ─── Render ───────────────────────────────────────────────────────────────
238
+
239
+ return (
240
+ <div
241
+ data-slot="json-input-root"
242
+ className={cn("relative flex flex-col gap-1.5", className)}
243
+ >
244
+ {/* Textarea + optional Format button wrapper */}
245
+ <div className="relative">
246
+ <Textarea
247
+ {...props}
248
+ ref={textareaRef}
249
+ size={size}
250
+ value={isControlled ? controlledValue : internalValue}
251
+ onChange={handleChange}
252
+ onBlur={handleBlur}
253
+ disabled={disabled}
254
+ placeholder={placeholder}
255
+ aria-invalid={showError ? "true" : undefined}
256
+ aria-describedby={
257
+ [props["aria-describedby"], showError ? errorId : undefined]
258
+ .filter(Boolean)
259
+ .join(" ") || undefined
260
+ }
261
+ spellCheck={false}
262
+ autoCapitalize="none"
263
+ autoCorrect="off"
264
+ data-slot="json-input-textarea"
265
+ // Right-side padding so text never runs under the status icon.
266
+ className={cn(
267
+ "font-mono",
268
+ (showFormatButton || !isEmpty) && "pr-9"
269
+ )}
270
+ />
271
+
272
+ {/* Status icon — valid or empty show nothing, invalid shows AlertCircle */}
273
+ <div
274
+ aria-hidden="true"
275
+ data-slot="json-input-status"
276
+ className={cn(
277
+ "pointer-events-none absolute right-3 top-3",
278
+ "transition-opacity",
279
+ "size-4 shrink-0"
280
+ )}
281
+ style={{
282
+ transitionDuration: "var(--duration-fast)",
283
+ transitionTimingFunction: "var(--ease-out)",
284
+ opacity: showError || showValid ? 1 : 0,
285
+ }}
286
+ >
287
+ {showValid && (
288
+ <CheckCircle2
289
+ className="size-4 text-[var(--color-success,oklch(0.65_0.15_150))]"
290
+ strokeWidth={1.5}
291
+ />
292
+ )}
293
+ {showError && (
294
+ <AlertCircle className="size-4 text-destructive" strokeWidth={1.5} />
295
+ )}
296
+ </div>
297
+ </div>
298
+
299
+ {/* Bottom row: error message + Format button */}
300
+ <div className="flex min-h-0 items-start justify-between gap-2">
301
+ {/* Error message — announces on appearance via role=alert */}
302
+ <p
303
+ id={errorId}
304
+ role="status"
305
+ aria-live="polite"
306
+ aria-atomic="true"
307
+ data-slot="json-input-error"
308
+ className={cn(
309
+ "flex min-w-0 items-start gap-1 text-xs text-destructive",
310
+ "transition-opacity",
311
+ showError ? "opacity-100" : "opacity-0 pointer-events-none select-none"
312
+ )}
313
+ style={{
314
+ transitionDuration: "var(--duration-fast)",
315
+ transitionTimingFunction: "var(--ease-out)",
316
+ }}
317
+ >
318
+ {showError && (
319
+ <>
320
+ <AlertCircle
321
+ aria-hidden="true"
322
+ className="mt-px size-3.5 shrink-0 text-destructive"
323
+ strokeWidth={1.5}
324
+ />
325
+ <span className="break-words">{effectiveError}</span>
326
+ </>
327
+ )}
328
+ </p>
329
+
330
+ {/* Format button */}
331
+ {showFormatButton && (
332
+ <Button
333
+ type="button"
334
+ variant="ghost"
335
+ size="sm"
336
+ aria-label="Format JSON"
337
+ disabled={disabled || isEmpty || parseResult.ok === false}
338
+ onClick={handleFormat}
339
+ data-slot="json-input-format-button"
340
+ className="h-auto shrink-0 px-2 py-0.5 text-xs text-muted-foreground hover:text-foreground"
341
+ >
342
+ <WrapText aria-hidden="true" className="size-3.5" strokeWidth={1.5} />
343
+ Format
344
+ </Button>
345
+ )}
346
+ </div>
347
+ </div>
348
+ )
349
+ }
350
+
351
+ JsonInput.displayName = "JsonInput"
@@ -62,7 +62,7 @@ function MonthPicker({
62
62
  className,
63
63
  id,
64
64
  }: MonthPickerProps) {
65
- const isControlled = value !== undefined
65
+ const isControlled = value !== undefined || onChange !== undefined
66
66
  const [internalValue, setInternalValue] = React.useState<Date | undefined>(
67
67
  defaultValue
68
68
  )
@@ -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 }