Shadcn Tour
A guided product tour that walks users through your interface one step at a time. Each step points a popover at an element, dims the rest of the page with a spotlight and can wait until the user clicks the target. Progress can be saved to local storage, arrow keys move between steps and focus returns to where it was when the tour closes.
Installation
npx shadcn@latest add @shadcnuikit/tour1
This adds components/ui/tour.tsx and a demo file. Set up the registry once as described in Shadcn CLI. Tour is free and installs without an API key.
Manual installation
Install the dependencies:
npm install @ui-sdk/core@beta @ui-sdk/react@beta lucide-react
Add the shadcn/ui components it uses:
npx shadcn@latest add button
Copy the source into components/ui/tour.tsx:
"use client";
import * as React from "react";import { createPortal } from "react-dom";import { announce, bindLayer, createChange, createController, createLocalStorage, definePrimitive, isRTL, position, type ChangeDetails, type PositionOptions, type ValueStorage,} from "@ui-sdk/core";import { createParts } from "@ui-sdk/react/primitive";import { ArrowLeftIcon, ArrowRightIcon, XIcon } from "lucide-react";
import { Button } from "@/components/ui/button";import { cn } from "@/lib/utils";
type TourTarget = string | (() => Element | null | undefined) | { current: Element | null };
type TourAdvanceOn = { event?: string; target?: TourTarget; when?: (event: Event) => boolean; delay?: number;};
type TourStep = { id: string; target?: TourTarget; title?: React.ReactNode; description?: React.ReactNode; side?: PositionOptions["side"]; align?: PositionOptions["align"]; padding?: number; radius?: number; interactive?: boolean; backdrop?: boolean; arrow?: boolean; advanceOn?: TourAdvanceOn; initialFocus?: "content" | "target"; meta?: Record<string, unknown>;};
type TourStatus = "idle" | "running" | "completed" | "skipped" | "dismissed";
// None of these step reasons are in the shared vocabulary except "imperative" and "restore".type TourStepChangeReason = | "start" | "next-press" | "prev-press" | "dot-press" | "arrow-key" | "target-action" | "imperative" | "restore";
type TourOpenChangeReason = | "trigger-press" | "escape-key" | "outside-press" | "close-press" | "skip-press" | "finish-press" | "imperative";
type TourController = { start: (stepId?: string) => void; next: () => void; prev: () => void; goTo: (stepId: string) => void; skip: () => void; finish: () => void; close: () => void; reset: () => void;};
type TourOptions = { steps?: TourStep[]; open?: boolean; defaultOpen?: boolean; onOpenChange?: (open: boolean, details: ChangeDetails<TourOpenChangeReason>) => void; step?: string | null; defaultStep?: string | null; onStepChange?: (step: string | null, details: ChangeDetails<TourStepChangeReason>) => void; onStatusChange?: (status: TourStatus, details: ChangeDetails<TourOpenChangeReason | "start" | "reset">) => void; storageKey?: string; autoStart?: boolean; resume?: boolean; spotlightPadding?: number; spotlightRadius?: number; interactive?: boolean; closeOnEscape?: boolean; closeOnInteractOutside?: boolean; keyboardNavigation?: boolean; targetTimeout?: number; controller?: TourController;};
type TourState = { steps: TourStep[]; open: boolean; step: string | null; status: TourStatus; ready: boolean; anchored: boolean; version: number; persisted: string | null; padding: number; radius: number; interactive: boolean; closeOnEscape: boolean; closeOnInteractOutside: boolean; keyboardNavigation: boolean;};
const focusableSelector = 'a[href], button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';
function indexOf(state: TourState) { return state.steps.findIndex((step) => step.id === state.step);}
function currentStep(state: TourState) { return state.steps[indexOf(state)];}
function isInteractive(state: TourState, step = currentStep(state)) { return !!step && (step.interactive ?? (!!step.advanceOn || state.interactive));}
function isWaiting(state: TourState) { return !!currentStep(state)?.advanceOn;}
function isDone(persisted: string | null) { return persisted === "completed" || persisted === "skipped";}
function isEditable(target: EventTarget | null) { return ( target instanceof HTMLElement && (target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName)) );}
function trackRect( get: () => Element | null | undefined, write: (rect: DOMRect | null) => void, extra: () => string = () => "",) { let frame = 0; let last = ""; const loop = () => { const rect = get()?.getBoundingClientRect() ?? null; const key = rect ? `${rect.x}|${rect.y}|${rect.width}|${rect.height}|${extra()}` : ""; if (key !== last) { last = key; write(rect); } frame = requestAnimationFrame(loop); }; loop(); return () => cancelAnimationFrame(frame);}
const tour = definePrimitive({ name: "tour", options: { steps: "value", open: "boolean", defaultOpen: "boolean", onOpenChange: "callback", step: "string", defaultStep: "string", onStepChange: "callback", onStatusChange: "callback", storageKey: "string", autoStart: "boolean", resume: "boolean", spotlightPadding: "number", spotlightRadius: "number", interactive: "boolean", closeOnEscape: "boolean", closeOnInteractOutside: "boolean", keyboardNavigation: "boolean", targetTimeout: "number", controller: "value", }, controlled: ["open", "step"], state: (options: TourOptions): TourState => ({ steps: options.steps ?? [], open: options.open ?? options.defaultOpen ?? false, step: options.step ?? options.defaultStep ?? options.steps?.[0]?.id ?? null, status: "idle", ready: false, anchored: false, version: 0, persisted: null, padding: options.spotlightPadding ?? 6, radius: options.spotlightRadius ?? 10, interactive: options.interactive ?? false, closeOnEscape: options.closeOnEscape ?? true, closeOnInteractOutside: options.closeOnInteractOutside ?? false, keyboardNavigation: options.keyboardNavigation ?? true, }), sync: (options) => ({ steps: options.steps ?? [], ...(options.open === undefined ? {} : { open: options.open }), ...(options.step === undefined ? {} : { step: options.step }), padding: options.spotlightPadding ?? 6, radius: options.spotlightRadius ?? 10, interactive: options.interactive ?? false, closeOnEscape: options.closeOnEscape ?? true, closeOnInteractOutside: options.closeOnInteractOutside ?? false, keyboardNavigation: options.keyboardNavigation ?? true, }), api: (context) => { const { store } = context; const change = createChange(context); let storage: ValueStorage | null = null; let target: HTMLElement | null = null; let returnFocus: HTMLElement | null = null; let active = { open: false, step: null as string | null }; let stopStep: (() => void) | undefined;
const storageFor = () => { const key = context.options().storageKey; if (!key || typeof window === "undefined") return null; if (!storage || storage.id !== key) storage = createLocalStorage(key); return storage; };
const persist = (value: string | null) => { const saved = storageFor(); if (!saved) return; if (value === null) saved.remove(); else saved.set(value); store.set({ persisted: value }); };
const resolve = (value: TourTarget | undefined): HTMLElement | null => { if (!value) return null; if (typeof value === "string") { const root = context.element("root"); return (root?.querySelector<HTMLElement>(value) ?? (typeof document === "undefined" ? null : document.querySelector<HTMLElement>(value))) as HTMLElement | null; } const el = typeof value === "function" ? value() : value.current; return el instanceof HTMLElement ? el : null; };
const setStatus = (status: TourStatus, reason: TourOpenChangeReason | "start" | "reset", event?: Event) => { if (store.get().status !== status) change("status", status, { reason, event }); };
const activate = (step: TourStep) => { let frame = 0; let timer: ReturnType<typeof setTimeout> | undefined; const cleanups: (() => void)[] = []; const began = Date.now(); const timeout = context.options().targetTimeout ?? 1500;
const attempt = () => { const el = resolve(step.target); if (step.target && !el && Date.now() - began < timeout) { if (store.get().ready) store.set({ ready: false }); frame = requestAnimationFrame(attempt); return; } target = el; if (el) { const rect = el.getBoundingClientRect(); const visible = rect.top >= 0 && rect.bottom <= window.innerHeight && rect.left >= 0 && rect.right <= window.innerWidth; if (!visible) el.scrollIntoView({ block: "center", inline: "nearest", behavior: "smooth" }); } store.set({ ready: true, anchored: !!el, version: store.get().version + 1 });
const advance = step.advanceOn; const node = advance ? (resolve(advance.target) ?? el) : null; if (advance && node) { const type = advance.event ?? "click"; const handler = (event: Event) => { if (advance.when && !advance.when(event)) return; clearTimeout(timer); timer = setTimeout(() => { const state = store.get(); if (state.open && state.step === step.id) api.next(event, "target-action"); }, advance.delay ?? 0); }; node.addEventListener(type, handler); cleanups.push(() => node.removeEventListener(type, handler)); } }; attempt();
return () => { cancelAnimationFrame(frame); clearTimeout(timer); cleanups.forEach((cleanup) => cleanup()); }; };
const react = () => { const state = store.get(); if (state.open === active.open && state.step === active.step) return; const wasOpen = active.open; active = { open: state.open, step: state.step }; stopStep?.(); stopStep = undefined;
if (!state.open) { target = null; store.set({ ready: false, anchored: false }); const back = returnFocus?.isConnected ? returnFocus : context.element("trigger"); returnFocus = null; requestAnimationFrame(() => { const focused = document.activeElement; if (back?.isConnected && (!focused || focused === document.body)) back.focus({ preventScroll: true }); }); return; }
if (!wasOpen && typeof document !== "undefined") { const focused = document.activeElement; returnFocus = focused instanceof HTMLElement && focused !== document.body ? focused : null; }
const step = currentStep(state); if (!step) { if (state.steps[0]) change("step", state.steps[0].id, { reason: "imperative" }); return; } if (state.status !== "running") setStatus("running", "start"); persist(`step:${step.id}`); stopStep = activate(step); };
const goTo = (id: string, reason: TourStepChangeReason, event?: Event) => { const state = store.get(); const index = state.steps.findIndex((step) => step.id === id); if (index === -1 || id === state.step) return false; const moved = change("step", id, { reason, event }); if (moved && reason !== "start") { announce(`Step ${index + 1} of ${state.steps.length}`); } return moved; };
const api = { target: () => target, current: () => currentStep(store.get()), start(stepId?: string, event?: Event) { const state = store.get(); if (!state.steps.length) return; const saved = storageFor()?.get() ?? null; const resumeFrom = context.options().resume !== false && saved?.startsWith("step:") ? saved.slice(5) : undefined; const id = [stepId, resumeFrom, state.steps[0].id].find( (value) => value && state.steps.some((step) => step.id === value), )!; if (id !== state.step) change("step", id, { reason: "start", event }); setStatus("running", "start", event); change("open", true, { reason: event ? "trigger-press" : "imperative", event }); }, next(event?: Event, reason: TourStepChangeReason = "next-press") { const state = store.get(); if (!state.open) return; if (reason !== "target-action" && isWaiting(state)) return; const index = indexOf(state); const following = state.steps[index + 1]; if (!following) return api.finish(event); goTo(following.id, reason, event); }, prev(event?: Event, reason: TourStepChangeReason = "prev-press") { const state = store.get(); const previous = state.steps[indexOf(state) - 1]; if (state.open && previous) goTo(previous.id, reason, event); }, goTo(stepId: string, event?: Event) { goTo(stepId, event ? "dot-press" : "imperative", event); }, canGoTo(state: TourState, stepId: string) { const from = indexOf(state); const to = state.steps.findIndex((step) => step.id === stepId); if (to <= from) return to !== -1; return !state.steps.slice(from, to).some((step) => step.advanceOn); }, finish(event?: Event) { persist("completed"); setStatus("completed", "finish-press", event); change("open", false, { reason: event ? "finish-press" : "imperative", event }); }, skip(event?: Event) { persist("skipped"); setStatus("skipped", "skip-press", event); change("open", false, { reason: event ? "skip-press" : "imperative", event }); }, close(reason: TourOpenChangeReason = "imperative", event?: Event) { if (!store.get().open) return; if (change("open", false, { reason, event })) setStatus("dismissed", reason, event); }, reset() { persist(null); setStatus("idle", "reset"); const first = store.get().steps[0]; if (first) change("step", first.id, { reason: "imperative" }); }, restore() { const saved = storageFor()?.get() ?? null; store.set({ persisted: saved }); const options = context.options(); if (options.autoStart && !isDone(saved) && !store.get().open) { requestAnimationFrame(() => api.start()); } react(); }, keydown(event: KeyboardEvent, el: HTMLElement) { const state = store.get(); if (!state.open || event.defaultPrevented) return; if (event.key === "Tab" && !isInteractive(state) && el.contains(document.activeElement)) { const items = [...el.querySelectorAll<HTMLElement>(focusableSelector)]; if (!items.length) return event.preventDefault(); const first = items[0]; const last = items[items.length - 1]; const focused = document.activeElement; if (event.shiftKey && (focused === first || focused === el)) { event.preventDefault(); last.focus(); } else if (!event.shiftKey && focused === last) { event.preventDefault(); first.focus(); } return; } if (!state.keyboardNavigation || isEditable(event.target)) return; const inside = el.contains(event.target as Node) || event.target === document.body; if (!inside) return; const forward = isRTL(el) ? "ArrowLeft" : "ArrowRight"; const backward = isRTL(el) ? "ArrowRight" : "ArrowLeft"; if (event.key === forward) { event.preventDefault(); api.next(event, "arrow-key"); } else if (event.key === backward) { event.preventDefault(); api.prev(event, "arrow-key"); } }, };
context.onDestroy(store.subscribe(react)); context.onDestroy(() => stopStep?.());
return api; }, slots: (slot) => ({ root: slot< {}, { open: boolean; status: TourStatus; step: string | null; index: number; total: number; persisted: string | null; done: boolean } >({ state: (state) => ({ open: state.open, status: state.status, step: state.step, index: indexOf(state), total: state.steps.length, persisted: state.persisted, done: isDone(state.persisted), }), attrs: (state) => ({ "data-open": state.open ? "" : undefined, "data-status": state.status, }), bind: (_el, part) => { part.api.restore(); }, }), trigger: slot({ attrs: (state) => ({ type: "button", "aria-haspopup": "dialog", "aria-expanded": String(state.open), }), press: ({ api }, event) => api.start(undefined, event), }), backdrop: slot({ present: (state) => state.open && state.ready && currentStep(state)?.backdrop !== false, attrs: (state) => ({ "aria-hidden": "true", "data-anchored": state.anchored ? "" : undefined, "data-interactive": isInteractive(state) ? "" : undefined, }), bind: (el, part) => trackRect( () => (isInteractive(part.store.get()) ? part.api.target() : null), (rect) => { const state = part.store.get(); const p = currentStep(state)?.padding ?? state.padding; el.style.clipPath = rect ? `polygon(evenodd, 0 0, 100% 0, 100% 100%, 0 100%, 0 0, ${rect.left - p}px ${rect.top - p}px, ${rect.right + p}px ${rect.top - p}px, ${rect.right + p}px ${rect.bottom + p}px, ${rect.left - p}px ${rect.bottom + p}px, ${rect.left - p}px ${rect.top - p}px)` : ""; }, () => { const state = part.store.get(); return `${currentStep(state)?.padding ?? state.padding}`; }, ), }), spotlight: slot({ present: (state) => state.open && state.ready && state.anchored && currentStep(state)?.backdrop !== false, attrs: (state) => ({ "aria-hidden": "true", "data-interactive": isInteractive(state) ? "" : undefined, }), bind: (el, part) => trackRect( () => part.api.target(), (rect) => { if (!rect) return; const state = part.store.get(); const step = currentStep(state); const p = step?.padding ?? state.padding; el.style.setProperty("--tour-spotlight-x", `${rect.left - p}px`); el.style.setProperty("--tour-spotlight-y", `${rect.top - p}px`); el.style.setProperty("--tour-spotlight-width", `${rect.width + p * 2}px`); el.style.setProperty("--tour-spotlight-height", `${rect.height + p * 2}px`); el.style.setProperty("--tour-spotlight-radius", `${step?.radius ?? state.radius}px`); }, () => { const state = part.store.get(); const step = currentStep(state); return `${step?.padding ?? state.padding}|${step?.radius ?? state.radius}`; }, ), }), content: slot< {}, { index: number; total: number; step: string | null; isFirst: boolean; isLast: boolean; anchored: boolean; waiting: boolean } >({ role: "dialog", present: (state) => state.open && state.ready, state: (state) => { const index = indexOf(state); return { index, total: state.steps.length, step: state.step, isFirst: index === 0, isLast: index === state.steps.length - 1, anchored: state.anchored, waiting: isWaiting(state), }; }, attrs: (state, part) => ({ tabindex: "-1", "aria-labelledby": `${part.id}-title`, "aria-describedby": `${part.id}-description`, "data-anchored": state.anchored ? "" : undefined, "data-waiting": isWaiting(state) ? "" : undefined, "data-step": state.step ?? undefined, }), bind: (el, part) => { let version = -1; let stopPosition: (() => void) | undefined; const clear = () => { stopPosition?.(); stopPosition = undefined; for (const name of ["position", "inset", "margin", "left", "top", "right", "bottom"]) { el.style.removeProperty(name); } }; const update = () => { const state = part.store.get(); if (state.version === version) return; version = state.version; clear(); const step = currentStep(state); const anchor = part.api.target(); if (anchor && step) { stopPosition = position(anchor, el, () => { const latest = part.store.get(); const now = currentStep(latest) ?? step; return { side: now.side ?? "bottom", align: now.align ?? "center", sideOffset: (now.padding ?? latest.padding) + 10, collisionPadding: 12, arrow: now.arrow === false ? null : () => el.querySelector<HTMLElement>("[data-slot=tour-arrow]"), arrowPadding: 12, }; }); } requestAnimationFrame(() => { if (step?.initialFocus === "target" && anchor) { const field = anchor.matches(focusableSelector) ? anchor : anchor.querySelector<HTMLElement>(focusableSelector); (field ?? anchor).focus({ preventScroll: true }); } else if (!el.contains(document.activeElement)) el.focus({ preventScroll: true }); }); }; update(); const unsubscribe = part.store.subscribe(update); const layer = bindLayer(el, { contains: (node) => !!part.api.target()?.contains(node), onDismiss: (reason, event) => { const state = part.store.get(); if (reason === "escape-key" && state.closeOnEscape) part.api.close("escape-key", event); if (reason === "outside-press" && state.closeOnInteractOutside) part.api.close("outside-press", event); }, }); const onKeydown = (event: KeyboardEvent) => part.api.keydown(event, el); document.addEventListener("keydown", onKeydown); return () => { unsubscribe(); layer(); clear(); document.removeEventListener("keydown", onKeydown); }; }, }), arrow: slot({ present: (state) => state.anchored && currentStep(state)?.arrow !== false, attrs: () => ({ "aria-hidden": "true" }), }), title: slot({ attrs: (_state, part) => ({ id: `${part.id}-title` }), }), description: slot({ attrs: (_state, part) => ({ id: `${part.id}-description` }), }), progress: slot<{}, { index: number; total: number }>({ state: (state) => ({ index: indexOf(state), total: state.steps.length }), }), dots: slot({ attrs: () => ({ "aria-label": "Tour steps" }), role: "group", }), dot: slot<{ value: string }>({ props: { value: "string" }, attrs: (state, part) => { const index = state.steps.findIndex((step) => step.id === part.key); const current = indexOf(state); return { type: "button", "aria-label": `Go to step ${index + 1}`, "aria-current": index === current ? "step" : undefined, "aria-disabled": part.api.canGoTo(state, part.key) ? undefined : "true", "data-active": index === current ? "" : undefined, "data-complete": index < current ? "" : undefined, }; }, press: ({ api, key, store }, event) => { if (api.canGoTo(store.get(), key)) api.goTo(key, event); }, }), prev: slot({ present: (state) => indexOf(state) > 0, attrs: () => ({ type: "button" }), press: ({ api }, event) => api.prev(event), }), next: slot<{}, { isLast: boolean; waiting: boolean }>({ state: (state) => ({ isLast: indexOf(state) === state.steps.length - 1, waiting: isWaiting(state), }), attrs: (state) => ({ type: "button", "aria-disabled": isWaiting(state) ? "true" : undefined, }), press: ({ api }, event) => api.next(event), }), skip: slot({ present: (state) => indexOf(state) < state.steps.length - 1, attrs: () => ({ type: "button" }), press: ({ api }, event) => api.skip(event), }), close: slot({ attrs: () => ({ type: "button", "aria-label": "Close tour" }), press: ({ api }, event) => api.close("close-press", event), }), }), agent: { actions: ["start", "next", "prev", "goTo", "skip", "finish", "close", "reset"] },});
const Parts = createParts(tour, { root: "div", trigger: "button", backdrop: "div", spotlight: "div", content: "div", arrow: "div", title: "h2", description: "div", progress: "span", dots: "div", dot: "button", prev: "button", next: "button", skip: "button", close: "button",});
function createTourController() { return createController<TourController>();}
type PartClassName<T> = Omit<React.ComponentProps<T extends React.ElementType ? T : never>, "className"> & { className?: string;};
type ButtonStyleProps = Pick<React.ComponentProps<typeof Button>, "variant" | "size">;
type TourStepContextValue = { step: TourStep | undefined; index: number; total: number; isFirst: boolean; isLast: boolean; anchored: boolean; waiting: boolean;};
const TourStepsContext = React.createContext<TourStep[]>([]);const TourCurrentContext = React.createContext<TourStepContextValue | null>(null);
function useTourStep() { return React.useContext(TourCurrentContext);}
function usePortal() { const [container, setContainer] = React.useState<HTMLElement | null>(null); React.useEffect(() => setContainer(document.body), []); return container;}
function Tour({ steps, ...props }: PartClassName<typeof Parts.Root>) { return ( <TourStepsContext.Provider value={steps ?? []}> <Parts.Root steps={steps} {...props} /> </TourStepsContext.Provider> );}
function TourTrigger({ variant = "outline", size = "default", ...props}: PartClassName<typeof Parts.Trigger> & ButtonStyleProps) { return <Parts.Trigger render={<Button variant={variant} size={size} />} {...props} />;}
function TourOverlay({ className }: { className?: string }) { const container = usePortal(); if (!container) return null; return createPortal( <> <Parts.Backdrop className={cn( "animate-in fade-in-0 fixed inset-0 z-50 bg-black/40 duration-200 data-[anchored]:bg-transparent", className, )} /> <Parts.Spotlight className={cn( "pointer-events-none fixed top-(--tour-spotlight-y) left-(--tour-spotlight-x) z-50 h-(--tour-spotlight-height) w-(--tour-spotlight-width) rounded-(--tour-spotlight-radius) ring-[200vmax] ring-black/40 transition-[top,left,width,height,border-radius] duration-300 ease-out motion-reduce:transition-none", "after:ring-ring/60 after:absolute after:inset-0 after:rounded-[inherit] after:ring-2", )} /> </>, container, );}
function TourContent({ className, children, ...props}: Omit<PartClassName<typeof Parts.Content>, "children"> & { children?: React.ReactNode | ((context: TourStepContextValue) => React.ReactNode);}) { const steps = React.useContext(TourStepsContext); const container = usePortal(); if (!container) return null; return createPortal( <Parts.Content className={cn( "bg-popover text-popover-foreground ring-foreground/10 fixed z-51 flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-3 rounded-xl p-4 text-sm shadow-lg ring-1 outline-none", "animate-in fade-in-0 zoom-in-95 duration-200", "not-data-[anchored]:top-1/2 not-data-[anchored]:left-1/2 not-data-[anchored]:-translate-x-1/2 not-data-[anchored]:-translate-y-1/2", className, )} {...props} > {(state) => { const value: TourStepContextValue = { step: steps[state.index], index: state.index, total: state.total, isFirst: state.isFirst, isLast: state.isLast, anchored: state.anchored, waiting: state.waiting, }; return ( <TourCurrentContext.Provider value={value}> {typeof children === "function" ? children(value) : children} </TourCurrentContext.Provider> ); }} </Parts.Content>, container, );}
function TourArrow({ className, ...props }: PartClassName<typeof Parts.Arrow>) { return ( <Parts.Arrow className={cn( "bg-popover absolute size-2.5 rotate-45", "data-[side=bottom]:-top-[5px] data-[side=bottom]:shadow-[-1px_-1px_0_0_var(--border)]", "data-[side=top]:-bottom-[5px] data-[side=top]:shadow-[1px_1px_0_0_var(--border)]", "data-[side=left]:-right-[5px] data-[side=left]:shadow-[1px_-1px_0_0_var(--border)]", "data-[side=right]:-left-[5px] data-[side=right]:shadow-[-1px_1px_0_0_var(--border)]", className, )} {...props} /> );}
function TourHeader({ className, ...props }: React.ComponentProps<"div">) { return <div data-slot="tour-header" className={cn("flex items-start gap-2", className)} {...props} />;}
function TourTitle({ className, children, ...props }: PartClassName<typeof Parts.Title>) { const current = useTourStep(); return ( <Parts.Title className={cn("flex-1 text-base leading-snug font-medium", className)} {...props}> {children ?? current?.step?.title} </Parts.Title> );}
function TourDescription({ className, children, ...props }: PartClassName<typeof Parts.Description>) { const current = useTourStep(); return ( <Parts.Description className={cn("text-muted-foreground leading-relaxed", className)} {...props}> {children ?? current?.step?.description} </Parts.Description> );}
function TourProgress({ className, children, ...props }: PartClassName<typeof Parts.Progress>) { return ( <Parts.Progress className={cn("text-muted-foreground text-xs tabular-nums", className)} {...props}> {children ?? (({ index, total }) => `${index + 1} of ${total}`)} </Parts.Progress> );}
function TourDots({ className, ...props }: PartClassName<typeof Parts.Dots>) { const steps = React.useContext(TourStepsContext); return ( <Parts.Dots className={cn("flex items-center gap-1", className)} {...props}> {steps.map((step) => ( <Parts.Dot key={step.id} value={step.id} className={cn( "bg-muted-foreground/25 hover:bg-muted-foreground/50 focus-visible:ring-ring/50 h-1.5 w-1.5 rounded-full transition-all outline-none focus-visible:ring-3", "data-[complete]:bg-primary/40 data-[active]:bg-primary data-[active]:w-4 aria-disabled:pointer-events-none", )} /> ))} </Parts.Dots> );}
function TourFooter({ className, ...props }: React.ComponentProps<"div">) { return <div data-slot="tour-footer" className={cn("flex items-center gap-2", className)} {...props} />;}
function TourPrev({ children, variant = "ghost", size = "sm", ...props}: PartClassName<typeof Parts.Prev> & ButtonStyleProps) { return ( <Parts.Prev render={<Button variant={variant} size={size} />} {...props}> {children ?? ( <> <ArrowLeftIcon aria-hidden="true" className="rtl:rotate-180" /> Back </> )} </Parts.Prev> );}
function TourNext({ children, className, variant = "default", size = "sm", ...props}: PartClassName<typeof Parts.Next> & ButtonStyleProps) { return ( <Parts.Next render={<Button variant={variant} size={size} />} className={cn("aria-disabled:pointer-events-none aria-disabled:opacity-50", className)} {...props} > {children ?? (({ isLast }) => isLast ? ( "Finish" ) : ( <> Next <ArrowRightIcon aria-hidden="true" className="rtl:rotate-180" /> </> ))} </Parts.Next> );}
function TourSkip({ children, className, variant = "ghost", size = "sm", ...props}: PartClassName<typeof Parts.Skip> & ButtonStyleProps) { return ( <Parts.Skip render={<Button variant={variant} size={size} />} className={cn("text-muted-foreground", className)} {...props} > {children ?? "Skip"} </Parts.Skip> );}
function TourClose({ children, className, variant = "ghost", size = "icon-xs", ...props}: PartClassName<typeof Parts.Close> & ButtonStyleProps) { return ( <Parts.Close render={<Button variant={variant} size={size} />} className={cn("text-muted-foreground -mt-0.5 -me-1", className)} {...props} > {children ?? <XIcon aria-hidden="true" />} </Parts.Close> );}
export { Tour, TourArrow, TourClose, TourContent, TourDescription, TourDots, TourFooter, TourHeader, TourNext, TourOverlay, TourPrev, TourProgress, TourSkip, TourTitle, TourTrigger, createTourController, tour, useTourStep,};export type { TourAdvanceOn, TourController, TourOpenChangeReason, TourOptions, TourStatus, TourStep, TourStepChangeReason, TourTarget,};
Usage
import {
Tour,
TourArrow,
TourClose,
TourContent,
TourDescription,
TourDots,
TourFooter,
TourHeader,
TourNext,
TourOverlay,
TourPrev,
TourTitle,
TourTrigger,
type TourStep,
} from "@/components/ui/tour";
const steps: TourStep[] = [
{
id: "search",
target: "[data-tour=search]",
title: "Search everything",
description: "Find projects, people and files from one place.",
},
{
id: "create",
target: "[data-tour=create]",
title: "Create a project",
description: "Start a new project from scratch or from a template.",
},
];
<Tour steps={steps}>
<Button data-tour="search">Search</Button>
<Button data-tour="create">New project</Button>
<TourTrigger>Start tour</TourTrigger>
<TourOverlay />
<TourContent>
<TourArrow />
<TourHeader>
<TourTitle />
<TourClose />
</TourHeader>
<TourDescription />
<TourFooter>
<TourDots />
<TourPrev className="ms-auto" />
<TourNext />
</TourFooter>
</TourContent>
</Tour>;
Steps are plain data passed to steps. TourTitle and TourDescription show the current step's title and description when they have no children. TourOverlay and TourContent render in a portal on document.body, so they sit above the page.
A target can be a CSS selector, a ref or a function that returns an element. Selectors are looked up inside the Tour root first, then in the whole document.
Custom step content
<TourContent>
{({ step, index, total, isLast }) => (
<>
<TourTitle />
<p>
Step {index + 1} of {total}
</p>
{step?.meta?.image ? <img src={String(step.meta.image)} alt="" /> : null}
<TourNext>{isLast ? "Done" : "Continue"}</TourNext>
</>
)}
</TourContent>
TourContent takes a function as children with the current step, its index and flags. useTourStep() reads the same values from any component inside TourContent. Put your own data in a step's meta.
Examples
Placement
side and align on a step place the popover around its target. It flips when there is no room.
Centered Step
A step without a target opens in the center of the screen with a full backdrop, which suits welcome and summary steps. TourSkip ends the tour early and is hidden on the last step.
Interactive
interactive: true on a step keeps the highlighted target clickable while the rest of the page stays blocked. Set interactive on Tour to make every step interactive.
Wait for Action
advanceOn waits for an event on the target before moving on. TourNext is disabled until it happens.
Without Backdrop
backdrop: false shows the popover without dimming the page, like a tooltip. With closeOnInteractOutside, a click anywhere else closes it.
Saved Progress
storageKey saves the current step to local storage. Starting again resumes from it, and a finished or skipped tour stays done. reset() clears it.
Controller
createTourController() starts and moves the tour from anywhere, without a TourTrigger.
More layouts built with Tour, such as onboarding checklists, feature announcements and tours with media, are on the Tour components page.
API Reference
Tour
The root. Holds the steps and the tour state. Renders a div around its children.
| Prop | Type | Default | Description |
|---|---|---|---|
steps | TourStep[] | [] | The steps, in order. |
open | boolean | Whether the tour is showing. Pass it to control the tour. | |
defaultOpen | boolean | false | Whether the tour shows at first, when uncontrolled. |
onOpenChange | (open, details) => void | Runs when the tour opens or closes. details.reason is trigger-press, escape-key, outside-press, close-press, skip-press, finish-press or imperative. | |
step | string | null | The id of the current step. Pass it to control the step. | |
defaultStep | string | null | first step | The step at first, when uncontrolled. |
onStepChange | (step, details) => void | Runs when the step changes. details.reason is start, next-press, prev-press, dot-press, arrow-key, target-action or imperative. | |
onStatusChange | (status, details) => void | Runs when the status changes to idle, running, completed, skipped or dismissed. | |
storageKey | string | Saves progress to local storage under this key. | |
resume | boolean | true | Whether starting again opens the saved step. Only used with storageKey. |
autoStart | boolean | false | Starts the tour on mount, unless the saved progress says it was finished or skipped. |
spotlightPadding | number | 6 | Space in pixels between the target and the spotlight edge. |
spotlightRadius | number | 10 | Corner radius of the spotlight in pixels. |
interactive | boolean | false | Keeps every step's target clickable. A step's own interactive wins. |
closeOnEscape | boolean | true | Whether Escape closes the tour. |
closeOnInteractOutside | boolean | false | Whether a press outside the popover and the target closes the tour. |
keyboardNavigation | boolean | true | Whether the left and right arrow keys move between steps. |
targetTimeout | number | 1500 | How long in milliseconds to wait for a step's target to appear before showing the step centered. |
controller | TourController | Controls the tour from anywhere. Create one with createTourController(). | |
className | string | Classes for the root. |
The root has data-open while the tour shows and data-status with the current status.
TourStep
| Field | Type | Default | Description |
|---|---|---|---|
id | string | A unique id for the step. Required. | |
target | string, RefObject, () => Element | The element to point at. Without one, the step opens centered. | |
title | ReactNode | Shown by TourTitle. | |
description | ReactNode | Shown by TourDescription. | |
side | "top", "right", "bottom", "left" | "bottom" | Which side of the target the popover opens on. |
align | "start", "center", "end" | "center" | How the popover lines up with the target. |
padding | number | spotlightPadding | Spotlight padding for this step. |
radius | number | spotlightRadius | Spotlight radius for this step. |
interactive | boolean | Keeps the target clickable. Defaults to true for steps with advanceOn, else the root's interactive. | |
backdrop | boolean | true | Set false to show the popover without a backdrop or spotlight. |
arrow | boolean | true | Set false to hide TourArrow for this step. |
advanceOn | TourAdvanceOn | Waits for an event before moving on. See below. | |
initialFocus | "content", "target" | "content" | Where focus goes when the step opens. "target" focuses the target or the first focusable element inside it. |
meta | Record<string, unknown> | Your own data, read it with useTourStep() or the TourContent function. |
TourAdvanceOn
| Field | Type | Default | Description |
|---|---|---|---|
event | string | "click" | The DOM event to wait for, such as click, input or change. |
target | TourTarget | step target | The element to listen on, if not the step's target. |
when | (event) => boolean | Only moves on when this returns true, for example once an input has a value. | |
delay | number | 0 | Milliseconds to wait after the event before moving on. |
TourTrigger
A Button that starts the tour from the first step, or from the saved step with storageKey. Takes every Button prop.
| Prop | Type | Default | Description |
|---|---|---|---|
variant | Button variant | "outline" | The button style. |
size | Button size | "default" | The button size. |
TourOverlay
The backdrop and the spotlight around the target. Render it once inside Tour.
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | Classes for the backdrop. |
TourContent
The popover, with role="dialog". Placed next to the target, or centered for steps without one.
| Prop | Type | Default | Description |
|---|---|---|---|
children | ReactNode, (context) => ReactNode | The popover content. A function gets step, index, total, isFirst, isLast, anchored and waiting. | |
className | string | Classes for the popover. |
It has data-anchored when it points at a target, data-waiting while a step waits for an action and data-step with the step id.
TourArrow
The small arrow pointing at the target. Hidden for centered steps and steps with arrow: false. Takes className.
TourHeader and TourFooter
Plain div rows for the title and close button, and for the navigation buttons. Take every div prop.
TourTitle and TourDescription
The step's title (an h2) and description. They show the step's title and description unless you pass children, and they name and describe the dialog. Take className.
TourProgress
Shows "1 of 3" by default. Pass a function as children to change it.
| Prop | Type | Default | Description |
|---|---|---|---|
children | ReactNode, ({ index, total }) => ReactNode | "1 of 3" | The progress text. index starts at 0. |
className | string | Classes for the text. |
TourDots
A dot per step. Pressing a dot jumps to that step, except past a step that waits for an action. The active dot has data-active, earlier ones data-complete. Takes className.
TourPrev, TourNext, TourSkip and TourClose
Buttons that move through or end the tour. Each takes every Button prop and renders default content when it has no children.
| Part | Default variant | Default size | Default content | Notes |
|---|---|---|---|---|
TourPrev | "ghost" | "sm" | Back with an arrow | Hidden on the first step. |
TourNext | "default" | "sm" | Next with an arrow, Finish on the last step | Children can be a function of { isLast, waiting }. Disabled while a step waits for an action. Finishing sets status to completed. |
TourSkip | "ghost" | "sm" | Skip | Hidden on the last step. Sets status to skipped. |
TourClose | "ghost" | "icon-xs" | An X icon | Labelled "Close tour". Sets status to dismissed. |
createTourController
const [controller] = React.useState(() => createTourController());
<Tour steps={steps} controller={controller}>...</Tour>;
controller.start();
controller.start("billing");
controller.next();
controller.prev();
controller.goTo("team");
controller.skip();
controller.finish();
controller.close();
controller.reset();
reset() clears saved progress, sets the status back to idle and moves to the first step.
useTourStep
Returns { step, index, total, isFirst, isLast, anchored, waiting } for the current step, or null outside TourContent.
Keyboard
| Key | Action |
|---|---|
ArrowRight | Moves to the next step. Flips to ArrowLeft in right to left layouts. |
ArrowLeft | Moves to the previous step. Flips to ArrowRight in right to left layouts. |
Escape | Closes the tour, unless closeOnEscape is false. |
Tab, Shift+Tab | Moves between the buttons in the popover. Focus stays inside it, unless the step is interactive. |
Enter, Space | Presses the focused button. |
Arrow keys work while focus is in the popover or on the page body, never while typing in a field. Turn them off with keyboardNavigation={false}.
Accessibility
- The popover is a dialog named by
TourTitleand described byTourDescription. It takes focus when each step opens. - Focus returns to the element that was focused before the tour started, or to
TourTrigger, when the tour closes. - Each step change announces "Step 2 of 3" to screen readers.
TourTriggerhasaria-haspopup="dialog"andaria-expanded. Dots are a group named "Tour steps", each labelled "Go to step 2" witharia-currenton the active one.- The backdrop and spotlight are
aria-hidden. Targets that are off screen scroll into view. - Give
TourContentanaria-labelwhen your steps have notitle.
For AI Agents
When to use
- First run onboarding that points at real parts of your interface.
- Announcing a new feature next to where it lives.
- Guided tasks where the user has to click or type to move on, with
advanceOn.
When not to use
- A single hint on one element. Use a Tooltip or a Popover.
- A multi step form or setup wizard. Use a Stepper.
- An onboarding checklist that stays on the page. Build it with normal components and start a tour from each item.
Agent notes
- Import from
@/components/ui/tour. The exports areTour,TourTrigger,TourOverlay,TourContent,TourArrow,TourHeader,TourTitle,TourClose,TourDescription,TourProgress,TourDots,TourFooter,TourPrev,TourNext,TourSkip,createTourController,useTourStepandtour, plus theTourStep,TourAdvanceOn,TourController,TourOptions,TourStatus,TourTarget,TourOpenChangeReasonandTourStepChangeReasontypes. - Steps are data, not JSX. Mark targets with a
data-tourattribute and point at them with a selector like"[data-tour=search]". - Every step needs a unique
id.step,defaultStep,goTo()andstart()take step ids, not indexes. - Always render
TourOverlayandTourContentinsideTour. WithoutTourOverlaythere is no spotlight. - The file is a client component. Define
stepsoutside the component or withuseMemoso they don't change on every render. - Use
storageKeywith a unique key per tour. A finished or skipped tour won'tautoStartagain untilreset().
Resources
- Markdown: /docs/components/tour.md
- Variants: Tour components, 10 free examples
- Install:
npx shadcn@latest add @shadcnuikit/tour1 - MCP: call
get_item_codewithtour1from the MCP Server - Full index for agents: llms.txt