Guided tour

An onboarding walkthrough that points at real parts of your interface. A dimmed overlay leaves a rounded cut-out around the current target, and the cut-out glides and resizes from one target to the next. A step card sits on the side with room (flipping when it would overflow) with an arrow, title, body, step dots, Back, Next and Skip; under 480px it docks to the bottom as a sheet. Targets are CSS selectors or refs, scrolled into view and re-measured on scroll and resize. Optional beacon mode starts from a pulsing dot instead of the overlay, and interactive steps let clicks pass through the cut-out and advance when the target is pressed. The card is a labelled dialog with trapped focus, arrow keys and Enter to step, Escape to end and focus returned to the launcher; the target is described by the step while active. With reduced motion the cut-out jumps instead of gliding.

Modals & overlaysComponentTailwind v4

Source

"use client";

import {
  useEffect, useId, useLayoutEffect, useRef, useState,
  type KeyboardEvent as ReactKeyboardEvent, type ReactNode, type RefObject,
} from "react";
import { createPortal } from "react-dom";
import { ArrowLeft, ArrowRight, Check, X } from "lucide-react";
import { cn } from "@/lib/utils";

export type TourPlacement = "top" | "bottom" | "left" | "right";

export interface TourStep {
  /** A CSS selector or a ref to the element this step points at. */
  target: string | RefObject<HTMLElement | null>;
  title: ReactNode;
  body: ReactNode;
  /** Preferred side for the card. It flips when there is no room. Defaults to the roomiest side. */
  placement?: TourPlacement;
  /** Let clicks reach the target through the cut-out; clicking it moves to the next step. */
  interactive?: boolean;
}

export interface GuidedTourProps {
  steps: TourStep[];
  open: boolean;
  onOpenChange: (open: boolean) => void;
  startAt?: number;
  /** Called when the last step is completed (not when the tour is skipped). */
  onFinish?: () => void;
  /** Space between the target and the edge of the cut-out, in px. */
  padding?: number;
  /** Corner radius of the cut-out, in px. */
  radius?: number;
  /** Start from a pulsing dot on the first target instead of the full overlay. */
  beacon?: boolean;
  className?: string;
}

type Box = { x: number; y: number; w: number; h: number };
type Side = TourPlacement | "dock" | "center";
type CardPos = { x: number; y: number; side: Side; arrow: number; step: number; glide: boolean };

const GLIDE_MS = 380;
const GAP = 14;
const MARGIN = 12;
const FOCUSABLE = "a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex='-1'])";
const opposite: Record<TourPlacement, TourPlacement> = { top: "bottom", bottom: "top", left: "right", right: "left" };

function resolve(target: TourStep["target"] | undefined) {
  if (!target) return null;
  if (typeof target === "string") return document.querySelector<HTMLElement>(target);
  return target.current;
}

function roundedRect({ x, y, w, h }: Box, radius: number) {
  const r = Math.max(0, Math.min(radius, w / 2, h / 2));
  return `M${x + r} ${y}H${x + w - r}A${r} ${r} 0 0 1 ${x + w} ${y + r}V${y + h - r}A${r} ${r} 0 0 1 ${x + w - r} ${y + h}`
    + `H${x + r}A${r} ${r} 0 0 1 ${x} ${y + h - r}V${y + r}A${r} ${r} 0 0 1 ${x + r} ${y}Z`;
}

const clamp = (value: number, min: number, max: number) => Math.min(Math.max(value, min), Math.max(min, max));
const mix = (a: Box, b: Box, t: number): Box => ({ x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t, w: a.w + (b.w - a.w) * t, h: a.h + (b.h - a.h) * t });
const same = (a: Box | null, b: Box | null) => !!a && !!b && Math.abs(a.x - b.x) < 0.5 && Math.abs(a.y - b.y) < 0.5 && Math.abs(a.w - b.w) < 0.5 && Math.abs(a.h - b.h) < 0.5;

