@behavioral-agentic-design-system/core 0.24.0 → 0.26.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 (131) hide show
  1. package/package.json +5 -2
  2. package/scripts/build-tokens.cjs +79 -5
  3. package/src/app/preview/components/page.tsx +4474 -208
  4. package/src/app/shell.tsx +18 -6
  5. package/src/components/customize/brand-mark-section.tsx +1 -1
  6. package/src/components/customize-tab.tsx +2 -2
  7. package/src/components/home-tab.tsx +2 -2
  8. package/src/components/ui/action-bar.tsx +142 -0
  9. package/src/components/ui/affix.tsx +109 -0
  10. package/src/components/ui/alert.tsx +37 -3
  11. package/src/components/ui/anchor.tsx +136 -0
  12. package/src/components/ui/angle-slider.tsx +265 -0
  13. package/src/components/ui/autocomplete.tsx +223 -0
  14. package/src/components/ui/avatar.tsx +8 -2
  15. package/src/components/ui/blockquote.tsx +112 -0
  16. package/src/components/ui/bottom-navigation.tsx +144 -0
  17. package/src/components/ui/burger.tsx +117 -0
  18. package/src/components/ui/button.tsx +101 -3
  19. package/src/components/ui/calendar.tsx +1 -1
  20. package/src/components/ui/card.tsx +43 -5
  21. package/src/components/ui/carousel.tsx +10 -5
  22. package/src/components/ui/cascader.tsx +253 -0
  23. package/src/components/ui/checkbox-card.tsx +176 -0
  24. package/src/components/ui/checkbox-group.tsx +231 -0
  25. package/src/components/ui/checkbox.tsx +14 -3
  26. package/src/components/ui/chip.tsx +143 -0
  27. package/src/components/ui/circular-progress.tsx +2 -2
  28. package/src/components/ui/color-swatch.tsx +73 -0
  29. package/src/components/ui/copy-button.tsx +21 -4
  30. package/src/components/ui/date-picker.tsx +6 -3
  31. package/src/components/ui/date-range-picker.tsx +6 -3
  32. package/src/components/ui/float-label.tsx +114 -0
  33. package/src/components/ui/floating-panel.tsx +129 -0
  34. package/src/components/ui/format-number.tsx +122 -0
  35. package/src/components/ui/highlight.tsx +85 -0
  36. package/src/components/ui/image.tsx +195 -0
  37. package/src/components/ui/index.ts +50 -0
  38. package/src/components/ui/indicator.tsx +2 -2
  39. package/src/components/ui/input.tsx +48 -4
  40. package/src/components/ui/kbd.tsx +1 -1
  41. package/src/components/ui/link.tsx +158 -0
  42. package/src/components/ui/listbox.tsx +426 -0
  43. package/src/components/ui/loading-overlay.tsx +80 -0
  44. package/src/components/ui/marquee.tsx +193 -0
  45. package/src/components/ui/masonry.tsx +164 -0
  46. package/src/components/ui/meter.tsx +186 -0
  47. package/src/components/ui/motion-toggle.tsx +170 -0
  48. package/src/components/ui/notification.tsx +175 -0
  49. package/src/components/ui/overlay.tsx +63 -0
  50. package/src/components/ui/progress.tsx +95 -4
  51. package/src/components/ui/rating-group.tsx +1 -0
  52. package/src/components/ui/separator.tsx +57 -1
  53. package/src/components/ui/sidebar.tsx +1 -1
  54. package/src/components/ui/signature-pad.tsx +381 -0
  55. package/src/components/ui/skeleton.tsx +59 -2
  56. package/src/components/ui/skip-link.tsx +117 -0
  57. package/src/components/ui/slider.tsx +86 -1
  58. package/src/components/ui/spoiler.tsx +131 -0
  59. package/src/components/ui/tabs.tsx +1 -1
  60. package/src/components/ui/text.tsx +135 -0
  61. package/src/components/ui/textarea.tsx +66 -2
  62. package/src/components/ui/timeline.tsx +71 -14
  63. package/src/components/ui/timer.tsx +183 -0
  64. package/src/components/ui/tour.tsx +332 -0
  65. package/src/components/ui/transfer-list.tsx +308 -0
  66. package/src/components/ui/visually-hidden.tsx +42 -0
  67. package/src/components/ui/watermark.tsx +0 -0
  68. package/src/data/docs-index.ts +9 -2
  69. package/src/stories/ActionBar.stories.tsx +201 -0
  70. package/src/stories/Affix.stories.tsx +165 -0
  71. package/src/stories/Alert.stories.tsx +58 -0
  72. package/src/stories/Anchor.stories.tsx +236 -0
  73. package/src/stories/AngleSlider.stories.tsx +128 -0
  74. package/src/stories/Autocomplete.stories.tsx +216 -0
  75. package/src/stories/Avatar.stories.tsx +73 -1
  76. package/src/stories/Blockquote.stories.tsx +148 -0
  77. package/src/stories/BottomNavigation.stories.tsx +195 -0
  78. package/src/stories/Burger.stories.tsx +79 -0
  79. package/src/stories/Button.stories.tsx +103 -2
  80. package/src/stories/Calendar.stories.tsx +4 -0
  81. package/src/stories/Card.stories.tsx +30 -0
  82. package/src/stories/Carousel.stories.tsx +2 -1
  83. package/src/stories/Cascader.stories.tsx +285 -0
  84. package/src/stories/Checkbox.stories.tsx +13 -0
  85. package/src/stories/CheckboxCard.stories.tsx +210 -0
  86. package/src/stories/CheckboxGroup.stories.tsx +186 -0
  87. package/src/stories/Chip.stories.tsx +173 -0
  88. package/src/stories/CircularProgress.stories.tsx +3 -0
  89. package/src/stories/ColorSwatch.stories.tsx +81 -0
  90. package/src/stories/CopyButton.stories.tsx +3 -3
  91. package/src/stories/DatePicker.stories.tsx +3 -0
  92. package/src/stories/DateRangePicker.stories.tsx +3 -0
  93. package/src/stories/Editable.stories.tsx +14 -0
  94. package/src/stories/FloatLabel.stories.tsx +148 -0
  95. package/src/stories/FloatingPanel.stories.tsx +176 -0
  96. package/src/stories/FormatNumber.stories.tsx +308 -0
  97. package/src/stories/Highlight.stories.tsx +140 -0
  98. package/src/stories/Image.stories.tsx +141 -0
  99. package/src/stories/Indicator.stories.tsx +3 -0
  100. package/src/stories/Input.stories.tsx +33 -0
  101. package/src/stories/Kbd.stories.tsx +3 -0
  102. package/src/stories/Link.stories.tsx +198 -0
  103. package/src/stories/Listbox.stories.tsx +240 -0
  104. package/src/stories/LoadingOverlay.stories.tsx +148 -0
  105. package/src/stories/Marquee.stories.tsx +170 -0
  106. package/src/stories/Masonry.stories.tsx +227 -0
  107. package/src/stories/Meter.stories.tsx +143 -0
  108. package/src/stories/MotionToggle.stories.tsx +85 -0
  109. package/src/stories/Notification.stories.tsx +264 -0
  110. package/src/stories/Overlay.stories.tsx +169 -0
  111. package/src/stories/PasswordInput.stories.tsx +4 -0
  112. package/src/stories/Progress.stories.tsx +70 -27
  113. package/src/stories/RatingGroup.stories.tsx +5 -0
  114. package/src/stories/Separator.stories.tsx +41 -5
  115. package/src/stories/Sidebar.stories.tsx +2 -1
  116. package/src/stories/SignaturePad.stories.tsx +112 -0
  117. package/src/stories/Skeleton.stories.tsx +23 -4
  118. package/src/stories/SkipLink.stories.tsx +137 -0
  119. package/src/stories/Slider.stories.tsx +28 -0
  120. package/src/stories/Spoiler.stories.tsx +122 -0
  121. package/src/stories/Tabs.stories.tsx +2 -1
  122. package/src/stories/Text.stories.tsx +191 -0
  123. package/src/stories/Textarea.stories.tsx +58 -6
  124. package/src/stories/Timeline.stories.tsx +82 -0
  125. package/src/stories/Timer.stories.tsx +160 -0
  126. package/src/stories/Tour.stories.tsx +191 -0
  127. package/src/stories/TransferList.stories.tsx +169 -0
  128. package/src/stories/VisuallyHidden.stories.tsx +105 -0
  129. package/src/stories/Watermark.stories.tsx +212 -0
  130. package/src/styles.css +80 -6
  131. package/src/tokens.json +2 -2
