@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,140 @@
1
+ import * as React from "react"
2
+ import { cva, type VariantProps } from "class-variance-authority"
3
+
4
+ import { cn } from "../../lib/utils"
5
+
6
+ // Pill — compact, non-removable, read-only label.
7
+ //
8
+ // The fourth member of the label family, and the only one with no behavior
9
+ // baked into its API:
10
+ // - Tag → passive label WITH dismiss DNA (onClose) + semantic status
11
+ // variants; takes its text via `label`.
12
+ // - Badge → status/count semantics (primary fill by default,
13
+ // success/warning/info/destructive) and a focus ring for the
14
+ // `asChild` anchor case.
15
+ // - Chip → interactive filter toggle (native button, role=checkbox).
16
+ // - Pill → this. A neutral label for metadata that is neither a status
17
+ // nor an action and can never be removed in place: taxonomy
18
+ // terms, owner names, environment names, counts in a header.
19
+ //
20
+ // Peer parity: Mantine `Pill` (plain span, no role, `disabled` dims only) and
21
+ // Chakra `Tag` without its close trigger. Like both, Pill renders a plain
22
+ // <span> with no ARIA role: a label with no interaction needs none, and a
23
+ // screen reader reads it as inline text in sequence with its neighbours.
24
+ //
25
+ // Motion is pattern (c): `transition-colors` for the property list + inline
26
+ // var(--duration-fast) / var(--ease-out). Pill has no hover state of its own
27
+ // (it is not interactive), so the transition only fires when a consumer
28
+ // re-themes it (variant swap, theme toggle) — but the token-driven duration
29
+ // is still what keeps that repaint consistent with Tag and Badge.
30
+
31
+ const pillVariants = cva(
32
+ [
33
+ // Long-label overflow contract (CLAUDE.md → "Long-label overflow"): the
34
+ // span is the flex parent (max-w-full min-w-0 overflow-hidden); the inner
35
+ // label span truncates. Pills routinely hold runtime strings — user names,
36
+ // slugs, taxonomy terms — that have no word boundaries to wrap at.
37
+ "inline-flex max-w-full min-w-0 shrink-0 items-center overflow-hidden rounded-full border font-medium whitespace-nowrap select-none",
38
+ "transition-colors",
39
+ "data-[disabled]:opacity-50",
40
+ "[&_svg]:pointer-events-none [&_svg]:shrink-0",
41
+ ],
42
+ {
43
+ variants: {
44
+ variant: {
45
+ default: "border-transparent bg-secondary text-secondary-foreground",
46
+ outline: "border-border bg-transparent text-foreground",
47
+ muted: "border-transparent bg-muted text-muted-foreground",
48
+ },
49
+ /**
50
+ * Height ladder. sm is the default (Mantine's default register —
51
+ * dense metadata rows, card footers); md matches Tag md / Badge lg for
52
+ * body-copy rows; lg is for header and hero metadata.
53
+ * BADS text-xs = 14px and text-sm = 16px — never below 14px (AAA floor).
54
+ */
55
+ size: {
56
+ sm: "gap-1 px-2 py-0.5 text-xs [&_svg]:size-3",
57
+ md: "gap-1 px-2.5 py-0.5 text-sm [&_svg]:size-3.5",
58
+ lg: "gap-1.5 px-3 py-1 text-sm [&_svg]:size-4",
59
+ },
60
+ },
61
+ defaultVariants: {
62
+ variant: "default",
63
+ size: "sm",
64
+ },
65
+ }
66
+ )
67
+
68
+ type PillProps = Omit<React.ComponentProps<"span">, "children"> &
69
+ VariantProps<typeof pillVariants> & {
70
+ /**
71
+ * Optional leading element — a Lucide icon (strokeWidth 1.5), a custom
72
+ * SVG, or a small Avatar (`size="xs"`). SVGs are sized per `size`;
73
+ * anything else keeps its own dimensions.
74
+ */
75
+ icon?: React.ReactNode
76
+ /**
77
+ * Presentational dimming. Pill has no interactive state to disable —
78
+ * this mirrors Mantine's `disabled` and exists so a pill inside a
79
+ * disabled control (a disabled fieldset's selected values, an archived
80
+ * row) dims with it. Sets `data-disabled` only: the owning control is
81
+ * responsible for conveying the disabled state to assistive tech.
82
+ */
83
+ disabled?: boolean
84
+ /** Visible label text. Keep it to a few words — Pill truncates, it never wraps. */
85
+ children: React.ReactNode
86
+ }
87
+
88
+ function Pill({
89
+ className,
90
+ variant,
91
+ size,
92
+ icon,
93
+ disabled,
94
+ style,
95
+ children,
96
+ ...props
97
+ }: PillProps) {
98
+ return (
99
+ <span
100
+ data-slot="pill"
101
+ data-variant={variant ?? "default"}
102
+ data-size={size ?? "sm"}
103
+ data-disabled={disabled ? "" : undefined}
104
+ className={cn(pillVariants({ variant, size }), className)}
105
+ style={{
106
+ transitionDuration: "var(--duration-fast)",
107
+ transitionTimingFunction: "var(--ease-out)",
108
+ ...style,
109
+ }}
110
+ {...props}
111
+ >
112
+ {icon != null && (
113
+ <span aria-hidden="true" className="flex shrink-0 items-center [&>svg]:stroke-[1.5]">
114
+ {icon}
115
+ </span>
116
+ )}
117
+ <span className="min-w-0 truncate">{children}</span>
118
+ </span>
119
+ )
120
+ }
121
+
122
+ type PillGroupProps = React.ComponentProps<"div">
123
+
124
+ /**
125
+ * Wrapping flex row for a set of Pills. Plain <div> — a row of labels is
126
+ * inline text, not a list widget. Pass `aria-label` or `role="list"` only
127
+ * when the group itself is a navigable landmark in the consuming surface.
128
+ */
129
+ function PillGroup({ className, ...props }: PillGroupProps) {
130
+ return (
131
+ <div
132
+ data-slot="pill-group"
133
+ className={cn("flex flex-wrap items-center gap-1.5", className)}
134
+ {...props}
135
+ />
136
+ )
137
+ }
138
+
139
+ export { Pill, PillGroup, pillVariants }
140
+ export type { PillProps, PillGroupProps }
@@ -21,9 +21,23 @@ function PopoverTrigger({
21
21
  function PopoverContent({
22
22
  className,
23
23
  align = "center",
24
- sideOffset = 4,
24
+ sideOffset,
25
+ showArrow = false,
26
+ children,
25
27
  ...props
26
- }: React.ComponentProps<typeof PopoverPrimitive.Content>) {
28
+ }: React.ComponentProps<typeof PopoverPrimitive.Content> & {
29
+ /**
30
+ * Renders a directional arrow caret pointing at the trigger. Matches the
31
+ * popover border + background so it reads as an extension of the panel.
32
+ * Peer parity: Mantine Popover arrow, Ant Design Popover arrow, MUI Popper
33
+ * arrow, Chakra UI Popover arrow. Defaults to false (existing behaviour
34
+ * unchanged — byte-identical for consumers that don't set this prop).
35
+ */
36
+ showArrow?: boolean
37
+ }) {
38
+ // When showArrow is true, add extra sideOffset to accommodate the arrow height
39
+ // so the panel doesn't overlap the trigger element.
40
+ const resolvedSideOffset = sideOffset ?? (showArrow ? 8 : 4)
27
41
  // See use-portal-theme-class.ts: lets a PortalThemeProvider scope class
28
42
  // (e.g. "atrium-theme") apply to portal content so theme-scoped CSS
29
43
  // variables resolve inside the portal.
@@ -33,14 +47,23 @@ function PopoverContent({
33
47
  <PopoverPrimitive.Content
34
48
  data-slot="popover-content"
35
49
  align={align}
36
- sideOffset={sideOffset}
50
+ sideOffset={resolvedSideOffset}
37
51
  className={cn(
38
52
  "z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-hidden data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
39
53
  portalThemeClass,
40
54
  className
41
55
  )}
42
56
  {...props}
43
- />
57
+ >
58
+ {children}
59
+ {showArrow && (
60
+ <PopoverPrimitive.Arrow
61
+ width={11}
62
+ height={5.5}
63
+ className="fill-popover [filter:drop-shadow(0_1.5px_0_var(--border))]"
64
+ />
65
+ )}
66
+ </PopoverPrimitive.Content>
44
67
  </PopoverPrimitive.Portal>
45
68
  )
46
69
  }
@@ -0,0 +1,111 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import { createPortal } from "react-dom"
5
+
6
+ import { cn } from "../../lib/utils"
7
+ import { usePortalThemeClass } from "../../hooks/use-portal-theme-class"
8
+
9
+ /**
10
+ * Portal — render children into a different DOM container (by default the
11
+ * `<body>` of the component's own document) while keeping them in the React
12
+ * tree, so context, events, and state all still flow from the parent.
13
+ *
14
+ * Peer parity: Radix Portal, Chakra UI Portal, Mantine Portal, Ark UI Portal,
15
+ * MUI Portal. Zero dependencies beyond react-dom's `createPortal`.
16
+ *
17
+ * Why not just call createPortal?
18
+ * --------------------------------
19
+ * A raw portal lands OUTSIDE any theme/brand class a consumer applied to a
20
+ * page wrapper, so theme-scoped custom properties (`--shell-chrome-bg-rgb`,
21
+ * `--brand-*`) go invalid at computed-value time inside it and the surface
22
+ * renders unthemed — the failure documented in hooks/use-portal-theme-class
23
+ * and CLAUDE.md → "Portal components and CSS scope". Every BADS-shipped Radix
24
+ * portal merges `usePortalThemeClass()` onto its content for exactly this
25
+ * reason; this primitive does the same for arbitrary content, so a fork's
26
+ * own floating bar or toast gets the scope for free.
27
+ *
28
+ * The portal root is a `<div class="contents">`: it stays in the DOM tree
29
+ * (so the scope class's custom properties inherit into the children) but
30
+ * generates no box, so it never affects the layout of what it wraps. A plain
31
+ * div carries no semantics, so the historical `display: contents` a11y bug
32
+ * (dropped semantics on buttons/lists) does not apply.
33
+ *
34
+ * Cross-window safety
35
+ * -------------------
36
+ * The default container is read from an inline hidden anchor's
37
+ * `ownerDocument`, never the bare `document` global — a component inside an
38
+ * iframe (the BADS preview tabs) or another window portals into ITS body,
39
+ * not the top-level one (spec §2). Pass `container` to target any element.
40
+ *
41
+ * SSR: the anchor renders on the server; the portal mounts after hydration
42
+ * (same mount gate Radix uses).
43
+ */
44
+
45
+ const useIsoLayoutEffect =
46
+ typeof window !== "undefined" ? React.useLayoutEffect : React.useEffect
47
+
48
+ interface PortalProps extends React.ComponentPropsWithoutRef<"div"> {
49
+ /**
50
+ * Element to render into. Defaults to the `<body>` of the component's own
51
+ * document. `null` is treated as "not ready" and renders nothing until a
52
+ * container resolves — handy with a ref that populates after mount.
53
+ */
54
+ container?: Element | null
55
+ /** When true, children render in place (no portal). Useful for tests,
56
+ * print stylesheets, or when an ancestor already portals. */
57
+ disabled?: boolean
58
+ }
59
+
60
+ function Portal({
61
+ container,
62
+ disabled = false,
63
+ className,
64
+ children,
65
+ ...props
66
+ }: PortalProps) {
67
+ const anchorRef = React.useRef<HTMLSpanElement | null>(null)
68
+ const [ownBody, setOwnBody] = React.useState<Element | null>(null)
69
+ const portalThemeClass = usePortalThemeClass()
70
+
71
+ useIsoLayoutEffect(() => {
72
+ setOwnBody(anchorRef.current?.ownerDocument.body ?? null)
73
+ }, [])
74
+
75
+ if (disabled) {
76
+ return (
77
+ <div
78
+ data-slot="portal"
79
+ data-disabled="true"
80
+ className={cn("contents", className)}
81
+ {...props}
82
+ >
83
+ {children}
84
+ </div>
85
+ )
86
+ }
87
+
88
+ // `container === undefined` means "use my own body"; `null` means "wait".
89
+ const target = container === undefined ? ownBody : container
90
+
91
+ return (
92
+ <>
93
+ <span ref={anchorRef} data-slot="portal-anchor" hidden aria-hidden="true" />
94
+ {target
95
+ ? createPortal(
96
+ <div
97
+ data-slot="portal"
98
+ className={cn("contents", portalThemeClass, className)}
99
+ {...props}
100
+ >
101
+ {children}
102
+ </div>,
103
+ target
104
+ )
105
+ : null}
106
+ </>
107
+ )
108
+ }
109
+
110
+ export { Portal }
111
+ export type { PortalProps }
@@ -0,0 +1,172 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import { Slot } from "@radix-ui/react-slot"
5
+
6
+ import { cn } from "../../lib/utils"
7
+
8
+ /**
9
+ * Presence — mount/unmount wrapper with a token-driven enter *and exit*
10
+ * animation. `present={true}` mounts the child and plays the enter keyframe;
11
+ * `present={false}` plays the exit keyframe and only THEN unmounts (or hides)
12
+ * the child. Conditional rendering (`{open && <X />}`) can never animate out
13
+ * because the node is gone before the browser paints a frame — that exit
14
+ * frame is the whole reason this primitive exists.
15
+ *
16
+ * Peer parity: Ark UI Presence, Chakra UI v3 Presence, Mantine Transition,
17
+ * MUI Fade / Grow / Slide / Zoom, Radix's internal Presence.
18
+ *
19
+ * How the exit wait works
20
+ * -----------------------
21
+ * On `present=false` the wrapper flips to `data-state="closed"`, which the
22
+ * design-system CSS (keyed off `[data-slot="presence"][data-transition=…]
23
+ * [data-state=…]` in build-tokens.cjs — spec §4 pattern b) maps to the
24
+ * matching `presence-<transition>-out` keyframe. The effect then reads
25
+ * `element.getAnimations()`: zero running animations → unmount immediately
26
+ * (a consumer overrode `animation: none`, or the browser lacks the API);
27
+ * otherwise wait for every `finished` promise. A monotonically increasing
28
+ * token guards the wait, so a `present=true` that arrives mid-exit cancels
29
+ * the pending unmount and the enter keyframe simply replays.
30
+ *
31
+ * `animation-fill-mode: both` on the CSS side is load-bearing — without it
32
+ * the exit keyframe snaps back to its start frame (fully visible) for the
33
+ * one frame between `animationend` and React's commit.
34
+ *
35
+ * Reduced motion: the base layer forces `animation-duration: 0.01ms`, the
36
+ * `finished` promise still resolves, and the child unmounts effectively
37
+ * immediately. No per-component guard needed.
38
+ */
39
+
40
+ const PRESENCE_TRANSITIONS = [
41
+ "fade",
42
+ "scale",
43
+ "slide-up",
44
+ "slide-down",
45
+ "slide-left",
46
+ "slide-right",
47
+ ] as const
48
+
49
+ type PresenceTransition = (typeof PRESENCE_TRANSITIONS)[number]
50
+
51
+ type Phase = "mounted" | "exiting" | "unmounted"
52
+
53
+ interface PresenceProps extends React.ComponentPropsWithoutRef<"div"> {
54
+ /** Whether the child should be shown. Flipping to false plays the exit
55
+ * animation before the child leaves the DOM. */
56
+ present: boolean
57
+ /**
58
+ * Which enter/exit keyframe pair to play. Written to `data-transition`;
59
+ * the keyframes live in the generated styles.css. Default: fade.
60
+ */
61
+ transition?: PresenceTransition
62
+ /**
63
+ * When true (default) the child is removed from the DOM after the exit
64
+ * animation. When false it stays mounted with the `hidden` attribute —
65
+ * useful for expensive subtrees (iframes, charts) that should keep their
66
+ * state between shows.
67
+ */
68
+ unmountOnExit?: boolean
69
+ /**
70
+ * When true, renders as the single child element instead of a wrapper div —
71
+ * `data-slot`, `data-state`, `data-transition`, and `hidden` are merged
72
+ * onto the child (via Radix Slot). The child must forward its ref and must
73
+ * not set its own `animation` shorthand, which would override the keyframe.
74
+ */
75
+ asChild?: boolean
76
+ }
77
+
78
+ const useIsoLayoutEffect =
79
+ typeof window !== "undefined" ? React.useLayoutEffect : React.useEffect
80
+
81
+ const Presence = React.forwardRef<HTMLDivElement, PresenceProps>(
82
+ (
83
+ {
84
+ present,
85
+ transition = "fade",
86
+ unmountOnExit = true,
87
+ asChild = false,
88
+ className,
89
+ children,
90
+ ...props
91
+ },
92
+ forwardedRef
93
+ ) => {
94
+ const nodeRef = React.useRef<HTMLDivElement | null>(null)
95
+ const [phase, setPhase] = React.useState<Phase>(
96
+ present ? "mounted" : "unmounted"
97
+ )
98
+ // Bumped on every present flip; a pending exit wait only commits its
99
+ // unmount if the token it captured is still current.
100
+ const tokenRef = React.useRef(0)
101
+
102
+ const setRefs = React.useCallback(
103
+ (node: HTMLDivElement | null) => {
104
+ nodeRef.current = node
105
+ if (typeof forwardedRef === "function") forwardedRef(node)
106
+ else if (forwardedRef) forwardedRef.current = node
107
+ },
108
+ [forwardedRef]
109
+ )
110
+
111
+ // Layout effect so the data-state flip lands before the browser paints
112
+ // the frame in which the exit keyframe must already be running.
113
+ useIsoLayoutEffect(() => {
114
+ tokenRef.current += 1
115
+ if (present) {
116
+ setPhase("mounted")
117
+ } else {
118
+ setPhase((p) => (p === "unmounted" ? p : "exiting"))
119
+ }
120
+ }, [present])
121
+
122
+ React.useEffect(() => {
123
+ if (phase !== "exiting") return
124
+ const token = tokenRef.current
125
+ const finish = () => {
126
+ if (tokenRef.current === token) setPhase("unmounted")
127
+ }
128
+ const el = nodeRef.current
129
+ if (!el || typeof el.getAnimations !== "function") {
130
+ finish()
131
+ return
132
+ }
133
+ const animations = el.getAnimations()
134
+ if (animations.length === 0) {
135
+ finish()
136
+ return
137
+ }
138
+ let cancelled = false
139
+ Promise.allSettled(animations.map((a) => a.finished)).then(() => {
140
+ if (!cancelled) finish()
141
+ })
142
+ return () => {
143
+ cancelled = true
144
+ }
145
+ }, [phase])
146
+
147
+ const isOpen = phase === "mounted"
148
+ const isGone = phase === "unmounted"
149
+
150
+ if (isGone && unmountOnExit) return null
151
+
152
+ const Comp = asChild ? Slot : "div"
153
+
154
+ return (
155
+ <Comp
156
+ ref={setRefs}
157
+ data-slot="presence"
158
+ data-state={isOpen ? "open" : "closed"}
159
+ data-transition={transition}
160
+ hidden={isGone || undefined}
161
+ className={cn(className)}
162
+ {...props}
163
+ >
164
+ {children}
165
+ </Comp>
166
+ )
167
+ }
168
+ )
169
+ Presence.displayName = "Presence"
170
+
171
+ export { Presence, PRESENCE_TRANSITIONS }
172
+ export type { PresenceProps, PresenceTransition }