function useReducedMotion() {
  const [reduce, setReduce] = useState(false);
  useEffect(() => {
    const query = window.matchMedia?.("(prefers-reduced-motion: reduce)");
    if (!query) return;
    const update = () => setReduce(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  return reduce;
}

export function GuidedTour({
  steps, open, onOpenChange, startAt = 0, onFinish, padding = 8, radius = 12, beacon = false, className,
}: GuidedTourProps) {
  const id = useId();
  const titleId = `${id}-title`;
  const bodyId = `${id}-body`;
  const reduce = useReducedMotion();
  const [mounted, setMounted] = useState(false);
  const [index, setIndex] = useState(startAt);
  const [phase, setPhase] = useState<"beacon" | "tour">(beacon ? "beacon" : "tour");
  const [box, setBox] = useState<Box | null>(null);
  const [goal, setGoal] = useState<Box | null>(null);
  const [viewport, setViewport] = useState({ w: 0, h: 0 });
  const [card, setCard] = useState<CardPos | null>(null);
  const [cardSize, setCardSize] = useState("");
  const cardRef = useRef<HTMLDivElement>(null);
  const launcher = useRef<HTMLElement | null>(null);
  const shown = useRef<Box | null>(null);
  const tween = useRef<{ from: Box; to: Box; start: number } | null>(null);
  const frame = useRef(0);

  const last = steps.length - 1;
  const current = Math.min(Math.max(index, 0), last);
  const step = steps[current];
  const active = open && phase === "tour" && !!step;
  const interactive = !!step?.interactive;

  useEffect(() => setMounted(true), []);

  // Each opening starts fresh, remembers the launcher and hands focus back to it at the end.
  useEffect(() => {
    if (!open) return;
    launcher.current = document.activeElement as HTMLElement | null;
    setIndex(startAt);
    setPhase(beacon ? "beacon" : "tour");
    shown.current = null;
    setBox(null);
    setCard(null);
    return () => {
      cancelAnimationFrame(frame.current);
      tween.current = null;
      const previous = launcher.current;
      launcher.current = null;
      if (previous?.isConnected) previous.focus({ preventScroll: true });
    };
  }, [open, startAt, beacon]);

  // Keep the newest handlers reachable from DOM listeners without re-binding them.
  const actions = useRef({ next: () => {}, back: () => {}, end: () => {} });
  actions.current = {
    next: () => {
      if (current >= last) {
        onFinish?.();
        onOpenChange(false);
      } else setIndex(current + 1);
    },
    back: () => setIndex(Math.max(0, current - 1)),
    end: () => onOpenChange(false),
  };

  // Measure the target, scroll it into view and follow it through scrolling, resizing and layout changes.
  useEffect(() => {
    if (!open || !step) return;
    const element = resolve(step.target);

    function animate(now: number) {
      const t = tween.current;
      if (!t) return;
      const p = Math.min(1, (now - t.start) / GLIDE_MS);
      const eased = 1 - Math.pow(1 - p, 3);
      const next = mix(t.from, t.to, eased);
      shown.current = next;
      setBox(next);
      if (p < 1) frame.current = requestAnimationFrame(animate);
      else tween.current = null;
    }

    function measure(glide: boolean) {
      setViewport((prev) => (prev.w === window.innerWidth && prev.h === window.innerHeight ? prev : { w: window.innerWidth, h: window.innerHeight }));
      const rect = element?.getBoundingClientRect();
      if (!rect || (rect.width === 0 && rect.height === 0)) {
        tween.current = null;
        shown.current = null;
        setGoal(null);
        setBox(null);
        return;
      }
      const next = { x: rect.left - padding, y: rect.top - padding, w: rect.width + padding * 2, h: rect.height + padding * 2 };
      setGoal((prev) => (same(prev, next) ? prev : next));
      if (tween.current) {
        tween.current.to = next;
        return;
      }
      if (glide && shown.current && !reduce && !same(shown.current, next)) {
        tween.current = { from: shown.current, to: next, start: performance.now() };
        cancelAnimationFrame(frame.current);
        frame.current = requestAnimationFrame(animate);
        return;
      }
      shown.current = next;
      setBox((prev) => (same(prev, next) ? prev : next));
    }

    if (element) {
      const rect = element.getBoundingClientRect();
      const visible = rect.top >= 0 && rect.left >= 0 && rect.bottom <= window.innerHeight && rect.right <= window.innerWidth;
      if (!visible) element.scrollIntoView({ block: "center", inline: "nearest", behavior: reduce ? "auto" : "smooth" });
    }
    measure(true);

    let pending = 0;
    const schedule = () => {
      cancelAnimationFrame(pending);
      pending = requestAnimationFrame(() => measure(false));
    };
    const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(schedule);
    if (element) observer?.observe(element);
    observer?.observe(document.documentElement);
    window.addEventListener("scroll", schedule, { capture: true, passive: true });
    window.addEventListener("resize", schedule);
    return () => {
      cancelAnimationFrame(pending);
      observer?.disconnect();
      window.removeEventListener("scroll", schedule, { capture: true });
      window.removeEventListener("resize", schedule);
    };
  }, [open, step, padding, reduce]);

  useEffect(() => () => cancelAnimationFrame(frame.current), []);

  // Place the card beside the target, preferring the requested side and flipping when it would overflow.
  useLayoutEffect(() => {
    const el = cardRef.current;
    if (!active || !el) return;
    const vw = window.innerWidth;
    const vh = window.innerHeight;
    let next: Omit<CardPos, "step" | "glide">;
    if (vw < 480) next = { x: 0, y: 0, side: "dock", arrow: 0 };
    else if (!goal) next = { x: (vw - el.offsetWidth) / 2, y: (vh - el.offsetHeight) / 2, side: "center", arrow: 0 };
    else {
      const cw = el.offsetWidth;
      const ch = el.offsetHeight;
      const room = { top: goal.y, bottom: vh - goal.y - goal.h, left: goal.x, right: vw - goal.x - goal.w };
      const fits = {
        top: room.top - GAP - ch >= MARGIN, bottom: room.bottom - GAP - ch >= MARGIN,
        left: room.left - GAP - cw >= MARGIN, right: room.right - GAP - cw >= MARGIN,
      };
      const roomiest = (Object.keys(room) as TourPlacement[]).reduce((a, b) => (room[b] > room[a] ? b : a), "bottom");
      const preferred = step.placement ?? roomiest;
      const order: TourPlacement[] = [preferred, opposite[preferred], "bottom", "top", "right", "left"];
      const side = order.find((s) => fits[s]) ?? roomiest;
      const cx = goal.x + goal.w / 2;
      const cy = goal.y + goal.h / 2;
      if (side === "top" || side === "bottom") {
        const x = clamp(cx - cw / 2, MARGIN, vw - cw - MARGIN);
        const y = side === "top" ? goal.y - GAP - ch : goal.y + goal.h + GAP;
        next = { x, y: clamp(y, MARGIN, vh - ch - MARGIN), side, arrow: clamp(cx - x, 18, cw - 18) };
      } else {
        const y = clamp(cy - ch / 2, MARGIN, vh - ch - MARGIN);
        const x = side === "left" ? goal.x - GAP - cw : goal.x + goal.w + GAP;
        next = { x: clamp(x, MARGIN, vw - cw - MARGIN), y, side, arrow: clamp(cy - y, 18, ch - 18) };
      }
    }
    // Glide only when moving to another step; resizing and scrolling follow the target instantly.
    setCard((prev) => (prev && prev.step === current && prev.side === next.side && Math.abs(prev.x - next.x) < 0.5 && Math.abs(prev.y - next.y) < 0.5 && Math.abs(prev.arrow - next.arrow) < 0.5
      ? prev
      : { ...next, step: current, glide: !!prev && prev.step !== current }));
  }, [active, goal, viewport, current, step, cardSize, mounted]);

  // The card's own size feeds placement (content, fonts and styles can change it after the first layout).
  useEffect(() => {
    const el = cardRef.current;
    if (!active || !el || typeof ResizeObserver === "undefined") return;
    const observer = new ResizeObserver(() => setCardSize(`${el.offsetWidth}x${el.offsetHeight}`));
    observer.observe(el);
    return () => observer.disconnect();
  }, [active, mounted]);

  // Focus follows the card on every step.
  useEffect(() => {
    if (active) cardRef.current?.focus({ preventScroll: true });
  }, [active, current, mounted]);

  // Keyboard: Escape ends, arrows and Enter step. Focus stays in the card unless the step is interactive.
  useEffect(() => {
    if (!open) return;
    function onKey(event: KeyboardEvent) {
      if (event.key === "Escape") {
        event.preventDefault();
        actions.current.end();
      }
    }
    function onFocusIn(event: FocusEvent) {
      const panel = cardRef.current;
      if (!active || interactive || !panel) return;
      if (event.target instanceof Node && !panel.contains(event.target)) panel.focus({ preventScroll: true });
    }
    document.addEventListener("keydown", onKey);
    document.addEventListener("focusin", onFocusIn);
    return () => {
      document.removeEventListener("keydown", onKey);
      document.removeEventListener("focusin", onFocusIn);
    };
  }, [open, active, interactive]);

  // While active the target is described by the step body; interactive steps advance when it is clicked.
  useEffect(() => {
    if (!active) return;
    const element = resolve(step.target);
    if (!element) return;
    const previous = element.getAttribute("aria-describedby");
    element.setAttribute("aria-describedby", previous ? `${previous} ${bodyId}` : bodyId);
    let timer = 0;
    const onClick = () => {
      timer = window.setTimeout(() => actions.current.next(), 0);
    };
    if (step.interactive) element.addEventListener("click", onClick);
    return () => {
      window.clearTimeout(timer);
      element.removeEventListener("click", onClick);
      if (previous) element.setAttribute("aria-describedby", previous);
      else element.removeAttribute("aria-describedby");
    };
  }, [active, step, bodyId]);

  function onCardKeyDown(event: ReactKeyboardEvent<HTMLDivElement>) {
    if (event.key === "ArrowRight" || (event.key === "Enter" && event.target === event.currentTarget)) {
      event.preventDefault();
      actions.current.next();
    } else if (event.key === "ArrowLeft") {
      event.preventDefault();
      actions.current.back();
    } else if (event.key === "Tab" && !interactive) {
      const items = Array.from(event.currentTarget.querySelectorAll<HTMLElement>(FOCUSABLE));
      if (!items.length) return;
      const first = items[0];
      const lastItem = items[items.length - 1];
      if (event.shiftKey && (document.activeElement === first || document.activeElement === event.currentTarget)) {
        event.preventDefault();
        lastItem.focus();
      } else if (!event.shiftKey && document.activeElement === lastItem) {
        event.preventDefault();
        first.focus();
      }
    }
  }

  if (!mounted || !open || !step) return null;

  // Beacon: a pulsing dot on the first target; pressing it opens the tour.
  if (phase === "beacon") {
    if (!goal) return null;
    return createPortal(
      <button
        type="button"
        aria-label="Start the tour"
        onClick={() => setPhase("tour")}
        style={{ left: goal.x + goal.w - padding - 6, top: goal.y + padding - 6 }}
        className="fixed z-[60] grid size-6 -translate-x-1/2 -translate-y-1/2 place-items-center rounded-full outline-hidden focus-visible:ring-[3px] focus-visible:ring-ring/60"
      >
        <span aria-hidden="true" className="absolute inset-0 rounded-full bg-primary/40 motion-safe:animate-ping" />
        <span aria-hidden="true" className="relative size-3 rounded-full bg-primary ring-4 ring-primary/25" />
      </button>,
      document.body,
    );
  }

  const vw = viewport.w || window.innerWidth;
  const vh = viewport.h || window.innerHeight;
  const dock = card?.side === "dock";
  const glide = !reduce && !!card?.glide && !dock && card.side !== "center";

  return createPortal(
    <div className={cn("guided-tour", className)}>
      <svg aria-hidden="true" className="pointer-events-none fixed inset-0 z-[60] h-full w-full" width={vw} height={vh}>
        <path
          d={`M0 0H${vw}V${vh}H0Z${box ? roundedRect(box, radius) : ""}`}
          fillRule="evenodd"
          className="pointer-events-auto fill-black/55 dark:fill-black/70"
        />
      </svg>
      {box && (
        <div
          aria-hidden="true"
          style={{ left: box.x, top: box.y, width: box.w, height: box.h, borderRadius: Math.min(radius, box.w / 2, box.h / 2) }}
          className={cn(
            "fixed z-[60] ring-2 ring-white/80 dark:ring-white/40",
            interactive ? "pointer-events-none" : "pointer-events-auto",
          )}
        />
      )}

      <div
        ref={cardRef}
        role="dialog"
        aria-modal={interactive ? undefined : true}
        aria-labelledby={titleId}
        aria-describedby={bodyId}
        tabIndex={-1}
        onKeyDown={onCardKeyDown}
        style={dock || !card ? undefined : { left: card.x, top: card.y }}
        className={cn(
          "fixed z-[61] rounded-xl border border-border bg-popover p-4 text-popover-foreground outline-hidden",
          "shadow-[0_18px_48px_-12px_rgb(0_0_0/0.35)]",
          dock ? "inset-x-3 bottom-3 rounded-2xl p-5" : "w-[min(340px,calc(100vw-24px))]",
          !card && "invisible left-0 top-0",
          glide && "motion-safe:transition-[left,top] motion-safe:duration-300 motion-safe:ease-[cubic-bezier(.2,.8,.2,1)]",
        )}
      >
        {card && !dock && card.side !== "center" && (
          <span
            aria-hidden="true"
            style={card.side === "top" || card.side === "bottom" ? { left: card.arrow } : { top: card.arrow }}
            className={cn(
              "absolute size-3 rotate-45 border-border bg-popover",
              card.side === "bottom" && "-top-[7px] -translate-x-1/2 border-l border-t",
              card.side === "top" && "-bottom-[7px] -translate-x-1/2 border-b border-r",
              card.side === "right" && "-left-[7px] -translate-y-1/2 border-b border-l",
              card.side === "left" && "-right-[7px] -translate-y-1/2 border-r border-t",
            )}
          />
        )}

        <div className="flex items-start justify-between gap-3">
          <p className="text-xs font-medium tabular-nums text-muted-foreground">
            Step {current + 1} of {steps.length}
          </p>
          <button
            type="button"
            aria-label="End tour"
            onClick={() => actions.current.end()}
            className="-mr-1.5 -mt-1.5 inline-flex size-7 items-center justify-center rounded-md text-muted-foreground outline-hidden hover:bg-accent hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50"
          >
            <X aria-hidden="true" className="size-4" />
          </button>
        </div>
        <h2 id={titleId} className="mt-1 text-[15px] font-semibold leading-snug tracking-tight">{step.title}</h2>
        <div id={bodyId} className="mt-1.5 text-sm leading-relaxed text-muted-foreground">{step.body}</div>

        <div className="mt-4 flex items-center gap-2">
          <ol aria-hidden="true" className="mr-auto flex items-center gap-1.5">
            {steps.map((_, i) => (
              <li
                key={i}
                className={cn(
                  "h-1.5 rounded-full transition-all duration-300",
                  i === current ? "w-4 bg-primary" : "w-1.5 bg-muted-foreground/30",
                )}
              />
            ))}
          </ol>
          {current < last && (
            <button
              type="button"
              onClick={() => actions.current.end()}
              className="h-8 rounded-md px-2.5 text-sm text-muted-foreground outline-hidden hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50"
            >
              Skip
            </button>
          )}
          {current > 0 && (
            <button
              type="button"
              aria-label="Previous step"
              onClick={() => actions.current.back()}
              className="inline-flex size-8 items-center justify-center rounded-md border border-border text-foreground outline-hidden hover:bg-accent focus-visible:ring-[3px] focus-visible:ring-ring/50"
            >
              <ArrowLeft aria-hidden="true" className="size-4" />
            </button>
          )}
          <button
            type="button"
            onClick={() => actions.current.next()}
            className="inline-flex h-8 items-center gap-1.5 rounded-md bg-primary px-3 text-sm font-medium text-primary-foreground outline-hidden hover:bg-primary/90 focus-visible:ring-[3px] focus-visible:ring-ring/50"
          >
            {current >= last ? "Finish" : "Next"}
            {current >= last ? <Check aria-hidden="true" className="size-4" /> : <ArrowRight aria-hidden="true" className="size-4" />}
          </button>
        </div>
      </div>
    </div>,
    document.body,
  );
}