1"use client";
2
3import {
4 autoUpdate,
5 flip,
6 hide,
7 limitShift,
8 type Middleware,
9 offset,
10 arrow as onArrow,
11 type Placement,
12 shift,
13 useFloating,
14} from "@floating-ui/react-dom";
15import { ChevronLeft, ChevronRight, X } from "lucide-react";
16import {
17 Direction as DirectionPrimitive,
18 Slot as SlotPrimitive,
19} from "radix-ui";
20import * as React from "react";
21import * as ReactDOM from "react-dom";
22import { useComposedRefs } from "@/lib/compose-refs";
23import { cn } from "@/lib/utils";
24import { useAsRef } from "@/registry/bases/radix/hooks/use-as-ref";
25import { useIsomorphicLayoutEffect } from "@/registry/bases/radix/hooks/use-isomorphic-layout-effect";
26import { useLazyRef } from "@/registry/bases/radix/hooks/use-lazy-ref";
27import { Button } from "@/registry/bases/radix/ui/button";
28
29const ROOT_NAME = "Tour";
30const PORTAL_NAME = "TourPortal";
31const STEP_NAME = "TourStep";
32const ARROW_NAME = "TourArrow";
33const HEADER_NAME = "TourHeader";
34const TITLE_NAME = "TourTitle";
35const DESCRIPTION_NAME = "TourDescription";
36const CLOSE_NAME = "TourClose";
37const PREV_NAME = "TourPrev";
38const NEXT_NAME = "TourNext";
39const SKIP_NAME = "TourSkip";
40const FOOTER_NAME = "TourFooter";
41
42const POINTER_DOWN_OUTSIDE = "tour.pointerDownOutside";
43const INTERACT_OUTSIDE = "tour.interactOutside";
44const OPEN_AUTO_FOCUS = "tour.openAutoFocus";
45const CLOSE_AUTO_FOCUS = "tour.closeAutoFocus";
46const EVENT_OPTIONS = { bubbles: false, cancelable: true };
47
48const SIDE_OPTIONS = ["top", "right", "bottom", "left"] as const;
49const ALIGN_OPTIONS = ["start", "center", "end"] as const;
50
51const DEFAULT_ALIGN_OFFSET = 0;
52const DEFAULT_SIDE_OFFSET = 16;
53const DEFAULT_SPOTLIGHT_PADDING = 4;
54
55type Side = (typeof SIDE_OPTIONS)[number];
56type Align = (typeof ALIGN_OPTIONS)[number];
57type Direction = "ltr" | "rtl";
58
59interface ScrollOffset {
60 top?: number;
61 bottom?: number;
62 left?: number;
63 right?: number;
64}
65
66type Boundary = Element | null;
67
68interface DivProps extends React.ComponentProps<"div"> {
69 asChild?: boolean;
70}
71
72type StepElement = React.ComponentRef<typeof TourStep>;
73type CloseElement = React.ComponentRef<typeof TourClose>;
74type PrevElement = React.ComponentRef<typeof TourPrev>;
75type NextElement = React.ComponentRef<typeof TourNext>;
76type SkipElement = React.ComponentRef<typeof TourSkip>;
77type FooterElement = React.ComponentRef<typeof TourFooter>;
78
79const OPPOSITE_SIDE: Record<Side, Side> = {
80 top: "bottom",
81 right: "left",
82 bottom: "top",
83 left: "right",
84};
85
86/**
87 * @see https://github.com/radix-ui/primitives/blob/main/packages/react/focus-guards/src/focus-guards.tsx
88 */
89let focusGuardCount = 0;
90
91function createFocusGuard() {
92 const element = document.createElement("span");
93 element.setAttribute("data-tour-focus-guard", "");
94 element.tabIndex = 0;
95 element.style.outline = "none";
96 element.style.opacity = "0";
97 element.style.position = "fixed";
98 element.style.pointerEvents = "none";
99 return element;
100}
101
102function useFocusGuards() {
103 React.useEffect(() => {
104 const edgeGuards = document.querySelectorAll("[data-tour-focus-guard]");
105 document.body.insertAdjacentElement(
106 "afterbegin",
107 edgeGuards[0] ?? createFocusGuard(),
108 );
109 document.body.insertAdjacentElement(
110 "beforeend",
111 edgeGuards[1] ?? createFocusGuard(),
112 );
113 focusGuardCount++;
114
115 return () => {
116 if (focusGuardCount === 1) {
117 const guards = document.querySelectorAll("[data-tour-focus-guard]");
118 for (const node of guards) {
119 node.remove();
120 }
121 }
122 focusGuardCount--;
123 };
124 }, []);
125}
126
127function useFocusTrap(
128 containerRef: React.RefObject<HTMLElement | null>,
129 enabled: boolean,
130 tourOpen: boolean,
131 onOpenAutoFocus?: (event: OpenAutoFocusEvent) => void,
132 onCloseAutoFocus?: (event: CloseAutoFocusEvent) => void,
133) {
134 const lastFocusedElementRef = React.useRef<HTMLElement | null>(null);
135 const onOpenAutoFocusRef = useAsRef(onOpenAutoFocus);
136 const onCloseAutoFocusRef = useAsRef(onCloseAutoFocus);
137 const tourOpenRef = useAsRef(tourOpen);
138
139 React.useEffect(() => {
140 if (!enabled) return;
141
142 const container = containerRef.current;
143 if (!container) return;
144
145 const previouslyFocusedElement =
146 document.activeElement as HTMLElement | null;
147
148 function getTabbableCandidates() {
149 if (!container) return [];
150
151 const nodes: HTMLElement[] = [];
152 const walker = document.createTreeWalker(
153 container,
154 NodeFilter.SHOW_ELEMENT,
155 {
156 acceptNode: (node: Element) => {
157 const element = node as HTMLElement;
158 const isHiddenInput =
159 element.tagName === "INPUT" &&
160 (element as HTMLInputElement).type === "hidden";
161 if (element.hidden || isHiddenInput) return NodeFilter.FILTER_SKIP;
162 return element.tabIndex >= 0
163 ? NodeFilter.FILTER_ACCEPT
164 : NodeFilter.FILTER_SKIP;
165 },
166 },
167 );
168 while (walker.nextNode()) {
169 nodes.push(walker.currentNode as HTMLElement);
170 }
171 return nodes;
172 }
173
174 function getTabbableEdges() {
175 const candidates = getTabbableCandidates();
176 const first = candidates[0];
177 const last = candidates[candidates.length - 1];
178 return [first, last] as const;
179 }
180
181 function onFocusIn(event: FocusEvent) {
182 if (!container) return;
183
184 const target = event.target as HTMLElement | null;
185 if (container.contains(target)) {
186 lastFocusedElementRef.current = target;
187 } else {
188 const elementToFocus =
189 lastFocusedElementRef.current ?? getTabbableCandidates()[0];
190 elementToFocus?.focus({ preventScroll: true });
191 }
192 }
193
194 function onKeyDown(event: KeyboardEvent) {
195 if (event.key !== "Tab" || event.altKey || event.ctrlKey || event.metaKey)
196 return;
197
198 const [first, last] = getTabbableEdges();
199 const hasTabbableElements = first && last;
200
201 if (!hasTabbableElements) {
202 if (document.activeElement === container) event.preventDefault();
203 return;
204 }
205
206 if (!event.shiftKey && document.activeElement === last) {
207 event.preventDefault();
208 first?.focus({ preventScroll: true });
209 } else if (event.shiftKey && document.activeElement === first) {
210 event.preventDefault();
211 last?.focus({ preventScroll: true });
212 }
213 }
214
215 const openAutoFocusEvent = new CustomEvent(OPEN_AUTO_FOCUS, EVENT_OPTIONS);
216 if (onOpenAutoFocusRef.current) {
217 container.addEventListener(
218 OPEN_AUTO_FOCUS,
219 onOpenAutoFocusRef.current as EventListener,
220 { once: true },
221 );
222 }
223 container.dispatchEvent(openAutoFocusEvent);
224
225 if (!openAutoFocusEvent.defaultPrevented) {
226 const tabbableCandidates = getTabbableCandidates();
227 if (tabbableCandidates.length > 0) {
228 tabbableCandidates[0]?.focus({ preventScroll: true });
229 } else {
230 container.focus({ preventScroll: true });
231 }
232 }
233
234 document.addEventListener("focusin", onFocusIn);
235 container.addEventListener("keydown", onKeyDown);
236
237 return () => {
238 document.removeEventListener("focusin", onFocusIn);
239 container.removeEventListener("keydown", onKeyDown);
240
241 if (!tourOpenRef.current) {
242 setTimeout(() => {
243 const closeAutoFocusEvent = new CustomEvent(
244 CLOSE_AUTO_FOCUS,
245 EVENT_OPTIONS,
246 );
247 if (onCloseAutoFocusRef.current) {
248 container.addEventListener(
249 CLOSE_AUTO_FOCUS,
250 onCloseAutoFocusRef.current as EventListener,
251 { once: true },
252 );
253 }
254 container.dispatchEvent(closeAutoFocusEvent);
255
256 if (!closeAutoFocusEvent.defaultPrevented) {
257 if (
258 previouslyFocusedElement &&
259 document.body.contains(previouslyFocusedElement)
260 ) {
261 previouslyFocusedElement.focus({ preventScroll: true });
262 }
263 }
264
265 if (onCloseAutoFocusRef.current) {
266 container.removeEventListener(
267 CLOSE_AUTO_FOCUS,
268 onCloseAutoFocusRef.current as EventListener,
269 );
270 }
271 }, 0);
272 }
273 };
274 }, [
275 containerRef,
276 enabled,
277 onOpenAutoFocusRef,
278 onCloseAutoFocusRef,
279 tourOpenRef,
280 ]);
281}
282
283function getDataState(open: boolean) {
284 return open ? "open" : "closed";
285}
286
287interface StepData {
288 target: string | React.RefObject<HTMLElement> | HTMLElement;
289 align?: Align;
290 alignOffset?: number;
291 side?: Side;
292 sideOffset?: number;
293 collisionBoundary?: Boundary | Boundary[];
294 collisionPadding?: number | Partial<Record<Side, number>>;
295 arrowPadding?: number;
296 sticky?: "partial" | "always";
297 hideWhenDetached?: boolean;
298 avoidCollisions?: boolean;
299 onStepEnter?: () => void;
300 onStepLeave?: () => void;
301 required?: boolean;
302}
303
304interface StoreState {
305 open: boolean;
306 value: number;
307 steps: StepData[];
308 maskPath: string;
309 spotlightRect: { x: number; y: number; width: number; height: number } | null;
310}
311
312interface Store {
313 subscribe: (callback: () => void) => () => void;
314 getState: () => StoreState;
315 setState: <K extends keyof StoreState>(
316 key: K,
317 value: StoreState[K],
318 opts?: unknown,
319 ) => void;
320 notify: () => void;
321 addStep: (stepData: StepData) => { id: string; index: number };
322 removeStep: (id: string) => void;
323}
324
325function useStore<T>(
326 selector: (state: StoreState) => T,
327 ogStore?: Store | null,
328): T {
329 const contextStore = React.useContext(StoreContext);
330
331 const store = ogStore ?? contextStore;
332
333 if (!store) {
334 throw new Error(`\`useStore\` must be used within \`${ROOT_NAME}\``);
335 }
336
337 const getSnapshot = React.useCallback(
338 () => selector(store.getState()),
339 [store, selector],
340 );
341
342 return React.useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
343}
344
345function getTargetElement(
346 target: string | React.RefObject<HTMLElement> | HTMLElement,
347): HTMLElement | null {
348 if (typeof target === "string") {
349 return document.querySelector(target);
350 }
351 if (target && "current" in target) {
352 return target.current;
353 }
354 if (target instanceof HTMLElement) {
355 return target;
356 }
357 return null;
358}
359
360function getDefaultScrollBehavior(): ScrollBehavior {
361 if (typeof window === "undefined") return "smooth";
362 return window.matchMedia("(prefers-reduced-motion: reduce)").matches
363 ? "auto"
364 : "smooth";
365}
366
367function onScrollToElement(
368 element: HTMLElement,
369 scrollBehavior: ScrollBehavior = getDefaultScrollBehavior(),
370 scrollOffset?: ScrollOffset,
371) {
372 const offset: Required<ScrollOffset> = {
373 top: 100,
374 bottom: 100,
375 left: 0,
376 right: 0,
377 ...scrollOffset,
378 };
379 const rect = element.getBoundingClientRect();
380 const viewportHeight = window.innerHeight;
381 const viewportWidth = window.innerWidth;
382
383 const isInViewport =
384 rect.top >= offset.top &&
385 rect.bottom <= viewportHeight - offset.bottom &&
386 rect.left >= offset.left &&
387 rect.right <= viewportWidth - offset.right;
388
389 if (!isInViewport) {
390 const elementTop = rect.top + window.scrollY;
391 const scrollTop = elementTop - offset.top;
392
393 window.scrollTo({
394 top: Math.max(0, scrollTop),
395 behavior: scrollBehavior,
396 });
397 }
398}
399
400function getSideAndAlignFromPlacement(placement: Placement): [Side, Align] {
401 const [side, align = "center"] = placement.split("-") as [Side, Align?];
402 return [side, align];
403}
404
405function getPlacement(side: Side, align: Align): Placement {
406 if (align === "center") {
407 return side as Placement;
408 }
409 return `${side}-${align}` as Placement;
410}
411
412function updateMask(
413 store: Store,
414 targetElement: HTMLElement,
415 padding: number = DEFAULT_SPOTLIGHT_PADDING,
416) {
417 const clientRect = targetElement.getBoundingClientRect();
418 const viewportWidth = window.innerWidth;
419 const viewportHeight = window.innerHeight;
420
421 const x = Math.max(0, clientRect.left - padding);
422 const y = Math.max(0, clientRect.top - padding);
423 const width = Math.min(viewportWidth - x, clientRect.width + padding * 2);
424 const height = Math.min(viewportHeight - y, clientRect.height + padding * 2);
425
426 const path = `polygon(0% 0%, 0% 100%, ${x}px 100%, ${x}px ${y}px, ${x + width}px ${y}px, ${x + width}px ${y + height}px, ${x}px ${y + height}px, ${x}px 100%, 100% 100%, 100% 0%)`;
427 store.setState("maskPath", path);
428 store.setState("spotlightRect", { x, y, width, height });
429}
430
431const StoreContext = React.createContext<Store | null>(null);
432
433function useStoreContext(consumerName: string) {
434 const context = React.useContext(StoreContext);
435 if (!context) {
436 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
437 }
438 return context;
439}
440
441interface TourContextValue {
442 dir: Direction;
443 alignOffset: number;
444 sideOffset: number;
445 spotlightPadding: number;
446 dismissible: boolean;
447 modal: boolean;
448 stepFooter?: React.ReactElement;
449 onPointerDownOutside?: (event: PointerDownOutsideEvent) => void;
450 onInteractOutside?: (event: InteractOutsideEvent) => void;
451 onOpenAutoFocus?: (event: OpenAutoFocusEvent) => void;
452 onCloseAutoFocus?: (event: CloseAutoFocusEvent) => void;
453}
454
455const TourContext = React.createContext<TourContextValue | null>(null);
456
457function useTourContext(consumerName: string) {
458 const context = React.useContext(TourContext);
459 if (!context) {
460 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
461 }
462 return context;
463}
464
465interface StepContextValue {
466 arrowX?: number;
467 arrowY?: number;
468 placedAlign: Align;
469 placedSide: Side;
470 shouldHideArrow: boolean;
471 onArrowChange: (arrow: HTMLSpanElement | null) => void;
472 onFooterChange: (footer: FooterElement | null) => void;
473}
474
475const StepContext = React.createContext<StepContextValue | null>(null);
476
477function useStepContext(consumerName: string) {
478 const context = React.useContext(StepContext);
479 if (!context) {
480 throw new Error(`\`${consumerName}\` must be used within \`${STEP_NAME}\``);
481 }
482 return context;
483}
484
485const DefaultFooterContext = React.createContext(false);
486
487interface PortalContextValue {
488 portal: HTMLElement | null;
489 onPortalChange: (node: HTMLElement | null) => void;
490}
491
492const PortalContext = React.createContext<PortalContextValue | null>(null);
493
494function usePortalContext(consumerName: string) {
495 const context = React.useContext(PortalContext);
496 if (!context) {
497 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
498 }
499 return context;
500}
501
502function useScrollLock(enabled: boolean) {
503 React.useEffect(() => {
504 if (!enabled) return;
505
506 const originalStyle = window.getComputedStyle(document.body).overflow;
507 const scrollbarWidth =
508 window.innerWidth - document.documentElement.clientWidth;
509
510 document.body.style.overflow = "hidden";
511 if (scrollbarWidth > 0) {
512 document.body.style.paddingRight = `${scrollbarWidth}px`;
513 }
514
515 return () => {
516 document.body.style.overflow = originalStyle;
517 document.body.style.paddingRight = "";
518 };
519 }, [enabled]);
520}
521
522type PointerDownOutsideEvent = CustomEvent<{ originalEvent: PointerEvent }>;
523type InteractOutsideEvent = CustomEvent<{
524 originalEvent: PointerEvent | FocusEvent;
525}>;
526type OpenAutoFocusEvent = CustomEvent<Record<string, never>>;
527type CloseAutoFocusEvent = CustomEvent<Record<string, never>>;
528
529interface TourProps extends DivProps {
530 open?: boolean;
531 defaultOpen?: boolean;
532 onOpenChange?: (open: boolean) => void;
533 value?: number;
534 defaultValue?: number;
535 onValueChange?: (step: number) => void;
536 onComplete?: () => void;
537 onSkip?: () => void;
538 onEscapeKeyDown?: (event: KeyboardEvent) => void;
539 onPointerDownOutside?: (event: PointerDownOutsideEvent) => void;
540 onInteractOutside?: (event: InteractOutsideEvent) => void;
541 onOpenAutoFocus?: (event: OpenAutoFocusEvent) => void;
542 onCloseAutoFocus?: (event: CloseAutoFocusEvent) => void;
543 dir?: Direction;
544 alignOffset?: number;
545 sideOffset?: number;
546 spotlightPadding?: number;
547 autoScroll?: boolean;
548 scrollBehavior?: ScrollBehavior;
549 scrollOffset?: ScrollOffset;
550 dismissible?: boolean;
551 modal?: boolean;
552 stepFooter?: React.ReactElement;
553}
554
555function Tour(props: TourProps) {
556 const {
557 open: openProp,
558 defaultOpen = false,
559 onOpenChange,
560 value: valueProp,
561 defaultValue = 0,
562 onValueChange,
563 onComplete,
564 onSkip,
565 autoScroll = true,
566 scrollBehavior = getDefaultScrollBehavior(),
567 scrollOffset,
568 onEscapeKeyDown,
569 onPointerDownOutside,
570 onInteractOutside,
571 onOpenAutoFocus,
572 onCloseAutoFocus,
573 dir: dirProp,
574 alignOffset = DEFAULT_ALIGN_OFFSET,
575 sideOffset = DEFAULT_SIDE_OFFSET,
576 spotlightPadding = DEFAULT_SPOTLIGHT_PADDING,
577 dismissible = true,
578 modal = true,
579 stepFooter,
580 asChild,
581 ...rootProps
582 } = props;
583
584 const dir = DirectionPrimitive.useDirection(dirProp);
585
586 const [portal, setPortal] = React.useState<HTMLElement | null>(null);
587 const prevOpenRef = React.useRef<boolean | undefined>(undefined);
588 const previouslyFocusedElementRef = React.useRef<HTMLElement | null>(null);
589
590 const stateRef = useLazyRef<StoreState>(() => ({
591 open: openProp ?? defaultOpen,
592 value: valueProp ?? defaultValue,
593 steps: [],
594 maskPath: "",
595 spotlightRect: null,
596 }));
597 const listenersRef = useLazyRef<Set<() => void>>(() => new Set());
598 const stepIdsMapRef = useLazyRef<Map<string, number>>(() => new Map());
599 const stepIdCounterRef = useLazyRef(() => ({ current: 0 }));
600 const propsRef = useAsRef({
601 valueProp,
602 onOpenChange,
603 onValueChange,
604 onComplete,
605 onSkip,
606 onEscapeKeyDown,
607 onCloseAutoFocus,
608 autoScroll,
609 scrollBehavior,
610 scrollOffset,
611 });
612
613 const store: Store = React.useMemo(
614 () => ({
615 subscribe: (cb) => {
616 listenersRef.current.add(cb);
617 return () => listenersRef.current.delete(cb);
618 },
619 getState: () => {
620 return stateRef.current;
621 },
622 setState: (key, value) => {
623 if (Object.is(stateRef.current[key], value)) return;
624 stateRef.current[key] = value;
625
626 if (key === "open" && typeof value === "boolean") {
627 propsRef.current.onOpenChange?.(value);
628
629 if (value) {
630 if (stateRef.current.steps.length > 0) {
631 if (stateRef.current.value >= stateRef.current.steps.length) {
632 store.setState("value", 0);
633 }
634 }
635 } else {
636 if (
637 stateRef.current.value <
638 (stateRef.current.steps.length || 0) - 1
639 ) {
640 propsRef.current.onSkip?.();
641 }
642 }
643 } else if (key === "value" && typeof value === "number") {
644 const prevStep = stateRef.current.steps[stateRef.current.value];
645 const nextStep = stateRef.current.steps[value];
646
647 prevStep?.onStepLeave?.();
648 nextStep?.onStepEnter?.();
649
650 if (value >= stateRef.current.steps.length) {
651 propsRef.current.onComplete?.();
652
653 if (propsRef.current.valueProp !== undefined) {
654 propsRef.current.onValueChange?.(value);
655 }
656
657 store.setState("open", false);
658 return;
659 }
660
661 if (propsRef.current.valueProp !== undefined) {
662 propsRef.current.onValueChange?.(value);
663 return;
664 }
665
666 propsRef.current.onValueChange?.(value);
667
668 if (nextStep && propsRef.current.autoScroll) {
669 const targetElement = getTargetElement(nextStep.target);
670 if (targetElement) {
671 onScrollToElement(
672 targetElement,
673 propsRef.current.scrollBehavior,
674 propsRef.current.scrollOffset,
675 );
676 }
677 }
678 }
679
680 store.notify();
681 },
682 notify: () => {
683 listenersRef.current.forEach((l) => {
684 l();
685 });
686 },
687 addStep: (stepData) => {
688 const id = `step-${stepIdCounterRef.current.current++}`;
689 const index = stateRef.current.steps.length;
690 stepIdsMapRef.current.set(id, index);
691 stateRef.current.steps = [...stateRef.current.steps, stepData];
692 store.notify();
693 return { id, index };
694 },
695 removeStep: (id) => {
696 const index = stepIdsMapRef.current.get(id);
697 if (index === undefined) return;
698
699 stateRef.current.steps = stateRef.current.steps.filter(
700 (_, i) => i !== index,
701 );
702
703 stepIdsMapRef.current.delete(id);
704
705 for (const [stepId, stepIndex] of stepIdsMapRef.current.entries()) {
706 if (stepIndex > index) {
707 stepIdsMapRef.current.set(stepId, stepIndex - 1);
708 }
709 }
710
711 store.notify();
712 },
713 }),
714 [stateRef, listenersRef, stepIdsMapRef, stepIdCounterRef, propsRef],
715 );
716
717 const open = useStore((state) => state.open, store);
718
719 React.useEffect(() => {
720 function onKeyDown(event: KeyboardEvent) {
721 if (open && event.key === "Escape") {
722 if (propsRef.current.onEscapeKeyDown) {
723 propsRef.current.onEscapeKeyDown(event);
724 if (event.defaultPrevented) return;
725 }
726 store.setState("open", false);
727 }
728 }
729
730 document.addEventListener("keydown", onKeyDown);
731 return () => document.removeEventListener("keydown", onKeyDown);
732 }, [store, open, propsRef]);
733
734 useIsomorphicLayoutEffect(() => {
735 const wasOpen = prevOpenRef.current;
736
737 if (open && !wasOpen) {
738 previouslyFocusedElementRef.current =
739 document.activeElement as HTMLElement | null;
740 } else if (!open && wasOpen) {
741 setTimeout(() => {
742 const container = portal ?? document.body;
743 const closeAutoFocusEvent = new CustomEvent(
744 CLOSE_AUTO_FOCUS,
745 EVENT_OPTIONS,
746 );
747
748 if (propsRef.current.onCloseAutoFocus) {
749 container.addEventListener(
750 CLOSE_AUTO_FOCUS,
751 propsRef.current.onCloseAutoFocus as EventListener,
752 { once: true },
753 );
754 }
755 container.dispatchEvent(closeAutoFocusEvent);
756
757 if (!closeAutoFocusEvent.defaultPrevented) {
758 const elementToFocus = previouslyFocusedElementRef.current;
759 if (elementToFocus && document.body.contains(elementToFocus)) {
760 elementToFocus.focus({ preventScroll: true });
761 }
762 }
763
764 previouslyFocusedElementRef.current = null;
765 }, 0);
766 }
767
768 prevOpenRef.current = open;
769 }, [open, portal, propsRef]);
770
771 useIsomorphicLayoutEffect(() => {
772 if (openProp !== undefined) {
773 store.setState("open", openProp);
774 }
775 }, [openProp, store]);
776
777 useIsomorphicLayoutEffect(() => {
778 if (valueProp !== undefined) {
779 store.setState("value", valueProp);
780 }
781 }, [valueProp, store]);
782
783 const contextValue = React.useMemo<TourContextValue>(
784 () => ({
785 dir,
786 alignOffset,
787 sideOffset,
788 spotlightPadding,
789 dismissible,
790 modal,
791 stepFooter,
792 onPointerDownOutside,
793 onInteractOutside,
794 onOpenAutoFocus,
795 onCloseAutoFocus,
796 }),
797 [
798 dir,
799 alignOffset,
800 sideOffset,
801 spotlightPadding,
802 dismissible,
803 modal,
804 stepFooter,
805 onPointerDownOutside,
806 onInteractOutside,
807 onOpenAutoFocus,
808 onCloseAutoFocus,
809 ],
810 );
811
812 const portalContextValue = React.useMemo<PortalContextValue>(
813 () => ({
814 portal,
815 onPortalChange: setPortal,
816 }),
817 [portal],
818 );
819
820 useScrollLock(open && modal);
821
822 const RootPrimitive = asChild ? SlotPrimitive.Slot : "div";
823
824 return (
825 <StoreContext.Provider value={store}>
826 <TourContext.Provider value={contextValue}>
827 <PortalContext.Provider value={portalContextValue}>
828 <RootPrimitive data-slot="tour" dir={dir} {...rootProps} />
829 </PortalContext.Provider>
830 </TourContext.Provider>
831 </StoreContext.Provider>
832 );
833}
834
835interface TourStepProps extends DivProps {
836 target: string | React.RefObject<HTMLElement> | HTMLElement;
837 side?: Side;
838 sideOffset?: number;
839 align?: Align;
840 alignOffset?: number;
841 collisionBoundary?: Boundary | Boundary[];
842 collisionPadding?: number | Partial<Record<Side, number>>;
843 arrowPadding?: number;
844 sticky?: "partial" | "always";
845 hideWhenDetached?: boolean;
846 avoidCollisions?: boolean;
847 required?: boolean;
848 forceMount?: boolean;
849 onStepEnter?: () => void;
850 onStepLeave?: () => void;
851}
852
853function TourStep(props: TourStepProps) {
854 const {
855 target,
856 side = "bottom",
857 sideOffset,
858 align = "center",
859 alignOffset,
860 collisionBoundary = [],
861 collisionPadding = 0,
862 arrowPadding = 0,
863 sticky = "partial",
864 hideWhenDetached = false,
865 avoidCollisions = true,
866 required = false,
867 forceMount = false,
868 onStepEnter,
869 onStepLeave,
870 onPointerDownCapture: onPointerDownCaptureProp,
871 onFocusCapture: onFocusCaptureProp,
872 onBlurCapture: onBlurCaptureProp,
873 children,
874 className,
875 style,
876 asChild,
877 ...stepProps
878 } = props;
879
880 const store = useStoreContext(STEP_NAME);
881
882 const [arrow, setArrow] = React.useState<HTMLSpanElement | null>(null);
883 const [footer, setFooter] = React.useState<FooterElement | null>(null);
884
885 const stepRef = React.useRef<StepElement | null>(null);
886 const stepIdRef = React.useRef<string>("");
887 const stepOrderRef = React.useRef<number>(-1);
888 const isPointerInsideReactTreeRef = React.useRef(false);
889 const isFocusInsideReactTreeRef = React.useRef(false);
890
891 const open = useStore((state) => state.open);
892 const value = useStore((state) => state.value);
893 const steps = useStore((state) => state.steps);
894 const context = useTourContext(STEP_NAME);
895
896 const resolvedSideOffset = sideOffset ?? context.sideOffset;
897 const resolvedAlignOffset = alignOffset ?? context.alignOffset;
898
899 useIsomorphicLayoutEffect(() => {
900 const { id, index } = store.addStep({
901 target,
902 align,
903 alignOffset: resolvedAlignOffset,
904 side,
905 sideOffset: resolvedSideOffset,
906 collisionBoundary,
907 collisionPadding,
908 arrowPadding,
909 sticky,
910 hideWhenDetached,
911 avoidCollisions,
912 onStepEnter,
913 onStepLeave,
914 required,
915 });
916 stepIdRef.current = id;
917 stepOrderRef.current = index;
918
919 return () => {
920 store.removeStep(stepIdRef.current);
921 };
922 }, [
923 target,
924 side,
925 resolvedSideOffset,
926 align,
927 resolvedAlignOffset,
928 collisionPadding,
929 arrowPadding,
930 sticky,
931 hideWhenDetached,
932 avoidCollisions,
933 required,
934 onStepEnter,
935 onStepLeave,
936 store,
937 ]);
938
939 const stepData = steps[value];
940 const targetElement = stepData ? getTargetElement(stepData.target) : null;
941
942 const isCurrentStep = stepOrderRef.current === value;
943
944 const middleware = React.useMemo(() => {
945 if (!stepData) return [];
946
947 const mainAxisOffset = stepData.sideOffset ?? resolvedSideOffset;
948 const crossAxisOffset = stepData.alignOffset ?? resolvedAlignOffset;
949
950 const padding =
951 typeof stepData.collisionPadding === "number"
952 ? stepData.collisionPadding
953 : {
954 top: stepData.collisionPadding?.top ?? 0,
955 right: stepData.collisionPadding?.right ?? 0,
956 bottom: stepData.collisionPadding?.bottom ?? 0,
957 left: stepData.collisionPadding?.left ?? 0,
958 };
959
960 const boundary = Array.isArray(stepData.collisionBoundary)
961 ? stepData.collisionBoundary
962 : stepData.collisionBoundary
963 ? [stepData.collisionBoundary]
964 : [];
965 const hasExplicitBoundaries = boundary.length > 0;
966
967 const detectOverflowOptions = {
968 padding,
969 boundary: boundary.filter((b): b is Element => b !== null),
970 altBoundary: hasExplicitBoundaries,
971 };
972
973 return [
974 offset({
975 mainAxis: mainAxisOffset,
976 alignmentAxis: crossAxisOffset,
977 }),
978 stepData.avoidCollisions &&
979 shift({
980 mainAxis: true,
981 crossAxis: false,
982 limiter: stepData.sticky === "partial" ? limitShift() : undefined,
983 ...detectOverflowOptions,
984 }),
985 stepData.avoidCollisions && flip({ ...detectOverflowOptions }),
986 arrow && onArrow({ element: arrow, padding: stepData.arrowPadding }),
987 stepData.hideWhenDetached &&
988 hide({
989 strategy: "referenceHidden",
990 ...detectOverflowOptions,
991 }),
992 ].filter(Boolean) as Middleware[];
993 }, [stepData, resolvedSideOffset, resolvedAlignOffset, arrow]);
994
995 const placement = getPlacement(
996 stepData?.side ?? side,
997 stepData?.align ?? align,
998 );
999
1000 const {
1001 refs,
1002 floatingStyles,
1003 placement: finalPlacement,
1004 middlewareData,
1005 } = useFloating({
1006 placement,
1007 middleware,
1008 strategy: "fixed",
1009 whileElementsMounted: autoUpdate,
1010 elements: {
1011 reference: targetElement,
1012 },
1013 });
1014
1015 const composedRef = useComposedRefs(refs.setFloating, stepRef);
1016
1017 const [placedSide, placedAlign] =
1018 getSideAndAlignFromPlacement(finalPlacement);
1019
1020 const arrowX = middlewareData.arrow?.x;
1021 const arrowY = middlewareData.arrow?.y;
1022 const cannotCenterArrow = middlewareData.arrow?.centerOffset !== 0;
1023 const isHidden = hideWhenDetached && middlewareData.hide?.referenceHidden;
1024
1025 const stepContextValue = React.useMemo<StepContextValue>(
1026 () => ({
1027 arrowX,
1028 arrowY,
1029 placedAlign,
1030 placedSide,
1031 shouldHideArrow: cannotCenterArrow,
1032 onArrowChange: setArrow,
1033 onFooterChange: setFooter,
1034 }),
1035 [arrowX, arrowY, placedSide, placedAlign, cannotCenterArrow],
1036 );
1037
1038 React.useEffect(() => {
1039 if (open && targetElement && isCurrentStep) {
1040 updateMask(store, targetElement, context.spotlightPadding);
1041
1042 let rafId: number | null = null;
1043
1044 function onResize() {
1045 if (targetElement) {
1046 updateMask(store, targetElement, context.spotlightPadding);
1047 }
1048 }
1049
1050 function onScroll() {
1051 if (rafId !== null) return;
1052 rafId = requestAnimationFrame(() => {
1053 if (targetElement) {
1054 updateMask(store, targetElement, context.spotlightPadding);
1055 }
1056 rafId = null;
1057 });
1058 }
1059
1060 window.addEventListener("resize", onResize);
1061 window.addEventListener("scroll", onScroll, { passive: true });
1062 return () => {
1063 window.removeEventListener("resize", onResize);
1064 window.removeEventListener("scroll", onScroll);
1065 if (rafId !== null) {
1066 cancelAnimationFrame(rafId);
1067 }
1068 };
1069 }
1070 }, [open, targetElement, isCurrentStep, store, context.spotlightPadding]);
1071
1072 React.useEffect(() => {
1073 if (!open || !isCurrentStep) return;
1074
1075 const stepElement = stepRef.current;
1076 if (!stepElement) return;
1077
1078 const ownerDocument = stepElement.ownerDocument;
1079
1080 function onPointerDown(event: PointerEvent) {
1081 if (event.target && !isPointerInsideReactTreeRef.current) {
1082 const pointerDownOutsideEvent = new CustomEvent(POINTER_DOWN_OUTSIDE, {
1083 ...EVENT_OPTIONS,
1084 detail: { originalEvent: event },
1085 });
1086
1087 context.onPointerDownOutside?.(pointerDownOutsideEvent);
1088
1089 const interactOutsideEvent = new CustomEvent(INTERACT_OUTSIDE, {
1090 ...EVENT_OPTIONS,
1091 detail: { originalEvent: event },
1092 });
1093 context.onInteractOutside?.(interactOutsideEvent);
1094
1095 if (
1096 !pointerDownOutsideEvent.defaultPrevented &&
1097 !interactOutsideEvent.defaultPrevented &&
1098 context.dismissible
1099 ) {
1100 store.setState("open", false);
1101 }
1102 }
1103
1104 isPointerInsideReactTreeRef.current = false;
1105 }
1106
1107 const timerId = window.setTimeout(() => {
1108 ownerDocument.addEventListener("pointerdown", onPointerDown);
1109 }, 0);
1110
1111 return () => {
1112 window.clearTimeout(timerId);
1113 ownerDocument.removeEventListener("pointerdown", onPointerDown);
1114 };
1115 }, [open, isCurrentStep, store, context]);
1116
1117 React.useEffect(() => {
1118 if (!open || !isCurrentStep) return;
1119
1120 const stepElement = stepRef.current;
1121 if (!stepElement) return;
1122
1123 const ownerDocument = stepElement.ownerDocument;
1124
1125 function onFocusIn(event: FocusEvent) {
1126 const target = event.target as HTMLElement;
1127
1128 const isFocusInStep = stepElement?.contains(target);
1129 const isFocusInTarget = targetElement?.contains(target);
1130
1131 if (
1132 event.target &&
1133 !isFocusInsideReactTreeRef.current &&
1134 !isFocusInStep &&
1135 !isFocusInTarget
1136 ) {
1137 const interactOutsideEvent = new CustomEvent(INTERACT_OUTSIDE, {
1138 ...EVENT_OPTIONS,
1139 detail: { originalEvent: event },
1140 });
1141
1142 context.onInteractOutside?.(interactOutsideEvent);
1143
1144 if (!interactOutsideEvent.defaultPrevented && context.dismissible) {
1145 store.setState("open", false);
1146 }
1147 }
1148 }
1149
1150 ownerDocument.addEventListener("focusin", onFocusIn);
1151
1152 return () => {
1153 ownerDocument.removeEventListener("focusin", onFocusIn);
1154 };
1155 }, [open, isCurrentStep, store, context, targetElement]);
1156
1157 const onPointerDownCapture = React.useCallback(
1158 (event: React.PointerEvent<StepElement>) => {
1159 onPointerDownCaptureProp?.(event);
1160 isPointerInsideReactTreeRef.current = true;
1161 },
1162 [onPointerDownCaptureProp],
1163 );
1164
1165 const onFocusCapture = React.useCallback(
1166 (event: React.FocusEvent<StepElement>) => {
1167 onFocusCaptureProp?.(event);
1168 isFocusInsideReactTreeRef.current = true;
1169 },
1170 [onFocusCaptureProp],
1171 );
1172
1173 const onBlurCapture = React.useCallback(
1174 (event: React.FocusEvent<StepElement>) => {
1175 onBlurCaptureProp?.(event);
1176 isFocusInsideReactTreeRef.current = false;
1177 },
1178 [onBlurCaptureProp],
1179 );
1180
1181 React.useEffect(() => {
1182 if (!open || !isCurrentStep || !targetElement) return;
1183
1184 function onTargetPointerDownCapture() {
1185 isPointerInsideReactTreeRef.current = true;
1186 }
1187
1188 function onTargetFocusCapture() {
1189 isFocusInsideReactTreeRef.current = true;
1190 }
1191
1192 function onTargetBlurCapture() {
1193 isFocusInsideReactTreeRef.current = false;
1194 }
1195
1196 targetElement.addEventListener(
1197 "pointerdown",
1198 onTargetPointerDownCapture,
1199 true,
1200 );
1201 targetElement.addEventListener("focus", onTargetFocusCapture, true);
1202 targetElement.addEventListener("blur", onTargetBlurCapture, true);
1203
1204 return () => {
1205 targetElement.removeEventListener(
1206 "pointerdown",
1207 onTargetPointerDownCapture,
1208 true,
1209 );
1210 targetElement.removeEventListener("focus", onTargetFocusCapture, true);
1211 targetElement.removeEventListener("blur", onTargetBlurCapture, true);
1212 };
1213 }, [open, isCurrentStep, targetElement]);
1214
1215 useFocusGuards();
1216 useFocusTrap(
1217 stepRef,
1218 open && isCurrentStep,
1219 open,
1220 context.onOpenAutoFocus,
1221 context.onCloseAutoFocus,
1222 );
1223
1224 if (!open || !stepData || (!targetElement && !forceMount) || !isCurrentStep) {
1225 return null;
1226 }
1227
1228 const StepPrimitive = asChild ? SlotPrimitive.Slot : "div";
1229
1230 return (
1231 <StepContext.Provider value={stepContextValue}>
1232 <StepPrimitive
1233 ref={composedRef}
1234 data-slot="tour-step"
1235 data-side={placedSide}
1236 data-align={placedAlign}
1237 dir={context.dir}
1238 tabIndex={-1}
1239 {...stepProps}
1240 onPointerDownCapture={onPointerDownCapture}
1241 onFocusCapture={onFocusCapture}
1242 onBlurCapture={onBlurCapture}
1243 className={cn(
1244 "fixed z-50 flex w-80 flex-col gap-4 rounded-lg border bg-popover p-4 text-popover-foreground shadow-md outline-none",
1245 className,
1246 )}
1247 style={{
1248 ...style,
1249 ...floatingStyles,
1250 visibility: isHidden ? "hidden" : undefined,
1251 pointerEvents: isHidden ? "none" : undefined,
1252 }}
1253 >
1254 {children}
1255 {!footer && (
1256 <DefaultFooterContext.Provider value={true}>
1257 {context.stepFooter}
1258 </DefaultFooterContext.Provider>
1259 )}
1260 </StepPrimitive>
1261 </StepContext.Provider>
1262 );
1263}
1264
1265interface TourSpotlightProps extends DivProps {
1266 forceMount?: boolean;
1267}
1268
1269function TourSpotlight(props: TourSpotlightProps) {
1270 const {
1271 asChild,
1272 className,
1273 style,
1274 forceMount = false,
1275 ...backdropProps
1276 } = props;
1277
1278 const open = useStore((state) => state.open);
1279 const maskPath = useStore((state) => state.maskPath);
1280
1281 if (!open && !forceMount) return null;
1282
1283 const SpotlightPrimitive = asChild ? SlotPrimitive.Slot : "div";
1284
1285 return (
1286 <SpotlightPrimitive
1287 data-slot="tour-spotlight"
1288 data-state={getDataState(open)}
1289 {...backdropProps}
1290 className={cn(
1291 "data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/80 data-[state=closed]:animate-out data-[state=open]:animate-in",
1292 className,
1293 )}
1294 style={{
1295 clipPath: maskPath,
1296 ...style,
1297 }}
1298 />
1299 );
1300}
1301
1302interface TourSpotlightRingProps extends DivProps {
1303 forceMount?: boolean;
1304}
1305
1306function TourSpotlightRing(props: TourSpotlightRingProps) {
1307 const { asChild, className, style, forceMount = false, ...ringProps } = props;
1308
1309 const open = useStore((state) => state.open);
1310 const spotlightRect = useStore((state) => state.spotlightRect);
1311
1312 if (!open && !forceMount) return null;
1313 if (!spotlightRect) return null;
1314
1315 const RingPrimitive = asChild ? SlotPrimitive.Slot : "div";
1316
1317 return (
1318 <RingPrimitive
1319 data-slot="tour-spotlight-ring"
1320 data-state={getDataState(open)}
1321 {...ringProps}
1322 className={cn(
1323 "pointer-events-none fixed z-50 border-ring ring-[3px] ring-ring/50",
1324 className,
1325 )}
1326 style={{
1327 left: spotlightRect.x,
1328 top: spotlightRect.y,
1329 width: spotlightRect.width,
1330 height: spotlightRect.height,
1331 ...style,
1332 }}
1333 />
1334 );
1335}
1336
1337interface TourPortalProps {
1338 children?: React.ReactNode;
1339 container?: HTMLElement | null;
1340}
1341
1342function TourPortal(props: TourPortalProps) {
1343 const { children, container } = props;
1344
1345 const portalContext = usePortalContext(PORTAL_NAME);
1346
1347 const [mounted, setMounted] = React.useState(false);
1348
1349 useIsomorphicLayoutEffect(() => {
1350 setMounted(true);
1351
1352 const node = container ?? document.body;
1353
1354 portalContext?.onPortalChange(node);
1355 return () => {
1356 portalContext?.onPortalChange(null);
1357 };
1358 }, [container, portalContext]);
1359
1360 if (!mounted) return null;
1361
1362 const portalContainer = container ?? portalContext?.portal ?? document.body;
1363
1364 return ReactDOM.createPortal(children, portalContainer);
1365}
1366
1367interface TourArrowProps extends React.ComponentProps<"svg"> {
1368 width?: number;
1369 height?: number;
1370 asChild?: boolean;
1371}
1372
1373function TourArrow(props: TourArrowProps) {
1374 const {
1375 width = 10,
1376 height = 5,
1377 className,
1378 children,
1379 asChild,
1380 ...arrowProps
1381 } = props;
1382
1383 const stepContext = useStepContext(ARROW_NAME);
1384 const baseSide = OPPOSITE_SIDE[stepContext.placedSide];
1385
1386 return (
1387 <span
1388 ref={stepContext.onArrowChange}
1389 data-slot="tour-arrow"
1390 style={{
1391 position: "absolute",
1392 left:
1393 stepContext.arrowX != null ? `${stepContext.arrowX}px` : undefined,
1394 top: stepContext.arrowY != null ? `${stepContext.arrowY}px` : undefined,
1395 [baseSide]: 0,
1396 transformOrigin: {
1397 top: "",
1398 right: "0 0",
1399 bottom: "center 0",
1400 left: "100% 0",
1401 }[stepContext.placedSide],
1402 transform: {
1403 top: "translateY(100%)",
1404 right: "translateY(50%) rotate(90deg) translateX(-50%)",
1405 bottom: "rotate(180deg)",
1406 left: "translateY(50%) rotate(-90deg) translateX(50%)",
1407 }[stepContext.placedSide],
1408 visibility: stepContext.shouldHideArrow ? "hidden" : undefined,
1409 }}
1410 >
1411 <svg
1412 viewBox="0 0 30 10"
1413 preserveAspectRatio="none"
1414 width={width}
1415 height={height}
1416 {...arrowProps}
1417 className={cn("block fill-popover stroke-border", className)}
1418 >
1419 {asChild ? children : <polygon points="0,0 30,0 15,10" />}
1420 </svg>
1421 </span>
1422 );
1423}
1424
1425function TourHeader(props: DivProps) {
1426 const { asChild, className, ...headerProps } = props;
1427
1428 const context = useTourContext(HEADER_NAME);
1429
1430 const HeaderPrimitive = asChild ? SlotPrimitive.Slot : "div";
1431
1432 return (
1433 <HeaderPrimitive
1434 data-slot="tour-header"
1435 dir={context.dir}
1436 {...headerProps}
1437 className={cn(
1438 "flex flex-col gap-1.5 text-center sm:text-left",
1439 className,
1440 )}
1441 />
1442 );
1443}
1444
1445function TourTitle(props: DivProps) {
1446 const { asChild, className, ...titleProps } = props;
1447
1448 const context = useTourContext(TITLE_NAME);
1449
1450 const TitlePrimitive = asChild ? SlotPrimitive.Slot : "div";
1451
1452 return (
1453 <TitlePrimitive
1454 data-slot="tour-title"
1455 dir={context.dir}
1456 {...titleProps}
1457 className={cn(
1458 "font-semibold text-lg leading-none tracking-tight",
1459 className,
1460 )}
1461 />
1462 );
1463}
1464
1465function TourDescription(props: DivProps) {
1466 const { asChild, className, ...descriptionProps } = props;
1467
1468 const context = useTourContext(DESCRIPTION_NAME);
1469
1470 const DescriptionPrimitive = asChild ? SlotPrimitive.Slot : "div";
1471
1472 return (
1473 <DescriptionPrimitive
1474 data-slot="tour-description"
1475 dir={context.dir}
1476 {...descriptionProps}
1477 className={cn("text-muted-foreground text-sm", className)}
1478 />
1479 );
1480}
1481
1482interface TourCloseProps extends React.ComponentProps<"button"> {
1483 asChild?: boolean;
1484}
1485
1486function TourClose(props: TourCloseProps) {
1487 const {
1488 asChild,
1489 className,
1490 onClick: onClickProp,
1491 ...closeButtonProps
1492 } = props;
1493
1494 const store = useStoreContext(CLOSE_NAME);
1495
1496 const onClick = React.useCallback(
1497 (event: React.MouseEvent<CloseElement>) => {
1498 onClickProp?.(event);
1499 if (event.defaultPrevented) return;
1500
1501 store.setState("open", false);
1502 },
1503 [store, onClickProp],
1504 );
1505
1506 const ClosePrimitive = asChild ? SlotPrimitive.Slot : "button";
1507
1508 return (
1509 <ClosePrimitive
1510 type="button"
1511 aria-label="Close tour"
1512 className={cn(
1513 "absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-hidden focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
1514 className,
1515 )}
1516 onClick={onClick}
1517 {...closeButtonProps}
1518 >
1519 <X className="size-4" />
1520 </ClosePrimitive>
1521 );
1522}
1523
1524function TourPrev(props: React.ComponentProps<typeof Button>) {
1525 const { children, onClick: onClickProp, ...prevButtonProps } = props;
1526
1527 const store = useStoreContext(PREV_NAME);
1528 const value = useStore((state) => state.value);
1529
1530 const onClick = React.useCallback(
1531 (event: React.MouseEvent<PrevElement>) => {
1532 onClickProp?.(event);
1533 if (event.defaultPrevented) return;
1534
1535 if (value > 0) {
1536 store.setState("value", value - 1);
1537 }
1538 },
1539 [value, store, onClickProp],
1540 );
1541
1542 return (
1543 <Button
1544 type="button"
1545 aria-label="Previous step"
1546 data-slot="tour-prev"
1547 variant="outline"
1548 {...prevButtonProps}
1549 onClick={onClick}
1550 disabled={value === 0}
1551 >
1552 {children ?? (
1553 <>
1554 <ChevronLeft />
1555 Previous
1556 </>
1557 )}
1558 </Button>
1559 );
1560}
1561
1562function TourNext(props: React.ComponentProps<typeof Button>) {
1563 const { children, onClick: onClickProp, ...nextButtonProps } = props;
1564 const store = useStoreContext(NEXT_NAME);
1565 const value = useStore((state) => state.value);
1566 const steps = useStore((state) => state.steps);
1567
1568 const isLastStep = value === steps.length - 1;
1569
1570 const onClick = React.useCallback(
1571 (event: React.MouseEvent<NextElement>) => {
1572 onClickProp?.(event);
1573 if (event.defaultPrevented) return;
1574
1575 store.setState("value", value + 1);
1576 },
1577 [value, store, onClickProp],
1578 );
1579
1580 return (
1581 <Button
1582 type="button"
1583 aria-label="Next step"
1584 data-slot="tour-next"
1585 {...nextButtonProps}
1586 onClick={onClick}
1587 >
1588 {children ?? (
1589 <>
1590 {isLastStep ? "Finish" : "Next"}
1591 {!isLastStep && <ChevronRight />}
1592 </>
1593 )}
1594 </Button>
1595 );
1596}
1597
1598function TourSkip(props: React.ComponentProps<typeof Button>) {
1599 const { children, onClick: onClickProp, ...skipButtonProps } = props;
1600
1601 const store = useStoreContext(SKIP_NAME);
1602
1603 const onClick = React.useCallback(
1604 (event: React.MouseEvent<SkipElement>) => {
1605 onClickProp?.(event);
1606 if (event.defaultPrevented) return;
1607
1608 store.setState("open", false);
1609 },
1610 [store, onClickProp],
1611 );
1612
1613 return (
1614 <Button
1615 type="button"
1616 aria-label="Skip tour"
1617 data-slot="tour-skip"
1618 variant="outline"
1619 {...skipButtonProps}
1620 onClick={onClick}
1621 >
1622 {children ?? "Skip"}
1623 </Button>
1624 );
1625}
1626
1627interface TourStepCounterProps extends DivProps {
1628 format?: (current: number, total: number) => string;
1629}
1630
1631function TourStepCounter(props: TourStepCounterProps) {
1632 const {
1633 format = (current, total) => `${current} / ${total}`,
1634 asChild,
1635 className,
1636 children,
1637 ...stepCounterProps
1638 } = props;
1639
1640 const value = useStore((state) => state.value);
1641 const steps = useStore((state) => state.steps);
1642
1643 const StepCounterPrimitive = asChild ? SlotPrimitive.Slot : "div";
1644
1645 return (
1646 <StepCounterPrimitive
1647 data-slot="tour-step-counter"
1648 {...stepCounterProps}
1649 className={cn("text-muted-foreground text-sm", className)}
1650 >
1651 {children ?? format(value + 1, steps.length)}
1652 </StepCounterPrimitive>
1653 );
1654}
1655
1656function TourFooter(props: DivProps) {
1657 const { asChild, className, ref, ...footerProps } = props;
1658
1659 const stepContext = useStepContext(FOOTER_NAME);
1660 const hasDefaultFooter = React.useContext(DefaultFooterContext);
1661 const context = useTourContext(FOOTER_NAME);
1662
1663 const composedRef = useComposedRefs(
1664 ref,
1665 hasDefaultFooter ? undefined : stepContext.onFooterChange,
1666 );
1667
1668 const FooterPrimitive = asChild ? SlotPrimitive.Slot : "div";
1669
1670 return (
1671 <FooterPrimitive
1672 data-slot="tour-footer"
1673 dir={context.dir}
1674 {...footerProps}
1675 ref={composedRef}
1676 className={cn(
1677 "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
1678 className,
1679 )}
1680 />
1681 );
1682}
1683
1684export {
1685 Tour,
1686 TourArrow,
1687 TourClose,
1688 TourDescription,
1689 TourFooter,
1690 TourHeader,
1691 TourNext,
1692 TourPortal,
1693 TourPrev,
1694 type TourProps,
1695 TourSkip,
1696 TourSpotlight,
1697 TourSpotlightRing,
1698 TourStep,
1699 TourStepCounter,
1700 TourTitle,
1701};
1702