@behavioral-agentic-design-system/core 0.28.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 (95) hide show
  1. package/package.json +2 -2
  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 +5532 -3044
  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 +74 -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/alert.tsx +12 -0
  17. package/src/components/ui/badge.tsx +19 -0
  18. package/src/components/ui/chat-marker.tsx +120 -0
  19. package/src/components/ui/checkbox.tsx +9 -1
  20. package/src/components/ui/close-button.tsx +71 -0
  21. package/src/components/ui/combobox.tsx +62 -3
  22. package/src/components/ui/container.tsx +65 -0
  23. package/src/components/ui/date-field.tsx +368 -0
  24. package/src/components/ui/drawer.tsx +334 -0
  25. package/src/components/ui/file-button.tsx +145 -0
  26. package/src/components/ui/floating-indicator.tsx +217 -0
  27. package/src/components/ui/format-byte.tsx +113 -0
  28. package/src/components/ui/index.ts +21 -0
  29. package/src/components/ui/input.tsx +38 -3
  30. package/src/components/ui/keyboard-shortcut.tsx +146 -0
  31. package/src/components/ui/loading-dots.tsx +99 -0
  32. package/src/components/ui/month-picker.tsx +296 -0
  33. package/src/components/ui/multi-select.tsx +15 -13
  34. package/src/components/ui/nav-link.tsx +200 -0
  35. package/src/components/ui/navigation-rail.tsx +256 -0
  36. package/src/components/ui/notification.tsx +20 -0
  37. package/src/components/ui/password-input.tsx +34 -1
  38. package/src/components/ui/progress.tsx +15 -1
  39. package/src/components/ui/prose.tsx +62 -0
  40. package/src/components/ui/result.tsx +151 -0
  41. package/src/components/ui/rolling-number.tsx +1 -0
  42. package/src/components/ui/simple-grid.tsx +110 -0
  43. package/src/components/ui/skeleton.tsx +52 -3
  44. package/src/components/ui/squircle.tsx +274 -0
  45. package/src/components/ui/stack.tsx +105 -0
  46. package/src/components/ui/status-badge.tsx +93 -0
  47. package/src/components/ui/tabs.tsx +34 -7
  48. package/src/components/ui/tag.tsx +46 -5
  49. package/src/components/ui/theme-icon.tsx +138 -0
  50. package/src/components/ui/timeline.tsx +27 -10
  51. package/src/components/ui/tooltip.tsx +12 -1
  52. package/src/components/ui/tree-select.tsx +386 -0
  53. package/src/components/ui/year-picker.tsx +307 -0
  54. package/src/data/docs-index.ts +10 -0
  55. package/src/hooks/use-global-primary-color.ts +57 -6
  56. package/src/stories/Alert.stories.tsx +31 -1
  57. package/src/stories/Badge.stories.tsx +63 -6
  58. package/src/stories/ChatMarker.stories.tsx +59 -0
  59. package/src/stories/Checkbox.stories.tsx +5 -0
  60. package/src/stories/CloseButton.stories.tsx +65 -0
  61. package/src/stories/Combobox.stories.tsx +74 -3
  62. package/src/stories/Container.stories.tsx +134 -0
  63. package/src/stories/DateField.stories.tsx +114 -0
  64. package/src/stories/Drawer.stories.tsx +211 -0
  65. package/src/stories/FileButton.stories.tsx +117 -0
  66. package/src/stories/FloatingIndicator.stories.tsx +343 -0
  67. package/src/stories/FormatByte.stories.tsx +142 -0
  68. package/src/stories/Input.stories.tsx +91 -0
  69. package/src/stories/KeyboardShortcut.stories.tsx +87 -0
  70. package/src/stories/LoadingDots.stories.tsx +73 -0
  71. package/src/stories/MonthPicker.stories.tsx +99 -0
  72. package/src/stories/MultiSelect.stories.tsx +3 -1
  73. package/src/stories/NavLink.stories.tsx +213 -0
  74. package/src/stories/NavigationRail.stories.tsx +413 -0
  75. package/src/stories/Notification.stories.tsx +53 -0
  76. package/src/stories/PasswordInput.stories.tsx +21 -0
  77. package/src/stories/Progress.stories.tsx +38 -0
  78. package/src/stories/Prose.stories.tsx +232 -0
  79. package/src/stories/Result.stories.tsx +145 -0
  80. package/src/stories/RollingNumber.stories.tsx +1 -1
  81. package/src/stories/SimpleGrid.stories.tsx +130 -0
  82. package/src/stories/Skeleton.stories.tsx +62 -1
  83. package/src/stories/Squircle.stories.tsx +127 -0
  84. package/src/stories/Stack.stories.tsx +139 -0
  85. package/src/stories/StatusBadge.stories.tsx +125 -0
  86. package/src/stories/Tabs.stories.tsx +56 -1
  87. package/src/stories/Tag.stories.tsx +31 -0
  88. package/src/stories/ThemeIcon.stories.tsx +97 -0
  89. package/src/stories/Timeline.stories.tsx +69 -0
  90. package/src/stories/Tooltip.stories.tsx +18 -0
  91. package/src/stories/TreeSelect.stories.tsx +222 -0
  92. package/src/stories/YearPicker.stories.tsx +100 -0
  93. package/src/styles.css +289 -15
  94. package/src/tokens.json +96 -1
  95. package/LICENSE +0 -21
