@behavioral-agentic-design-system/core 0.27.0 → 0.29.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 (113) hide show
  1. package/package.json +5 -5
  2. package/scripts/a11y-lint.cjs +78 -9
  3. package/scripts/build-tokens.cjs +273 -15
  4. package/scripts/wcag-audit.cjs +37 -7
  5. package/src/api/layers/file.ts +1 -0
  6. package/src/app/font-ready.tsx +6 -5
  7. package/src/app/layout.tsx +54 -3
  8. package/src/app/preview/components/page.tsx +5735 -2500
  9. package/src/app/preview/layout.tsx +4 -1
  10. package/src/app/preview/showcase-filter.tsx +66 -0
  11. package/src/app/preview/tab-replay.tsx +63 -0
  12. package/src/app/shell.tsx +91 -18
  13. package/src/components/customize/save-bar.tsx +19 -6
  14. package/src/components/docs-tab.tsx +36 -24
  15. package/src/components/layers-tab.tsx +37 -5
  16. package/src/components/ui/ai-badge.tsx +74 -0
  17. package/src/components/ui/alert.tsx +12 -0
  18. package/src/components/ui/badge.tsx +19 -0
  19. package/src/components/ui/chat-bubble.tsx +298 -0
  20. package/src/components/ui/chat-marker.tsx +120 -0
  21. package/src/components/ui/checkbox.tsx +9 -1
  22. package/src/components/ui/clipboard.tsx +291 -0
  23. package/src/components/ui/close-button.tsx +71 -0
  24. package/src/components/ui/combobox.tsx +62 -3
  25. package/src/components/ui/container.tsx +65 -0
  26. package/src/components/ui/copy-button.tsx +5 -1
  27. package/src/components/ui/data-table.tsx +388 -0
  28. package/src/components/ui/date-field.tsx +368 -0
  29. package/src/components/ui/drawer.tsx +334 -0
  30. package/src/components/ui/file-button.tsx +145 -0
  31. package/src/components/ui/floating-indicator.tsx +217 -0
  32. package/src/components/ui/focus-trap.tsx +184 -0
  33. package/src/components/ui/format-byte.tsx +113 -0
  34. package/src/components/ui/index.ts +28 -0
  35. package/src/components/ui/input.tsx +38 -3
  36. package/src/components/ui/keyboard-shortcut.tsx +146 -0
  37. package/src/components/ui/loading-dots.tsx +99 -0
  38. package/src/components/ui/mark.tsx +69 -0
  39. package/src/components/ui/month-picker.tsx +296 -0
  40. package/src/components/ui/multi-select.tsx +15 -13
  41. package/src/components/ui/nav-link.tsx +200 -0
  42. package/src/components/ui/navigation-rail.tsx +256 -0
  43. package/src/components/ui/notification.tsx +20 -0
  44. package/src/components/ui/password-input.tsx +34 -1
  45. package/src/components/ui/progress.tsx +15 -1
  46. package/src/components/ui/prose.tsx +62 -0
  47. package/src/components/ui/result.tsx +151 -0
  48. package/src/components/ui/rolling-number.tsx +201 -0
  49. package/src/components/ui/simple-grid.tsx +110 -0
  50. package/src/components/ui/skeleton.tsx +52 -3
  51. package/src/components/ui/squircle.tsx +274 -0
  52. package/src/components/ui/stack.tsx +105 -0
  53. package/src/components/ui/status-badge.tsx +93 -0
  54. package/src/components/ui/tabs.tsx +34 -7
  55. package/src/components/ui/tag.tsx +46 -5
  56. package/src/components/ui/theme-icon.tsx +138 -0
  57. package/src/components/ui/timeline.tsx +27 -10
  58. package/src/components/ui/tooltip.tsx +12 -1
  59. package/src/components/ui/tree-select.tsx +386 -0
  60. package/src/components/ui/typing-indicator.tsx +2 -2
  61. package/src/components/ui/word-rotate.tsx +6 -1
  62. package/src/components/ui/year-picker.tsx +307 -0
  63. package/src/data/docs-index.ts +10 -0
  64. package/src/hooks/use-global-primary-color.ts +57 -6
  65. package/src/stories/AiBadge.stories.tsx +67 -0
  66. package/src/stories/Alert.stories.tsx +31 -1
  67. package/src/stories/Badge.stories.tsx +63 -6
  68. package/src/stories/ChatBubble.stories.tsx +222 -0
  69. package/src/stories/ChatMarker.stories.tsx +59 -0
  70. package/src/stories/Checkbox.stories.tsx +5 -0
  71. package/src/stories/Clipboard.stories.tsx +136 -0
  72. package/src/stories/CloseButton.stories.tsx +65 -0
  73. package/src/stories/Combobox.stories.tsx +74 -3
  74. package/src/stories/Container.stories.tsx +134 -0
  75. package/src/stories/CopyButton.stories.tsx +2 -0
  76. package/src/stories/DataTable.stories.tsx +271 -0
  77. package/src/stories/DateField.stories.tsx +114 -0
  78. package/src/stories/Drawer.stories.tsx +211 -0
  79. package/src/stories/FileButton.stories.tsx +117 -0
  80. package/src/stories/FloatingIndicator.stories.tsx +343 -0
  81. package/src/stories/FocusTrap.stories.tsx +218 -0
  82. package/src/stories/FormatByte.stories.tsx +142 -0
  83. package/src/stories/Input.stories.tsx +91 -0
  84. package/src/stories/KeyboardShortcut.stories.tsx +87 -0
  85. package/src/stories/LoadingDots.stories.tsx +73 -0
  86. package/src/stories/Mark.stories.tsx +84 -0
  87. package/src/stories/MonthPicker.stories.tsx +99 -0
  88. package/src/stories/MultiSelect.stories.tsx +3 -1
  89. package/src/stories/NavLink.stories.tsx +213 -0
  90. package/src/stories/NavigationRail.stories.tsx +413 -0
  91. package/src/stories/Notification.stories.tsx +53 -0
  92. package/src/stories/PasswordInput.stories.tsx +21 -0
  93. package/src/stories/Progress.stories.tsx +38 -0
  94. package/src/stories/Prose.stories.tsx +232 -0
  95. package/src/stories/Result.stories.tsx +145 -0
  96. package/src/stories/RollingNumber.stories.tsx +226 -0
  97. package/src/stories/SimpleGrid.stories.tsx +130 -0
  98. package/src/stories/Skeleton.stories.tsx +62 -1
  99. package/src/stories/Squircle.stories.tsx +127 -0
  100. package/src/stories/Stack.stories.tsx +139 -0
  101. package/src/stories/StatusBadge.stories.tsx +125 -0
  102. package/src/stories/Tabs.stories.tsx +56 -1
  103. package/src/stories/Tag.stories.tsx +31 -0
  104. package/src/stories/ThemeIcon.stories.tsx +97 -0
  105. package/src/stories/Timeline.stories.tsx +69 -0
  106. package/src/stories/Tooltip.stories.tsx +18 -0
  107. package/src/stories/TreeSelect.stories.tsx +222 -0
  108. package/src/stories/TypingIndicator.stories.tsx +1 -0
  109. package/src/stories/WordRotate.stories.tsx +1 -0
  110. package/src/stories/YearPicker.stories.tsx +100 -0
  111. package/src/styles.css +289 -15
  112. package/src/tokens.json +96 -1
  113. package/LICENSE +0 -21