@@ -9,6 +9,16 @@ import { cn } from "../../lib/utils";
9
9
 
10
10
  export type TimelineStatus = "default" | "complete" | "active" | "pending";
11
11
 
12
+ export type TimelineOrientation = "vertical" | "alternate";
13
+
14
+ /**
15
+ * Orientation flows from the Timeline root to each TimelineItem via context so
16
+ * the item API stays unchanged. Defaults to "vertical" — an item rendered
17
+ * outside a Timeline behaves exactly as before.
18
+ */
19
+ const TimelineOrientationContext =
20
+ React.createContext<TimelineOrientation>("vertical");
21
+
12
22
  // ─── Variants ─────────────────────────────────────────────────────────────────
13
23
 
14
24
  const dotVariants = cva(
@@ -31,17 +41,40 @@ const dotVariants = cva(
31
41
 
32
42
  // ─── Root ─────────────────────────────────────────────────────────────────────
33
43
 
34
- export interface TimelineProps extends React.HTMLAttributes<HTMLOListElement> {}
44
+ export interface TimelineProps extends React.HTMLAttributes<HTMLOListElement> {
45
+ /**
46
+ * Layout orientation.
47
+ *
48
+ * - `"vertical"` (default) — the classic left-rail layout: dots on the left,
49
+ * one content column. Unchanged from previous releases.
50
+ * - `"alternate"` — a centered vertical spine with consecutive items
51
+ * alternating left/right of it (cf. MUI `position="alternate"`, Ant Design
52
+ * `mode="alternate"`). Applies at the `md` breakpoint and up; on narrower
53
+ * viewports it gracefully falls back to the vertical layout, since
54
+ * alternating columns don't fit. Alternation is CSS-only — the `<ol>`/`<li>`
55
+ * DOM and reading order stay top-to-bottom for screen readers and keyboard
56
+ * users regardless of orientation.
57
+ */
58
+ orientation?: TimelineOrientation;
59
+ }
35
60
 
36
- export function Timeline({ className, children, ...props }: TimelineProps) {
61
+ export function Timeline({
62
+ className,
63
+ children,
64
+ orientation = "vertical",
65
+ ...props
66
+ }: TimelineProps) {
37
67
  return (
38
- <ol
39
- data-slot="timeline"
40
- className={cn("relative space-y-0", className)}
41
- {...props}
42
- >
43
- {children}
44
- </ol>
68
+ <TimelineOrientationContext.Provider value={orientation}>
69
+ <ol
70
+ data-slot="timeline"
71
+ data-orientation={orientation === "alternate" ? "alternate" : undefined}
72
+ className={cn("relative space-y-0", className)}
73
+ {...props}
74
+ >
75
+ {children}
76
+ </ol>
77
+ </TimelineOrientationContext.Provider>
45
78
  );
46
79
  }
47
80
 
@@ -88,11 +121,23 @@ export function TimelineItem({
88
121
  ? <CheckIcon className="size-3" strokeWidth={1.5} aria-hidden />
89
122
  : null;
90
123
 
124
+ // "alternate" repositions dot/connector onto a centered spine and flips the
125
+ // content column per :nth-child odd/even — CSS-only, gated on md:+ so narrow
126
+ // viewports keep the vertical layout. When "vertical" (the default), every
127
+ // conditional below is false and the rendered output is identical to
128
+ // previous releases.
129
+ const orientation = React.useContext(TimelineOrientationContext);
130
+ const alternate = orientation === "alternate";
131
+
91
132
  return (
92
133
  <li
93
134
  data-slot="timeline-item"
94
135
  data-status={status}
95
- className={cn("group relative pb-6 pl-8 last:pb-0", className)}
136
+ className={cn(
137
+ "group relative pb-6 pl-8 last:pb-0",
138
+ alternate && "md:pl-0",
139
+ className
140
+ )}
96
141
  {...props}
97
142
  >
98
143
  {/* Connector line: runs from below the dot to the bottom of the item.
@@ -103,7 +148,8 @@ export function TimelineItem({
103
148
  className={cn(
104
149
  "absolute left-[9px] top-5 bottom-0 w-px",
105
150
  "group-last:hidden",
106
- status === "pending" ? "bg-border/30" : "bg-border"
151
+ status === "pending" ? "bg-border/30" : "bg-border",
152
+ alternate && "md:left-1/2 md:-translate-x-1/2"
107
153
  )}
108
154
  style={{
109
155
  transitionProperty: "background-color",
@@ -116,7 +162,10 @@ export function TimelineItem({
116
162
  <span
117
163
  aria-hidden
118
164
  data-slot="timeline-dot"
119
- className={cn(dotVariants({ status }))}
165
+ className={cn(
166
+ dotVariants({ status }),
167
+ alternate && "md:left-1/2 md:-translate-x-1/2"
168
+ )}
120
169
  style={{
121
170
  transitionProperty: "background-color, border-color",
122
171
  transitionDuration: "var(--duration-fast)",
@@ -126,8 +175,16 @@ export function TimelineItem({
126
175
  {resolvedIcon}
127
176
  </span>
128
177
 
129
- {/* Content */}
130
- <div data-slot="timeline-content" className="min-w-0 pt-0.5">
178
+ {/* Content — in alternate mode, odd items take the left half (text
179
+ aligned toward the spine), even items the right half. */}
180
+ <div
181
+ data-slot="timeline-content"
182
+ className={cn(
183
+ "min-w-0 pt-0.5",
184
+ alternate &&
185
+ "md:w-1/2 md:group-odd:pr-8 md:group-odd:text-right md:group-even:ml-auto md:group-even:pl-8"
186
+ )}
187
+ >
131
188
  {title && (
132
189
  <p
133
190
  data-slot="timeline-title"
@@ -0,0 +1,183 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+
5
+ import { cn } from "../../lib/utils"
6
+
7
+ /**
8
+ * Timer — a live countdown or count-up display that ticks on a configurable
9
+ * interval (the Ark UI Timer / Ant Design Statistic-countdown shape).
10
+ * Distinct from Stat (static value), Progress (visual fill), and
11
+ * FormatNumber (formatting without ticking).
12
+ *
13
+ * Drift-free ticking: each run anchors a `Date.now()` timestamp and derives
14
+ * the displayed value from wall-clock elapsed time, so a throttled or busy
15
+ * tab can delay a repaint but never accumulate error. Pausing freezes the
16
+ * current value; resuming re-anchors from it.
17
+ *
18
+ * Accessibility: the ticking digits are `aria-live="off"` — announcing
19
+ * every second is unusable noise for screen-reader users. Completion is the
20
+ * one event worth announcing: a visually hidden `role="status"` region
21
+ * (polite) appears when a countdown reaches zero. Digits render
22
+ * `tabular-nums` so the display doesn't jitter as values change.
23
+ *
24
+ * State surface: `data-state="running" | "paused" | "completed"` for CSS
25
+ * and test targeting. Paused dims to `text-muted-foreground` via a
26
+ * token-driven color transition — the visible state change is animated, the
27
+ * per-second digit swap deliberately is not (a transition on every tick
28
+ * would smear the digits).
29
+ *
30
+ * Ethics note (registry `ethicsContract`, darkPatternRisk medium):
31
+ * countdowns are the classic fake-scarcity surface. Only bind a Timer to a
32
+ * REAL deadline (session expiry, meeting start, rate-limit window). A
33
+ * countdown that resets on reload, or that pressures a purchase with an
34
+ * invented deadline, is a dark pattern — the ethics floor refuses it.
35
+ */
36
+
37
+ export type TimerFormat = "HH:MM:SS" | "MM:SS" | "SS" | ((ms: number) => string)
38
+
39
+ export interface TimerProps
40
+ extends Omit<React.ComponentProps<"span">, "children" | "onComplete"> {
41
+ /** "countdown" ticks toward zero and completes; "countup" ticks upward forever. Default "countdown". */
42
+ mode?: "countdown" | "countup"
43
+ /**
44
+ * Starting value in milliseconds — the time remaining for a countdown, or
45
+ * the already-elapsed offset for a count-up (usually 0). Default 0.
46
+ */
47
+ startMs?: number
48
+ /** Tick interval in milliseconds. Default 1000. */
49
+ intervalMs?: number
50
+ /**
51
+ * Start ticking on mount (default true). With `autoStart={false}` the
52
+ * timer holds at `startMs` until a `paused={false}` prop starts it.
53
+ */
54
+ autoStart?: boolean
55
+ /** Pause/resume control. When provided it wins over `autoStart`. */
56
+ paused?: boolean
57
+ /** Fires every tick with the current value (remaining ms for countdown, elapsed ms for count-up). */
58
+ onTick?: (ms: number) => void
59
+ /** Fires once when a countdown reaches zero. Never fires in count-up mode. */
60
+ onComplete?: () => void
61
+ /** Display format. A preset string or a custom `(ms) => string`. Default "MM:SS". */
62
+ format?: TimerFormat
63
+ /** Screen-reader announcement when a countdown completes. Default "Time is up". */
64
+ completeAnnouncement?: string
65
+ }
66
+
67
+ function pad(value: number): string {
68
+ return String(value).padStart(2, "0")
69
+ }
70
+
71
+ function formatMs(ms: number, format: TimerFormat): string {
72
+ if (typeof format === "function") return format(ms)
73
+ const totalSeconds = Math.max(0, Math.floor(ms / 1000))
74
+ switch (format) {
75
+ case "HH:MM:SS": {
76
+ const hours = Math.floor(totalSeconds / 3600)
77
+ const minutes = Math.floor((totalSeconds % 3600) / 60)
78
+ const seconds = totalSeconds % 60
79
+ return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`
80
+ }
81
+ case "SS":
82
+ return String(totalSeconds)
83
+ case "MM:SS":
84
+ default: {
85
+ const minutes = Math.floor(totalSeconds / 60)
86
+ const seconds = totalSeconds % 60
87
+ return `${pad(minutes)}:${pad(seconds)}`
88
+ }
89
+ }
90
+ }
91
+
92
+ function Timer({
93
+ mode = "countdown",
94
+ startMs = 0,
95
+ intervalMs = 1000,
96
+ autoStart = true,
97
+ paused,
98
+ onTick,
99
+ onComplete,
100
+ format = "MM:SS",
101
+ completeAnnouncement = "Time is up",
102
+ className,
103
+ style,
104
+ ...props
105
+ }: TimerProps) {
106
+ const [displayMs, setDisplayMs] = React.useState(startMs)
107
+ const [completed, setCompleted] = React.useState(
108
+ mode === "countdown" && startMs <= 0
109
+ )
110
+ // Latest value lives in a ref so a resume can re-anchor from it without
111
+ // the effect depending on displayMs (which would reset the interval every
112
+ // tick).
113
+ const msRef = React.useRef(startMs)
114
+ const onTickRef = React.useRef(onTick)
115
+ const onCompleteRef = React.useRef(onComplete)
116
+ onTickRef.current = onTick
117
+ onCompleteRef.current = onComplete
118
+
119
+ // `paused` prop wins when provided; otherwise autoStart decides.
120
+ const isPaused = paused ?? !autoStart
121
+ const running = !completed && !isPaused
122
+
123
+ React.useEffect(() => {
124
+ if (!running) return
125
+ // Anchor wall-clock time at (re)start — drift-free regardless of how
126
+ // late the interval callbacks actually fire.
127
+ const anchor = Date.now()
128
+ const baseMs = msRef.current
129
+ const tick = () => {
130
+ const elapsed = Date.now() - anchor
131
+ const next =
132
+ mode === "countdown"
133
+ ? Math.max(0, baseMs - elapsed)
134
+ : baseMs + elapsed
135
+ msRef.current = next
136
+ setDisplayMs(next)
137
+ onTickRef.current?.(next)
138
+ if (mode === "countdown" && next <= 0) {
139
+ setCompleted(true)
140
+ onCompleteRef.current?.()
141
+ }
142
+ }
143
+ const id = window.setInterval(tick, intervalMs)
144
+ return () => window.clearInterval(id)
145
+ }, [running, intervalMs, mode])
146
+
147
+ const state = completed ? "completed" : isPaused ? "paused" : "running"
148
+
149
+ return (
150
+ <span
151
+ data-slot="timer"
152
+ data-state={state}
153
+ className={cn(
154
+ // State-change (running ⇄ paused ⇄ completed) animates via a
155
+ // token-driven color transition; the per-tick digit swap does not.
156
+ "inline-flex items-center font-medium tabular-nums transition-colors",
157
+ "text-foreground data-[state=paused]:text-muted-foreground",
158
+ className
159
+ )}
160
+ style={{
161
+ transitionDuration: "var(--duration-base)",
162
+ transitionTimingFunction: "var(--ease-out)",
163
+ ...style,
164
+ }}
165
+ {...props}
166
+ >
167
+ {/* aria-live="off": per-second announcements are unusable noise. The
168
+ value stays readable on demand in the a11y tree. */}
169
+ <span data-slot="timer-value" aria-live="off">
170
+ {formatMs(displayMs, format)}
171
+ </span>
172
+ {/* Entering the DOM on completion triggers exactly one polite
173
+ announcement — the only tick worth interrupting for. */}
174
+ {completed && (
175
+ <span data-slot="timer-announcement" role="status" className="sr-only">
176
+ {completeAnnouncement}
177
+ </span>
178
+ )}
179
+ </span>
180
+ )
181
+ }
182
+
183
+ export { Timer }
@@ -0,0 +1,332 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import * as DialogPrimitive from "@radix-ui/react-dialog"
5
+ import { XIcon } from "lucide-react"
6
+
7
+ import { cn } from "../../lib/utils"
8
+ import { usePortalThemeClass } from "../../hooks/use-portal-theme-class"
9
+ import { Button } from "./button"
10
+
11
+ /**
12
+ * Tour — guided product tour overlay with step progression.
13
+ *
14
+ * A sequenced, selector-anchored walkthrough: each step points at an existing
15
+ * element on the page (by CSS selector), highlights it with a primary ring,
16
+ * and shows a popover-styled panel with title, description, text progress
17
+ * ("Step N of M"), and Back / Next / Finish controls.
18
+ *
19
+ * Built on Radix Dialog internally, so the focus trap, Escape-to-close,
20
+ * scroll lock, and focus-return-to-opener all come from the most
21
+ * a11y-correct base. The page behind the tour is intentionally inert while
22
+ * the tour is open — a tour narrates chrome, it doesn't operate it.
23
+ *
24
+ * Steps with `target: null` (or a selector that matches nothing — e.g.
25
+ * responsive chrome that isn't rendered) render centered, like a welcome or
26
+ * wrap-up step. The panel and highlight glide between steps via token-driven
27
+ * transitions (pattern c); open/close uses the same animate-in/out vocabulary
28
+ * as Dialog (pattern a).
29
+ */
30
+
31
+ interface TourStep {
32
+ /** Step heading, rendered as the dialog title. */
33
+ title: React.ReactNode
34
+ /** Supporting copy for the step. Optional. */
35
+ description?: React.ReactNode
36
+ /**
37
+ * CSS selector for the element this step points at
38
+ * (e.g. `"#save-button"`, `"[data-tour='filters']"`).
39
+ * `null` / `undefined` / no match ⇒ the step renders centered.
40
+ */
41
+ target?: string | null
42
+ /** Which side of the target the panel sits on. Default `"bottom"`. */
43
+ placement?: "top" | "bottom" | "left" | "right"
44
+ }
45
+
46
+ interface TourLabels {
47
+ back?: string
48
+ next?: string
49
+ finish?: string
50
+ close?: string
51
+ /** Formats the text progress indicator. Default: `Step ${current} of ${total}`. */
52
+ progress?: (current: number, total: number) => string
53
+ }
54
+
55
+ interface TourProps {
56
+ /** The ordered steps of the tour. */
57
+ steps: TourStep[]
58
+ /** Whether the tour is open. Fully controlled. */
59
+ open: boolean
60
+ /** Called when the tour requests open/close (Escape, close button, Finish). */
61
+ onOpenChange: (open: boolean) => void
62
+ /** Controlled 0-based step index. Omit for uncontrolled stepping. */
63
+ step?: number
64
+ /** Uncontrolled initial step index. Default 0. */
65
+ defaultStep?: number
66
+ /** Called whenever the active step changes (Back/Next/arrow keys). */
67
+ onStepChange?: (step: number) => void
68
+ /** Called when Finish is pressed on the last step (the tour also closes). */
69
+ onComplete?: () => void
70
+ /** Override the built-in button / progress strings (i18n). */
71
+ labels?: TourLabels
72
+ /** Accessible name for the tour dialog. Default "Product tour". */
73
+ "aria-label"?: string
74
+ }
75
+
76
+ type TargetRect = { top: number; left: number; width: number; height: number }
77
+
78
+ const HIGHLIGHT_PADDING = 6
79
+ const PANEL_GAP = 12
80
+ const VIEWPORT_MARGIN = 16
81
+
82
+ function measureTarget(selector: string | null | undefined): TargetRect | null {
83
+ if (!selector || typeof document === "undefined") return null
84
+ const el = document.querySelector(selector)
85
+ if (!el) return null
86
+ el.scrollIntoView({ block: "nearest", inline: "nearest" })
87
+ const r = el.getBoundingClientRect()
88
+ return { top: r.top, left: r.left, width: r.width, height: r.height }
89
+ }
90
+
91
+ function clamp(value: number, min: number, max: number) {
92
+ return Math.min(Math.max(value, min), Math.max(min, max))
93
+ }
94
+
95
+ function computePanelPosition(
96
+ target: TargetRect,
97
+ placement: NonNullable<TourStep["placement"]>,
98
+ panel: { width: number; height: number }
99
+ ): { top: number; left: number } {
100
+ const centerX = target.left + target.width / 2 - panel.width / 2
101
+ const centerY = target.top + target.height / 2 - panel.height / 2
102
+ let top: number
103
+ let left: number
104
+ switch (placement) {
105
+ case "top":
106
+ top = target.top - HIGHLIGHT_PADDING - PANEL_GAP - panel.height
107
+ left = centerX
108
+ break
109
+ case "left":
110
+ top = centerY
111
+ left = target.left - HIGHLIGHT_PADDING - PANEL_GAP - panel.width
112
+ break
113
+ case "right":
114
+ top = centerY
115
+ left = target.left + target.width + HIGHLIGHT_PADDING + PANEL_GAP
116
+ break
117
+ case "bottom":
118
+ default:
119
+ top = target.top + target.height + HIGHLIGHT_PADDING + PANEL_GAP
120
+ left = centerX
121
+ break
122
+ }
123
+ if (typeof window !== "undefined") {
124
+ top = clamp(top, VIEWPORT_MARGIN, window.innerHeight - panel.height - VIEWPORT_MARGIN)
125
+ left = clamp(left, VIEWPORT_MARGIN, window.innerWidth - panel.width - VIEWPORT_MARGIN)
126
+ }
127
+ return { top, left }
128
+ }
129
+
130
+ function Tour({
131
+ steps,
132
+ open,
133
+ onOpenChange,
134
+ step,
135
+ defaultStep = 0,
136
+ onStepChange,
137
+ onComplete,
138
+ labels,
139
+ "aria-label": ariaLabel = "Product tour",
140
+ }: TourProps) {
141
+ const [uncontrolledStep, setUncontrolledStep] = React.useState(defaultStep)
142
+ const activeIndex = clamp(step ?? uncontrolledStep, 0, Math.max(steps.length - 1, 0))
143
+ const activeStep = steps[activeIndex]
144
+ const total = steps.length
145
+ const isFirst = activeIndex === 0
146
+ const isLast = activeIndex === total - 1
147
+
148
+ const [targetRect, setTargetRect] = React.useState<TargetRect | null>(null)
149
+ const [panelPos, setPanelPos] = React.useState<{ top: number; left: number } | null>(null)
150
+ const panelRef = React.useRef<HTMLDivElement | null>(null)
151
+ const portalThemeClass = usePortalThemeClass()
152
+
153
+ const setStep = React.useCallback(
154
+ (next: number) => {
155
+ const clamped = clamp(next, 0, total - 1)
156
+ if (step === undefined) setUncontrolledStep(clamped)
157
+ onStepChange?.(clamped)
158
+ },
159
+ [step, total, onStepChange]
160
+ )
161
+
162
+ const reposition = React.useCallback(() => {
163
+ const rect = measureTarget(activeStep?.target)
164
+ setTargetRect(rect)
165
+ if (rect && panelRef.current) {
166
+ const { offsetWidth, offsetHeight } = panelRef.current
167
+ setPanelPos(
168
+ computePanelPosition(rect, activeStep?.placement ?? "bottom", {
169
+ width: offsetWidth,
170
+ height: offsetHeight,
171
+ })
172
+ )
173
+ } else {
174
+ setPanelPos(null)
175
+ }
176
+ }, [activeStep])
177
+
178
+ // Measure after the panel renders (its size feeds the position), and track
179
+ // viewport changes while open. Scroll uses capture so nested scroll
180
+ // containers reposition the highlight too.
181
+ React.useLayoutEffect(() => {
182
+ if (!open) return
183
+ reposition()
184
+ window.addEventListener("resize", reposition)
185
+ window.addEventListener("scroll", reposition, true)
186
+ return () => {
187
+ window.removeEventListener("resize", reposition)
188
+ window.removeEventListener("scroll", reposition, true)
189
+ }
190
+ }, [open, reposition])
191
+
192
+ // Reset to the first step whenever the tour reopens (uncontrolled mode).
193
+ React.useEffect(() => {
194
+ if (open && step === undefined) setUncontrolledStep(defaultStep)
195
+ // eslint-disable-next-line react-hooks/exhaustive-deps
196
+ }, [open])
197
+
198
+ if (total === 0) return null
199
+
200
+ const handleNext = () => {
201
+ if (isLast) {
202
+ onComplete?.()
203
+ onOpenChange(false)
204
+ } else {
205
+ setStep(activeIndex + 1)
206
+ }
207
+ }
208
+
209
+ const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
210
+ if (event.key === "ArrowRight" && !isLast) {
211
+ event.preventDefault()
212
+ setStep(activeIndex + 1)
213
+ } else if (event.key === "ArrowLeft" && !isFirst) {
214
+ event.preventDefault()
215
+ setStep(activeIndex - 1)
216
+ }
217
+ }
218
+
219
+ const anchored = targetRect !== null && panelPos !== null
220
+ const progressText =
221
+ labels?.progress?.(activeIndex + 1, total) ?? `Step ${activeIndex + 1} of ${total}`
222
+ const hasDescription = activeStep.description != null
223
+
224
+ return (
225
+ <DialogPrimitive.Root data-slot="tour" open={open} onOpenChange={onOpenChange}>
226
+ <DialogPrimitive.Portal>
227
+ <DialogPrimitive.Overlay
228
+ data-slot="tour-overlay"
229
+ // No backdrop blur — the page being toured must stay readable.
230
+ className="fixed inset-0 z-50 bg-black/40 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0"
231
+ />
232
+ {targetRect !== null && (
233
+ <div
234
+ data-slot="tour-highlight"
235
+ aria-hidden="true"
236
+ className="pointer-events-none fixed z-50 rounded-md ring-2 ring-primary transition-[top,left,width,height]"
237
+ style={{
238
+ top: targetRect.top - HIGHLIGHT_PADDING,
239
+ left: targetRect.left - HIGHLIGHT_PADDING,
240
+ width: targetRect.width + HIGHLIGHT_PADDING * 2,
241
+ height: targetRect.height + HIGHLIGHT_PADDING * 2,
242
+ transitionDuration: "var(--duration-base)",
243
+ transitionTimingFunction: "var(--ease-out)",
244
+ }}
245
+ />
246
+ )}
247
+ <DialogPrimitive.Content
248
+ ref={panelRef}
249
+ data-slot="tour-content"
250
+ data-anchored={anchored ? "" : undefined}
251
+ aria-label={ariaLabel}
252
+ // Steps without a description silence Radix's missing-Description
253
+ // warning; steps with one keep the automatic aria-describedby wiring.
254
+ {...(hasDescription ? {} : { "aria-describedby": undefined })}
255
+ onKeyDown={handleKeyDown}
256
+ className={cn(
257
+ "fixed z-50 flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-3 rounded-lg border bg-popover p-5 text-popover-foreground shadow-md outline-none",
258
+ "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",
259
+ // Anchored panels glide between step targets (pattern c, inline
260
+ // vars below); centered panels use the Dialog translate trick.
261
+ anchored ? "transition-[top,left]" : "left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2",
262
+ portalThemeClass
263
+ )}
264
+ style={
265
+ anchored
266
+ ? {
267
+ top: panelPos.top,
268
+ left: panelPos.left,
269
+ transitionDuration: "var(--duration-base)",
270
+ transitionTimingFunction: "var(--ease-out)",
271
+ }
272
+ : undefined
273
+ }
274
+ >
275
+ <div className="flex flex-col gap-1 pr-10">
276
+ <DialogPrimitive.Title
277
+ data-slot="tour-title"
278
+ className="text-sm leading-snug font-semibold"
279
+ >
280
+ {activeStep.title}
281
+ </DialogPrimitive.Title>
282
+ {hasDescription && (
283
+ <DialogPrimitive.Description
284
+ data-slot="tour-description"
285
+ className="text-sm text-muted-foreground"
286
+ >
287
+ {activeStep.description}
288
+ </DialogPrimitive.Description>
289
+ )}
290
+ </div>
291
+ <div className="flex items-center justify-between gap-3">
292
+ <p
293
+ data-slot="tour-progress"
294
+ aria-live="polite"
295
+ className="text-xs text-muted-foreground tabular-nums"
296
+ >
297
+ {progressText}
298
+ </p>
299
+ <div data-slot="tour-footer" className="flex items-center gap-2">
300
+ <Button
301
+ variant="outline"
302
+ size="xl"
303
+ className="px-4"
304
+ disabled={isFirst}
305
+ onClick={() => setStep(activeIndex - 1)}
306
+ >
307
+ {labels?.back ?? "Back"}
308
+ </Button>
309
+ <Button size="xl" className="px-4" onClick={handleNext}>
310
+ {isLast ? (labels?.finish ?? "Finish") : (labels?.next ?? "Next")}
311
+ </Button>
312
+ </div>
313
+ </div>
314
+ <DialogPrimitive.Close
315
+ data-slot="tour-close"
316
+ aria-label={labels?.close ?? "Close tour"}
317
+ className="absolute top-1 right-1 inline-flex size-11 items-center justify-center rounded-md text-muted-foreground opacity-70 transition-opacity hover:opacity-100 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none"
318
+ style={{
319
+ transitionDuration: "var(--duration-fast)",
320
+ transitionTimingFunction: "var(--ease-out)",
321
+ }}
322
+ >
323
+ <XIcon strokeWidth={1.5} className="size-4" aria-hidden="true" />
324
+ </DialogPrimitive.Close>
325
+ </DialogPrimitive.Content>
326
+ </DialogPrimitive.Portal>
327
+ </DialogPrimitive.Root>
328
+ )
329
+ }
330
+
331
+ export { Tour }
332
+ export type { TourProps, TourStep, TourLabels }