@@ -0,0 +1,151 @@
1
+ import * as React from "react"
2
+ import { cva, type VariantProps } from "class-variance-authority"
3
+ import { CheckCircle2, XCircle, AlertTriangle, Info } from "lucide-react"
4
+
5
+ import { cn } from "../../lib/utils"
6
+
7
+ // Result — feedback primitive for the outcome of a concluded operation
8
+ // (form submitted, payment confirmed, sync failed, onboarding complete).
9
+ // Distinct from EmptyState (no data yet — nothing happened) and from
10
+ // Sonner/Notification (transient or list-bound feedback): Result owns the
11
+ // surface after the operation ends.
12
+ //
13
+ // Status colors use the `text-[var(--success)]` arbitrary form — the
14
+ // Sonner / Meter / CircularProgress-proven pattern. The theme tokens are raw
15
+ // oklch values, so wrapping them in `hsl(var(--success))` produces invalid
16
+ // CSS that fails silently. `error` maps to the audited `text-destructive`
17
+ // utility. Zero new tokens.
18
+ //
19
+ // Motion (spec §4 pattern c): the icon wrapper enters via tw-animate-css
20
+ // `animate-in fade-in zoom-in-50` with token-driven timing supplied inline
21
+ // (`animationDuration: var(--duration-base)`, `animationTimingFunction:
22
+ // var(--ease-spring)`). No `duration-*` token utility classes — Tailwind v4
23
+ // has no `--duration-*` namespace and those classes compile to nothing.
24
+ // Reduced-motion is handled by the base layer (0.01ms override).
25
+
26
+ const resultVariants = cva("flex flex-col items-center text-center", {
27
+ variants: {
28
+ size: {
29
+ default: "gap-4 px-8 py-12",
30
+ sm: "gap-3 px-6 py-8",
31
+ },
32
+ },
33
+ defaultVariants: {
34
+ size: "default",
35
+ },
36
+ })
37
+
38
+ const resultIconVariants = cva(
39
+ "animate-in fade-in zoom-in-50 [&>svg]:shrink-0",
40
+ {
41
+ variants: {
42
+ status: {
43
+ success: "text-[var(--success)]",
44
+ error: "text-destructive",
45
+ warning: "text-[var(--warning)]",
46
+ info: "text-[var(--info)]",
47
+ },
48
+ size: {
49
+ default: "[&>svg]:size-12",
50
+ sm: "[&>svg]:size-10",
51
+ },
52
+ },
53
+ defaultVariants: {
54
+ size: "default",
55
+ },
56
+ }
57
+ )
58
+
59
+ const DEFAULT_STATUS_ICONS: Record<
60
+ NonNullable<ResultProps["status"]>,
61
+ React.ComponentType<React.SVGProps<SVGSVGElement> & { strokeWidth?: number }>
62
+ > = {
63
+ success: CheckCircle2,
64
+ error: XCircle,
65
+ warning: AlertTriangle,
66
+ info: Info,
67
+ }
68
+
69
+ export interface ResultProps
70
+ extends React.ComponentPropsWithoutRef<"div">,
71
+ VariantProps<typeof resultVariants> {
72
+ /** Semantic outcome — controls the default icon and its color. */
73
+ status: "success" | "error" | "warning" | "info"
74
+ /** Primary outcome statement. */
75
+ title: string
76
+ /** Supporting detail rendered below the title. */
77
+ subtitle?: string
78
+ /**
79
+ * Custom icon or illustration — replaces the default status icon when
80
+ * provided. The wrapper still carries the status color, so a custom SVG
81
+ * using `currentColor` inherits it.
82
+ */
83
+ icon?: React.ReactNode
84
+ /** Action row below title + subtitle — Buttons, links, extra detail. */
85
+ extra?: React.ReactNode
86
+ }
87
+
88
+ function Result({
89
+ className,
90
+ status,
91
+ size,
92
+ title,
93
+ subtitle,
94
+ icon,
95
+ extra,
96
+ ...props
97
+ }: ResultProps) {
98
+ const DefaultIcon = DEFAULT_STATUS_ICONS[status]
99
+ return (
100
+ <div
101
+ data-slot="result"
102
+ data-status={status}
103
+ // Outcome surfaces announce politely; errors announce assertively.
104
+ // Overridable — the spread below wins. Note: live regions only fire
105
+ // reliably when the Result is injected into an already-rendered
106
+ // container; a fresh-route render should not rely on the announcement.
107
+ role={status === "error" ? "alert" : "status"}
108
+ className={cn(resultVariants({ size }), className)}
109
+ {...props}
110
+ >
111
+ <div
112
+ data-slot="result-icon"
113
+ aria-hidden="true"
114
+ className={resultIconVariants({ status, size })}
115
+ style={{
116
+ animationDuration: "var(--duration-base)",
117
+ animationTimingFunction: "var(--ease-spring)",
118
+ }}
119
+ >
120
+ {icon ?? <DefaultIcon strokeWidth={1.5} />}
121
+ </div>
122
+ <div
123
+ data-slot="result-title"
124
+ className={cn(
125
+ "font-semibold tracking-tight text-foreground",
126
+ size === "sm" ? "text-lg" : "text-2xl"
127
+ )}
128
+ >
129
+ {title}
130
+ </div>
131
+ {subtitle && (
132
+ <p
133
+ data-slot="result-subtitle"
134
+ className="max-w-md text-sm leading-relaxed text-muted-foreground"
135
+ >
136
+ {subtitle}
137
+ </p>
138
+ )}
139
+ {extra && (
140
+ <div
141
+ data-slot="result-extra"
142
+ className="flex flex-wrap items-center justify-center gap-2 pt-2"
143
+ >
144
+ {extra}
145
+ </div>
146
+ )}
147
+ </div>
148
+ )
149
+ }
150
+
151
+ export { Result, resultVariants }
@@ -164,6 +164,7 @@ export function RollingNumber({
164
164
  return (
165
165
  <span
166
166
  data-slot="rolling-number"
167
+ role="status"
167
168
  aria-label={label}
168
169
  aria-live="polite"
169
170
  className={cn(
@@ -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 }