@@ -0,0 +1,201 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import { cn } from "../../lib/utils"
5
+
6
+ /**
7
+ * RollingNumber — animated digit counter that scrolls each digit independently
8
+ * (odometer / slot-machine style) when the value prop changes.
9
+ *
10
+ * Distinct from:
11
+ * - `FormatNumber` — static formatted display, no animation
12
+ * - `Stat` / `StatCard` — layout containers that hold a number; static
13
+ * - `Timer` — ticks on a live interval toward a deadline
14
+ *
15
+ * Use for dashboards, pricing counters, and KPI tiles where the value update
16
+ * itself is meaningful (revenue milestones, live seat counts, real-time stats).
17
+ * Don't use for values that change faster than ~1s — the animation will look
18
+ * like a blur rather than a meaningful transition.
19
+ *
20
+ * Motion: pattern (c) — inline style with var(--duration-base) + var(--ease-spring).
21
+ * Contained within each digit column; no layout shift. Base layer's
22
+ * prefers-reduced-motion rule silences the transition automatically.
23
+ *
24
+ * Accessibility: digits are aria-hidden; the containing span carries
25
+ * aria-label with the formatted value so screen readers announce the final
26
+ * number. aria-live="polite" is the default — value changes are typically
27
+ * meaningful events (a KPI crossed a milestone). Override with
28
+ * aria-live="off" for high-frequency updates.
29
+ */
30
+
31
+ // --- types ---
32
+
33
+ export interface RollingNumberProps
34
+ extends Omit<React.ComponentProps<"span">, "children"> {
35
+ /** The numeric value to display. Digit columns animate when this changes. */
36
+ value: number
37
+ /** Fixed decimal places to show. When absent, uses the value's natural precision. */
38
+ decimalScale?: number
39
+ /**
40
+ * Force decimalScale digits even for whole numbers (e.g. 42 → "42.00").
41
+ * Requires `decimalScale`. Default false.
42
+ */
43
+ fixedDecimalScale?: boolean
44
+ /**
45
+ * Thousands separator character (e.g. "," → "1,234,567").
46
+ * Default "" (no separator).
47
+ */
48
+ thousandSeparator?: string
49
+ /** Static prefix rendered before the number (e.g. "$"). Not animated. */
50
+ prefix?: string
51
+ /** Static suffix rendered after the number (e.g. "%", "k"). Not animated. */
52
+ suffix?: string
53
+ }
54
+
55
+ // --- helpers ---
56
+
57
+ type Part = { type: "digit"; value: number } | { type: "static"; char: string }
58
+
59
+ function toParts(
60
+ value: number,
61
+ thousandSeparator: string,
62
+ decimalScale: number | undefined,
63
+ fixedDecimalScale: boolean
64
+ ): Part[] {
65
+ let str: string
66
+ if (decimalScale !== undefined) {
67
+ const naturalPlaces = value.toString().split(".")[1]?.length ?? 0
68
+ const places = fixedDecimalScale
69
+ ? decimalScale
70
+ : Math.min(decimalScale, naturalPlaces)
71
+ str = value.toFixed(places)
72
+ } else {
73
+ str = String(value)
74
+ }
75
+
76
+ const [intRaw, decRaw] = str.split(".")
77
+ const intFormatted = thousandSeparator
78
+ ? intRaw.replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator)
79
+ : intRaw
80
+ const full = intFormatted + (decRaw !== undefined ? "." + decRaw : "")
81
+
82
+ return [...full].map((ch) =>
83
+ ch >= "0" && ch <= "9"
84
+ ? { type: "digit" as const, value: Number(ch) }
85
+ : { type: "static" as const, char: ch }
86
+ )
87
+ }
88
+
89
+ function formatLabel(
90
+ value: number,
91
+ prefix: string | undefined,
92
+ suffix: string | undefined,
93
+ decimalScale: number | undefined,
94
+ fixedDecimalScale: boolean
95
+ ): string {
96
+ let str: string
97
+ if (decimalScale !== undefined) {
98
+ const naturalPlaces = value.toString().split(".")[1]?.length ?? 0
99
+ const places = fixedDecimalScale
100
+ ? decimalScale
101
+ : Math.min(decimalScale, naturalPlaces)
102
+ str = value.toFixed(places)
103
+ } else {
104
+ str = String(value)
105
+ }
106
+ return (prefix ?? "") + str + (suffix ?? "")
107
+ }
108
+
109
+ // --- digit column ---
110
+
111
+ function DigitColumn({ digit }: { digit: number }) {
112
+ return (
113
+ <span
114
+ aria-hidden="true"
115
+ data-slot="rolling-number-digit"
116
+ className="relative inline-block overflow-hidden"
117
+ style={{ height: "1em", lineHeight: "1em" }}
118
+ >
119
+ {/* The inner column is 10em tall (one em per digit 0-9).
120
+ translateY shifts it to reveal the correct digit through the 1em window.
121
+ -digit * 10% of 10em = -digit * 1em — one digit height per step. */}
122
+ <span
123
+ className="flex flex-col"
124
+ style={{
125
+ transform: `translateY(${-digit * 10}%)`,
126
+ transitionProperty: "transform",
127
+ transitionDuration: "var(--duration-base)",
128
+ transitionTimingFunction: "var(--ease-spring)",
129
+ }}
130
+ >
131
+ {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((d) => (
132
+ <span
133
+ key={d}
134
+ style={{
135
+ height: "1em",
136
+ display: "flex",
137
+ alignItems: "center",
138
+ justifyContent: "center",
139
+ }}
140
+ >
141
+ {d}
142
+ </span>
143
+ ))}
144
+ </span>
145
+ </span>
146
+ )
147
+ }
148
+
149
+ // --- public component ---
150
+
151
+ export function RollingNumber({
152
+ value,
153
+ decimalScale,
154
+ fixedDecimalScale = false,
155
+ thousandSeparator = "",
156
+ prefix,
157
+ suffix,
158
+ className,
159
+ ...props
160
+ }: RollingNumberProps) {
161
+ const parts = toParts(value, thousandSeparator, decimalScale, fixedDecimalScale)
162
+ const label = formatLabel(value, prefix, suffix, decimalScale, fixedDecimalScale)
163
+
164
+ return (
165
+ <span
166
+ data-slot="rolling-number"
167
+ role="status"
168
+ aria-label={label}
169
+ aria-live="polite"
170
+ className={cn(
171
+ "inline-flex items-center tabular-nums",
172
+ className
173
+ )}
174
+ {...props}
175
+ >
176
+ {prefix && (
177
+ <span data-slot="rolling-number-prefix" aria-hidden="true">
178
+ {prefix}
179
+ </span>
180
+ )}
181
+ {parts.map((part, i) =>
182
+ part.type === "digit" ? (
183
+ <DigitColumn key={i} digit={part.value} />
184
+ ) : (
185
+ <span
186
+ key={i}
187
+ data-slot="rolling-number-separator"
188
+ aria-hidden="true"
189
+ >
190
+ {part.char}
191
+ </span>
192
+ )
193
+ )}
194
+ {suffix && (
195
+ <span data-slot="rolling-number-suffix" aria-hidden="true">
196
+ {suffix}
197
+ </span>
198
+ )}
199
+ </span>
200
+ )
201
+ }
@@ -0,0 +1,110 @@
1
+ "use client";
2
+
3
+ import * as React from "react";
4
+ import { cn } from "../../lib/utils";
5
+
6
+ // ─── SimpleGrid ────────────────────────────────────────────────────────────────
7
+ //
8
+ // Responsive equal-column CSS grid. Replaces boilerplate
9
+ // `<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">` with a
10
+ // statically-safe API: every column count maps to a literal Tailwind class
11
+ // from the lookup tables below, so the classes always survive the Tailwind v4
12
+ // scanner (a template-string `grid-cols-${n}` silently compiles to nothing).
13
+ //
14
+ // For variable-height content that should pack (Pinterest-style), use Masonry.
15
+ // For tabular data, use Table/DataTable. SimpleGrid is for equal-width cells
16
+ // in row-aligned tracks: card grids, stat rows, settings tiles, galleries.
17
+ //
18
+ // Layout-only primitive (same class as Stack/Group/Container): no ARIA, no
19
+ // interaction, no motion. Cross-system references: Mantine SimpleGrid,
20
+ // Chakra SimpleGrid; MUI Grid.
21
+
22
+ type Cols = 1 | 2 | 3 | 4 | 5 | 6;
23
+
24
+ /** Column counts per breakpoint. `base` applies from 0px up; sm/md/lg override upward. */
25
+ export interface ResponsiveCols {
26
+ base?: Cols;
27
+ sm?: Cols;
28
+ md?: Cols;
29
+ lg?: Cols;
30
+ }
31
+
32
+ // Literal class maps — every generated class must be spelled out so the
33
+ // Tailwind scanner ships it. Never build these strings dynamically.
34
+ const BASE_COLS: Record<Cols, string> = {
35
+ 1: "grid-cols-1",
36
+ 2: "grid-cols-2",
37
+ 3: "grid-cols-3",
38
+ 4: "grid-cols-4",
39
+ 5: "grid-cols-5",
40
+ 6: "grid-cols-6",
41
+ };
42
+ const SM_COLS: Record<Cols, string> = {
43
+ 1: "sm:grid-cols-1",
44
+ 2: "sm:grid-cols-2",
45
+ 3: "sm:grid-cols-3",
46
+ 4: "sm:grid-cols-4",
47
+ 5: "sm:grid-cols-5",
48
+ 6: "sm:grid-cols-6",
49
+ };
50
+ const MD_COLS: Record<Cols, string> = {
51
+ 1: "md:grid-cols-1",
52
+ 2: "md:grid-cols-2",
53
+ 3: "md:grid-cols-3",
54
+ 4: "md:grid-cols-4",
55
+ 5: "md:grid-cols-5",
56
+ 6: "md:grid-cols-6",
57
+ };
58
+ const LG_COLS: Record<Cols, string> = {
59
+ 1: "lg:grid-cols-1",
60
+ 2: "lg:grid-cols-2",
61
+ 3: "lg:grid-cols-3",
62
+ 4: "lg:grid-cols-4",
63
+ 5: "lg:grid-cols-5",
64
+ 6: "lg:grid-cols-6",
65
+ };
66
+
67
+ /** Same token-keyed gap scale as Stack/Group (gap-0/1/2/4/6/8 → 0/4/8/16/24/32px). */
68
+ const GAP: Record<"none" | "xs" | "sm" | "md" | "lg" | "xl", string> = {
69
+ none: "gap-0",
70
+ xs: "gap-1",
71
+ sm: "gap-2",
72
+ md: "gap-4",
73
+ lg: "gap-6",
74
+ xl: "gap-8",
75
+ };
76
+
77
+ export interface SimpleGridProps extends React.HTMLAttributes<HTMLDivElement> {
78
+ /**
79
+ * Column count — a single number (fixed at all widths) or a responsive
80
+ * object, e.g. `{ base: 1, sm: 2, lg: 3 }`. Values clamp to 1–6.
81
+ * Default: `{ base: 1, sm: 2, lg: 3 }` — the standard card-grid shape.
82
+ */
83
+ cols?: Cols | ResponsiveCols;
84
+ /** Gap between cells, keyed to the BADS spacing scale. Default: "lg" (24px) — the canonical card-grid gap. */
85
+ gap?: keyof typeof GAP;
86
+ }
87
+
88
+ function colsClasses(cols: Cols | ResponsiveCols): string[] {
89
+ if (typeof cols === "number") return [BASE_COLS[cols]];
90
+ const out: string[] = [BASE_COLS[cols.base ?? 1]];
91
+ if (cols.sm) out.push(SM_COLS[cols.sm]);
92
+ if (cols.md) out.push(MD_COLS[cols.md]);
93
+ if (cols.lg) out.push(LG_COLS[cols.lg]);
94
+ return out;
95
+ }
96
+
97
+ export const SimpleGrid = React.forwardRef<HTMLDivElement, SimpleGridProps>(
98
+ (
99
+ { className, cols = { base: 1, sm: 2, lg: 3 }, gap = "lg", ...props },
100
+ ref
101
+ ) => (
102
+ <div
103
+ ref={ref}
104
+ data-slot="simple-grid"
105
+ className={cn("grid", ...colsClasses(cols), GAP[gap], className)}
106
+ {...props}
107
+ />
108
+ )
109
+ );
110
+ SimpleGrid.displayName = "SimpleGrid";
@@ -14,6 +14,15 @@ type SkeletonProps = React.ComponentProps<"div"> & {
14
14
  * Ignored for other shapes; `<= 1` renders a single text line.
15
15
  */
16
16
  lines?: number
17
+ /**
18
+ * Loading motion. `"pulse"` (default) is the classic opacity pulse,
19
+ * `"wave"` sweeps a highlight left to right (CSS keyed off
20
+ * `data-animation="wave"` in the design-system layer), `false` renders
21
+ * a static block. Peer precedent: MUI `animation="pulse" | "wave" | false`,
22
+ * Mantine `animate`, Ant Design `active`. The base layer's reduced-motion
23
+ * rule stills both animated modes automatically.
24
+ */
25
+ animation?: "pulse" | "wave" | false
17
26
  }
18
27
 
19
28
  const shapeClasses = {
@@ -25,12 +34,31 @@ const shapeClasses = {
25
34
  text: "animate-pulse rounded-md bg-accent h-4 w-full",
26
35
  } as const
27
36
 
37
+ // Same silhouettes minus animate-pulse — used when animation is "wave"
38
+ // (keyframe applied via the data-animation selector in the generated CSS)
39
+ // or false (static block).
40
+ const staticShapeClasses = {
41
+ default: "rounded-md bg-accent",
42
+ circle: "rounded-full bg-accent size-10",
43
+ text: "rounded-md bg-accent h-4 w-full",
44
+ } as const
45
+
28
46
  function Skeleton({
29
47
  className,
30
48
  shape = "default",
31
49
  lines,
50
+ animation = "pulse",
32
51
  ...props
33
52
  }: SkeletonProps) {
53
+ const shapeClass =
54
+ animation === "pulse" ? shapeClasses[shape] : staticShapeClasses[shape]
55
+ // Omitted for the default pulse so a bare <Skeleton /> stays byte-identical
56
+ // to the pre-variant render. The attribute goes on the bg-carrying elements
57
+ // only (never the transparent multi-line wrapper) so the wave gradient
58
+ // can't paint on a bg-less container.
59
+ const dataAnimation =
60
+ animation === "pulse" ? undefined : animation === false ? "none" : "wave"
61
+
34
62
  const lineCount =
35
63
  shape === "text" && typeof lines === "number" && lines >= 2
36
64
  ? Math.floor(lines)
@@ -39,6 +67,7 @@ function Skeleton({
39
67
  if (lineCount) {
40
68
  return (
41
69
  <div
70
+ aria-hidden="true"
42
71
  data-slot="skeleton"
43
72
  data-shape="text"
44
73
  className={cn("flex w-full flex-col gap-2", className)}
@@ -48,7 +77,8 @@ function Skeleton({
48
77
  <div
49
78
  key={i}
50
79
  data-slot="skeleton-line"
51
- className={cn(shapeClasses.text, i === lineCount - 1 && "w-3/5")}
80
+ data-animation={dataAnimation}
81
+ className={cn(shapeClass, i === lineCount - 1 && "w-3/5")}
52
82
  />
53
83
  ))}
54
84
  </div>
@@ -57,14 +87,33 @@ function Skeleton({
57
87
 
58
88
  return (
59
89
  <div
90
+ aria-hidden="true"
60
91
  data-slot="skeleton"
61
92
  // data-shape is omitted for the default shape so a bare <Skeleton />
62
93
  // stays byte-identical to the pre-variant render.
63
94
  data-shape={shape === "default" ? undefined : shape}
64
- className={cn(shapeClasses[shape], className)}
95
+ data-animation={dataAnimation}
96
+ className={cn(shapeClass, className)}
65
97
  {...props}
66
98
  />
67
99
  )
68
100
  }
69
101
 
70
- export { Skeleton }
102
+ type SkeletonRegionProps = React.ComponentProps<"div"> & {
103
+ /** Accessible label announced while content is loading. */
104
+ label?: string
105
+ }
106
+
107
+ function SkeletonRegion({
108
+ label = "Loading…",
109
+ children,
110
+ ...props
111
+ }: SkeletonRegionProps) {
112
+ return (
113
+ <div role="status" aria-label={label} aria-live="polite" {...props}>
114
+ {children}
115
+ </div>
116
+ )
117
+ }
118
+
119
+ export { Skeleton, SkeletonRegion }
@@ -0,0 +1,274 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+
5
+ import { cn } from "../../lib/utils"
6
+
7
+ /* -------------------------------------------------------------------------------------------------
8
+ * Superellipse path math — Figma's corner-smoothing model
9
+ * (public algorithm: https://www.figma.com/blog/desperately-seeking-squircles/).
10
+ * Reimplemented here rather than vendored so BADS owns the source of record.
11
+ *
12
+ * A squircle is a superellipse: the corner is a circular arc whose ends are extended by two Bézier
13
+ * segments that blend the arc tangentially into the straight edges. `smoothing` (0–1) controls how
14
+ * much of the corner is Bézier blend vs pure arc — 0 = an ordinary rounded corner, ~0.6 = the iOS
15
+ * look. The output is a static SVG path fed to `clip-path: path(...)`, which the browser composites
16
+ * like `border-radius` (no per-frame work) and which works identically in every browser.
17
+ * ----------------------------------------------------------------------------------------------- */
18
+
19
+ const toRadians = (deg: number) => (deg * Math.PI) / 180
20
+
21
+ /** Trim float noise so identical sizes produce identical cache keys / paths. */
22
+ const n = (v: number) => Number(v.toFixed(4))
23
+
24
+ const clamp = (v: number, min: number, max: number) => Math.min(max, Math.max(min, v))
25
+
26
+ interface CornerParams {
27
+ a: number
28
+ b: number
29
+ c: number
30
+ d: number
31
+ p: number
32
+ arcSectionLength: number
33
+ radius: number
34
+ }
35
+
36
+ /**
37
+ * Derive the Bézier control offsets (a, b, c, d), the arc chord length, and the corner "reach" p
38
+ * for a single corner. `budget` is the space available along each edge from the corner (normally
39
+ * half the shorter side) — rounding + smoothing are clamped to it so adjacent corners never overlap.
40
+ */
41
+ function getCornerParams(cornerRadius: number, cornerSmoothing: number, budget: number): CornerParams {
42
+ const radius = Math.min(Math.max(0, cornerRadius), budget)
43
+ // Clamp smoothing so (1 + smoothing) * radius still fits the budget — otherwise a large radius
44
+ // with high smoothing would push p past the edge midpoint and self-intersect.
45
+ const maxSmoothing = radius > 0 ? budget / radius - 1 : 0
46
+ const smoothing = clamp(Math.min(cornerSmoothing, maxSmoothing), 0, 1)
47
+ const p = Math.min((1 + smoothing) * radius, budget)
48
+
49
+ const arcMeasure = 90 * (1 - smoothing)
50
+ const arcSectionLength = Math.sin(toRadians(arcMeasure / 2)) * radius * Math.SQRT2
51
+
52
+ const angleAlpha = (90 - arcMeasure) / 2
53
+ const p3ToP4Distance = radius * Math.tan(toRadians(angleAlpha / 2))
54
+
55
+ const angleBeta = 45 * smoothing
56
+ const c = p3ToP4Distance * Math.cos(toRadians(angleBeta))
57
+ const d = c * Math.tan(toRadians(angleBeta))
58
+
59
+ const b = (p - arcSectionLength - c - d) / 3
60
+ const a = 2 * b
61
+
62
+ return { a, b, c, d, p, arcSectionLength, radius }
63
+ }
64
+
65
+ /**
66
+ * Build the full squircle path for a box of `width` × `height` with a uniform `cornerRadius` and
67
+ * `smoothing`, optionally translated by (ox, oy) — the translate is used to draw the inner edge of
68
+ * the optional border. Absolute commands (M, L) carry the offset; the c/a segments are relative.
69
+ */
70
+ function squirclePath(
71
+ width: number,
72
+ height: number,
73
+ cornerRadius: number,
74
+ smoothing: number,
75
+ ox = 0,
76
+ oy = 0,
77
+ ): string {
78
+ const budget = Math.max(0, Math.min(width, height) / 2)
79
+ const { a, b, c, d, p, arcSectionLength, radius } = getCornerParams(cornerRadius, smoothing, budget)
80
+
81
+ // No radius → plain rectangle (still respects the offset for the border's inner path).
82
+ if (radius <= 0) {
83
+ return [
84
+ `M ${n(ox)} ${n(oy)}`,
85
+ `L ${n(ox + width)} ${n(oy)}`,
86
+ `L ${n(ox + width)} ${n(oy + height)}`,
87
+ `L ${n(ox)} ${n(oy + height)}`,
88
+ `Z`,
89
+ ].join(" ")
90
+ }
91
+
92
+ return [
93
+ `M ${n(ox + width - p)} ${n(oy)}`,
94
+ // top-right corner
95
+ `c ${n(a)} 0 ${n(a + b)} 0 ${n(a + b + c)} ${n(d)}`,
96
+ `a ${n(radius)} ${n(radius)} 0 0 1 ${n(arcSectionLength)} ${n(arcSectionLength)}`,
97
+ `c ${n(d)} ${n(c)} ${n(d)} ${n(b + c)} ${n(d)} ${n(a + b + c)}`,
98
+ `L ${n(ox + width)} ${n(oy + height - p)}`,
99
+ // bottom-right corner
100
+ `c 0 ${n(a)} 0 ${n(a + b)} ${n(-d)} ${n(a + b + c)}`,
101
+ `a ${n(radius)} ${n(radius)} 0 0 1 ${n(-arcSectionLength)} ${n(arcSectionLength)}`,
102
+ `c ${n(-c)} ${n(d)} ${n(-(b + c))} ${n(d)} ${n(-(a + b + c))} ${n(d)}`,
103
+ `L ${n(ox + p)} ${n(oy + height)}`,
104
+ // bottom-left corner
105
+ `c ${n(-a)} 0 ${n(-(a + b))} 0 ${n(-(a + b + c))} ${n(-d)}`,
106
+ `a ${n(radius)} ${n(radius)} 0 0 1 ${n(-arcSectionLength)} ${n(-arcSectionLength)}`,
107
+ `c ${n(-d)} ${n(-c)} ${n(-d)} ${n(-(b + c))} ${n(-d)} ${n(-(a + b + c))}`,
108
+ `L ${n(ox)} ${n(oy + p)}`,
109
+ // top-left corner
110
+ `c 0 ${n(-a)} 0 ${n(-(a + b))} ${n(d)} ${n(-(a + b + c))}`,
111
+ `a ${n(radius)} ${n(radius)} 0 0 1 ${n(arcSectionLength)} ${n(-arcSectionLength)}`,
112
+ `c ${n(c)} ${n(-d)} ${n(b + c)} ${n(-d)} ${n(a + b + c)} ${n(-d)}`,
113
+ `Z`,
114
+ ].join(" ")
115
+ }
116
+
117
+ /* -------------------------------------------------------------------------------------------------
118
+ * Token resolution helpers — the primitive reads its defaults off the live CSS custom properties so
119
+ * a Squircle tracks the same `--radius` every `rounded-*` uses (and the Customize-tab radius control).
120
+ * ----------------------------------------------------------------------------------------------- */
121
+
122
+ function cssLengthToPx(raw: string, el: Element): number {
123
+ const value = raw.trim()
124
+ if (!value) return 0
125
+ if (value.endsWith("px")) return parseFloat(value) || 0
126
+ if (value.endsWith("rem")) {
127
+ const rootFontSize =
128
+ parseFloat(getComputedStyle(el.ownerDocument.documentElement).fontSize) || 16
129
+ return (parseFloat(value) || 0) * rootFontSize
130
+ }
131
+ const num = parseFloat(value)
132
+ return Number.isFinite(num) ? num : 0
133
+ }
134
+
135
+ /** Merge a forwarded ref with the internal measuring ref. */
136
+ function useMergedRef<T>(external: React.Ref<T> | undefined) {
137
+ const internal = React.useRef<T | null>(null)
138
+ const callback = React.useCallback(
139
+ (node: T | null) => {
140
+ internal.current = node
141
+ if (typeof external === "function") external(node)
142
+ else if (external) (external as React.MutableRefObject<T | null>).current = node
143
+ },
144
+ [external],
145
+ )
146
+ return [internal, callback] as const
147
+ }
148
+
149
+ /* -------------------------------------------------------------------------------------------------
150
+ * Squircle
151
+ * ----------------------------------------------------------------------------------------------- */
152
+
153
+ type SquircleOwnProps = {
154
+ /**
155
+ * Corner radius in px. Omit to inherit the live `--radius` token (so a Squircle reads at the same
156
+ * corner radius as every `rounded-*` box — only the curve differs). When `radius ≥ min(w,h)/2` the
157
+ * shape becomes a capsule automatically.
158
+ */
159
+ radius?: number
160
+ /**
161
+ * Superellipse smoothing, 0–1. Omit to inherit `--corner-smoothing` (≈0.6, iOS-like). `0` renders
162
+ * pixel-identical to an ordinary rounded corner — the proof that Squircle re-curves the radius
163
+ * scale rather than competing with it.
164
+ */
165
+ smoothing?: number
166
+ /** Polymorphic host element/component. Defaults to `"div"`. Use `as={motion.div}`, `as="a"`, etc. */
167
+ as?: React.ElementType
168
+ /** Optional border that follows the squircle edge (drawn via an even-odd clipped overlay). */
169
+ borderWidth?: number
170
+ /** Border color — a token by default. Only used when `borderWidth > 0`. */
171
+ borderColor?: string
172
+ }
173
+
174
+ export type SquircleProps = SquircleOwnProps &
175
+ Omit<React.HTMLAttributes<HTMLElement>, keyof SquircleOwnProps> & {
176
+ ref?: React.Ref<HTMLElement>
177
+ children?: React.ReactNode
178
+ }
179
+
180
+ function Squircle({
181
+ radius,
182
+ smoothing,
183
+ as,
184
+ borderWidth = 0,
185
+ borderColor = "var(--border)",
186
+ className,
187
+ style,
188
+ children,
189
+ ref,
190
+ ...rest
191
+ }: SquircleProps) {
192
+ const Comp = (as ?? "div") as React.ElementType
193
+ const [measureRef, setRef] = useMergedRef<HTMLElement>(ref)
194
+ const [path, setPath] = React.useState<string | null>(null)
195
+ const [borderClip, setBorderClip] = React.useState<string | null>(null)
196
+
197
+ React.useEffect(() => {
198
+ const el = measureRef.current
199
+ if (!el) return
200
+ // Resolve the correct window from the node — BADS surfaces render inside preview iframes and
201
+ // portals, where the bare global `window`/`ResizeObserver` is the wrong one (build-spec §2).
202
+ const win = el.ownerDocument.defaultView ?? window
203
+
204
+ const compute = () => {
205
+ // borderBoxSize floats keep sub-pixel precision during size transitions; fall back to offset*.
206
+ const width = el.offsetWidth
207
+ const height = el.offsetHeight
208
+ if (width <= 0 || height <= 0) return
209
+
210
+ const styles = win.getComputedStyle(el)
211
+ const resolvedRadius =
212
+ typeof radius === "number"
213
+ ? radius
214
+ : cssLengthToPx(styles.getPropertyValue("--radius"), el)
215
+ const resolvedSmoothing =
216
+ typeof smoothing === "number"
217
+ ? smoothing
218
+ : (() => {
219
+ const raw = parseFloat(styles.getPropertyValue("--corner-smoothing"))
220
+ return Number.isFinite(raw) ? raw : 0.6
221
+ })()
222
+
223
+ const r = Math.max(0, resolvedRadius)
224
+ const s = clamp(resolvedSmoothing, 0, 1)
225
+
226
+ setPath(squirclePath(width, height, r, s))
227
+
228
+ if (borderWidth > 0) {
229
+ const inner = squirclePath(
230
+ Math.max(0, width - borderWidth * 2),
231
+ Math.max(0, height - borderWidth * 2),
232
+ Math.max(0, r - borderWidth),
233
+ s,
234
+ borderWidth,
235
+ borderWidth,
236
+ )
237
+ const outer = squirclePath(width, height, r, s)
238
+ // evenodd: paint only the ring between the outer squircle and the inset inner squircle.
239
+ setBorderClip(`path(evenodd, "${outer} ${inner}")`)
240
+ } else {
241
+ setBorderClip(null)
242
+ }
243
+ }
244
+
245
+ compute()
246
+ const ro = new win.ResizeObserver(compute)
247
+ ro.observe(el)
248
+ return () => ro.disconnect()
249
+ }, [radius, smoothing, borderWidth, measureRef])
250
+
251
+ return (
252
+ <Comp
253
+ ref={setRef}
254
+ data-slot="squircle"
255
+ // `relative` anchors the optional border overlay; `overflow: visible` (default) is required so
256
+ // the clip doesn't fight the border — content needing `overflow: hidden` wraps an inner box.
257
+ className={cn("relative", className)}
258
+ style={path ? { clipPath: `path("${path}")`, ...style } : style}
259
+ {...rest}
260
+ >
261
+ {children}
262
+ {borderWidth > 0 && borderClip ? (
263
+ <span
264
+ aria-hidden="true"
265
+ data-slot="squircle-border"
266
+ className="pointer-events-none absolute inset-0"
267
+ style={{ clipPath: borderClip, backgroundColor: borderColor }}
268
+ />
269
+ ) : null}
270
+ </Comp>
271
+ )
272
+ }
273
+
274
+ export { Squircle }