{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"product-tour","type":"registry:ui","title":"Product Tour","description":"A guided tour that dims the page around one element at a time and explains it in a card beside it.","dependencies":["lucide-react"],"registryDependencies":["https://dashral.com/r/utils.json","https://dashral.com/r/lib-locale.json","https://dashral.com/r/lib-motion.json","https://dashral.com/r/lib-portal.json","https://dashral.com/r/button.json"],"files":[{"path":"registry/dashral/product-tour.tsx","type":"registry:file","target":"components/dashral/product-tour.tsx","content":"\"use client\"\n\nimport * as React from \"react\"\nimport { createPortal } from \"react-dom\"\nimport { XIcon } from \"lucide-react\"\n\nimport { cn } from \"./lib/utils\"\nimport { useLocale } from \"./lib/locale\"\nimport { cssDuration, reducedMotion } from \"./lib/motion\"\nimport { usePortalContainer } from \"./lib/portal\"\nimport { Button } from \"./button\"\n\ntype TourTarget = string | React.RefObject<HTMLElement | null> | (() => HTMLElement | null)\n\ntype TourStep = {\n  /**\n   * What the step points at: a CSS selector (\"#search\", \"[data-tour=export]\"), a ref, or a function returning the\n   * element. Leave it out, or point at nothing on the page, for a step in the middle of the screen (a welcome or a\n   * last word).\n   */\n  target?: TourTarget\n  title: React.ReactNode\n  description?: React.ReactNode\n  /** A picture or anything else above the title. */\n  media?: React.ReactNode\n  /** Which side of the target the card sits on; it moves to another side when there isn't room. */\n  side?: \"top\" | \"right\" | \"bottom\" | \"left\"\n  /** How the card lines up with the target along that side. */\n  align?: \"start\" | \"center\" | \"end\"\n}\n\ntype ProductTourProps = {\n  steps: TourStep[]\n  /** What starts the tour, e.g. a button; it must take a ref and focus. Or open it yourself with `open`. */\n  trigger?: React.ReactElement<{ onClick?: React.MouseEventHandler }>\n  /** Whether the tour is showing, controlled. */\n  open?: boolean\n  defaultOpen?: boolean\n  onOpenChange?: (open: boolean) => void\n  /** The step showing (zero-based), controlled. */\n  step?: number\n  defaultStep?: number\n  onStepChange?: (step: number) => void\n  /** Called when the last step's Done is pressed (closing early with × or Escape doesn't count). */\n  onFinish?: () => void\n  /** Room in pixels between the target and the edge of its spotlight. */\n  padding?: number\n  /** The card's classes, e.g. a width. */\n  className?: string\n  classNames?: { card?: string; spotlight?: string }\n}\n\ntype Box = { x: number; y: number; width: number; height: number }\n\n// Room kept between the card and the screen's edges, and between the card and its spotlight.\nconst MARGIN = 12\nconst GAP = 12\n\nfunction resolve(target: TourTarget | undefined): HTMLElement | null {\n  if (!target || typeof document === \"undefined\") return null\n  if (typeof target === \"string\") return document.querySelector<HTMLElement>(target)\n  if (typeof target === \"function\") return target()\n  return target.current\n}\n\n/** Where the card goes: the asked side if it fits, else its opposite, else the roomiest; along it, the asked line-up kept on screen. */\nfunction placeCard(hole: Box | null, card: { width: number; height: number }, step: TourStep, rtl: boolean) {\n  const vw = window.innerWidth\n  const vh = window.innerHeight\n  const clampX = (x: number) => Math.max(MARGIN, Math.min(x, vw - card.width - MARGIN))\n  const clampY = (y: number) => Math.max(MARGIN, Math.min(y, vh - card.height - MARGIN))\n  if (!hole) return { x: clampX((vw - card.width) / 2), y: clampY((vh - card.height) / 2) }\n\n  const room = {\n    top: hole.y - GAP - MARGIN,\n    bottom: vh - (hole.y + hole.height) - GAP - MARGIN,\n    left: hole.x - GAP - MARGIN,\n    right: vw - (hole.x + hole.width) - GAP - MARGIN,\n  }\n  const fits = (side: keyof typeof room) => room[side] >= (side === \"top\" || side === \"bottom\" ? card.height : card.width)\n  const asked = step.side ?? \"bottom\"\n  const opposite = ({ top: \"bottom\", bottom: \"top\", left: \"right\", right: \"left\" } as const)[asked]\n  const side =\n    [asked, opposite, \"bottom\", \"top\", \"right\", \"left\"].find((s) => fits(s as keyof typeof room)) ??\n    (room.bottom >= room.top ? \"bottom\" : \"top\")\n\n  const align = step.align ?? \"center\"\n  if (side === \"top\" || side === \"bottom\") {\n    const start = rtl ? hole.x + hole.width - card.width : hole.x\n    const end = rtl ? hole.x : hole.x + hole.width - card.width\n    const x = align === \"center\" ? hole.x + (hole.width - card.width) / 2 : align === \"start\" ? start : end\n    const y = side === \"bottom\" ? hole.y + hole.height + GAP : hole.y - GAP - card.height\n    return { x: clampX(x), y: clampY(y) }\n  }\n  const y = align === \"center\" ? hole.y + (hole.height - card.height) / 2 : align === \"start\" ? hole.y : hole.y + hole.height - card.height\n  const x = side === \"right\" ? hole.x + hole.width + GAP : hole.x - GAP - card.width\n  return { x: clampX(x), y: clampY(y) }\n}\n\nconst focusable = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex=\"-1\"])'\n\n/**\n * A guided tour in one tag: each step dims the page around one element, lights it up and explains it in a card beside\n * it. The spotlight and the card glide from step to step.\n */\nfunction ProductTour({\n  steps,\n  trigger,\n  open: openProp,\n  defaultOpen = false,\n  onOpenChange,\n  step: stepProp,\n  defaultStep = 0,\n  onStepChange,\n  onFinish,\n  padding = 6,\n  className,\n  classNames,\n}: ProductTourProps) {\n  const { t, dir } = useLocale()\n  const portalContainer = usePortalContainer()\n  const [openState, setOpenState] = React.useState(defaultOpen)\n  const [stepState, setStepState] = React.useState(defaultStep)\n  const open = openProp ?? openState\n  const index = Math.max(0, Math.min(stepProp ?? stepState, steps.length - 1))\n  const current = steps[index]\n  const last = index === steps.length - 1\n\n  // Mounted from opening until the closing fade has played.\n  const [mounted, setMounted] = React.useState(open)\n  const [closing, setClosing] = React.useState(false)\n  // The step whose words are fading out while the new ones come in.\n  const [leaving, setLeaving] = React.useState<number | null>(null)\n  const shownIndex = React.useRef(index)\n\n  const card = React.useRef<HTMLDivElement>(null)\n  const body = React.useRef<HTMLDivElement>(null)\n  const content = React.useRef<HTMLDivElement>(null)\n  const spotlight = React.useRef<HTMLDivElement>(null)\n  const returnFocus = React.useRef<HTMLElement | null>(null)\n  // While a step change glides, positions move on a transition; the rest of the time (scrolling, resizing) they follow at once.\n  const gliding = React.useRef(false)\n  const glideTimer = React.useRef<number>(undefined)\n  const [bodyHeight, setBodyHeight] = React.useState<number | null>(null)\n  const titleId = React.useId()\n  const descriptionId = React.useId()\n\n  function setOpen(next: boolean) {\n    if (openProp === undefined) setOpenState(next)\n    onOpenChange?.(next)\n  }\n  function go(next: number) {\n    if (next < 0 || next >= steps.length) return\n    if (stepProp === undefined) setStepState(next)\n    onStepChange?.(next)\n  }\n  function finish() {\n    setOpen(false)\n    onFinish?.()\n  }\n\n  // Opening and closing: stay mounted through the fade out, and give focus back to where it was.\n  React.useEffect(() => {\n    if (open) {\n      returnFocus.current = document.activeElement as HTMLElement | null\n      setClosing(false)\n      setMounted(true)\n      return\n    }\n    if (!mounted) return\n    setClosing(true)\n    const timer = window.setTimeout(() => {\n      setMounted(false)\n      setClosing(false)\n      setLeaving(null)\n      const back = returnFocus.current\n      if (back && back.isConnected) back.focus({ preventScroll: true })\n    }, reducedMotion() ? 0 : cssDuration(\"--duration-standard\", 240))\n    return () => window.clearTimeout(timer)\n    // Only when open changes.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [open])\n\n  // Put the spotlight round the target and the card beside it.\n  const place = React.useCallback(() => {\n    const cardNode = card.current\n    const light = spotlight.current\n    if (!cardNode || !light || !current) return\n    const target = resolve(current.target)\n    const r = target?.getBoundingClientRect()\n    const hole = r && (r.width > 0 || r.height > 0) ? { x: r.x - padding, y: r.y - padding, width: r.width + padding * 2, height: r.height + padding * 2 } : null\n\n    const glide = gliding.current && !reducedMotion()\n    light.dataset.glide = glide ? \"true\" : \"false\"\n    cardNode.dataset.glide = glide ? \"true\" : \"false\"\n    // No target: the hole closes to a point in the middle, so the whole page is dimmed.\n    const box = hole ?? { x: window.innerWidth / 2, y: window.innerHeight / 2, width: 0, height: 0 }\n    light.style.left = `${box.x}px`\n    light.style.top = `${box.y}px`\n    light.style.width = `${box.width}px`\n    light.style.height = `${box.height}px`\n    light.dataset.empty = hole ? \"false\" : \"true\"\n    // Its corners sit round the target's (the target's radius plus the padding); a square target gets the theme's.\n    const corner = target ? parseFloat(getComputedStyle(target).borderTopLeftRadius) : NaN\n    light.style.borderRadius = corner > 0 ? `${corner + padding}px` : \"\"\n\n    // The card's height once its words have grown or shrunk to the new step's.\n    const height = cardNode.offsetHeight - (body.current?.offsetHeight ?? 0) + (content.current?.offsetHeight ?? 0)\n    const { x, y } = placeCard(hole, { width: cardNode.offsetWidth, height }, current, dir === \"rtl\")\n    cardNode.style.left = `${x}px`\n    cardNode.style.top = `${y}px`\n  }, [current, padding, dir])\n\n  // A new step: bring its target into view, then glide there; the old words fade out as the new ones come in.\n  React.useLayoutEffect(() => {\n    if (!mounted) return\n    const previous = shownIndex.current\n    shownIndex.current = index\n    const changed = previous !== index\n    const still = reducedMotion()\n    if (changed && !still) setLeaving(previous)\n    gliding.current = changed\n    window.clearTimeout(glideTimer.current)\n    const duration = cssDuration(\"--duration-considered\", 480)\n    glideTimer.current = window.setTimeout(() => {\n      gliding.current = false\n      setLeaving(null)\n    }, duration + 40)\n\n    const target = resolve(current?.target)\n    if (target) {\n      const r = target.getBoundingClientRect()\n      const outside = r.top < MARGIN || r.bottom > window.innerHeight - MARGIN || r.left < 0 || r.right > window.innerWidth\n      if (outside) target.scrollIntoView({ block: \"center\", inline: \"nearest\", behavior: still ? \"auto\" : \"smooth\" })\n    }\n    place()\n  }, [index, mounted, current, place])\n\n  // Follow the page as it scrolls or resizes, and the target as it changes size.\n  React.useEffect(() => {\n    if (!mounted) return\n    let frame = 0\n    const update = () => {\n      cancelAnimationFrame(frame)\n      frame = requestAnimationFrame(place)\n    }\n    window.addEventListener(\"scroll\", update, true)\n    window.addEventListener(\"resize\", update)\n    const observer = new ResizeObserver(update)\n    const target = resolve(current?.target)\n    if (target) observer.observe(target)\n    if (content.current) observer.observe(content.current)\n    return () => {\n      cancelAnimationFrame(frame)\n      window.removeEventListener(\"scroll\", update, true)\n      window.removeEventListener(\"resize\", update)\n      observer.disconnect()\n    }\n  }, [mounted, current, place])\n\n  // The words' height, for the card to grow or shrink to it.\n  React.useLayoutEffect(() => {\n    const node = content.current\n    if (!node) return\n    setBodyHeight(node.offsetHeight)\n    const observer = new ResizeObserver(() => setBodyHeight(node.offsetHeight))\n    observer.observe(node)\n    return () => observer.disconnect()\n  }, [mounted, index])\n\n  // Focus the card as it opens, so the first step is read out.\n  React.useEffect(() => {\n    if (mounted && !closing) card.current?.focus({ preventScroll: true })\n  }, [mounted, closing])\n\n  // Keys anywhere while it shows: Escape closes, the arrows step (mirrored right to left).\n  React.useEffect(() => {\n    if (!mounted || closing) return\n    const onKey = (event: KeyboardEvent) => {\n      if (event.defaultPrevented) return\n      if (event.key === \"Escape\") {\n        event.preventDefault()\n        setOpen(false)\n        return\n      }\n      const typing = event.target instanceof HTMLElement && event.target.closest(\"input, textarea, select, [contenteditable=true]\")\n      if (typing) return\n      const forward = dir === \"rtl\" ? \"ArrowLeft\" : \"ArrowRight\"\n      const backward = dir === \"rtl\" ? \"ArrowRight\" : \"ArrowLeft\"\n      if (event.key === forward && !last) {\n        event.preventDefault()\n        go(index + 1)\n      } else if (event.key === backward && index > 0) {\n        event.preventDefault()\n        go(index - 1)\n      }\n    }\n    document.addEventListener(\"keydown\", onKey)\n    return () => document.removeEventListener(\"keydown\", onKey)\n  })\n\n  // Focus stays in the card: Tab wraps round its buttons. A button that goes away (Back on the first step) hands\n  // focus to Next.\n  React.useEffect(() => {\n    const node = card.current\n    if (!node || !mounted) return\n    if (!node.contains(document.activeElement)) node.querySelector<HTMLElement>(\"[data-tour-next]\")?.focus({ preventScroll: true })\n  }, [index, mounted])\n\n  function onCardKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {\n    if (event.key !== \"Tab\") return\n    const items = Array.from(card.current?.querySelectorAll<HTMLElement>(focusable) ?? []).filter(\n      (el) => !el.closest(\"[data-tour-leaving]\")\n    )\n    if (!items.length) return\n    const first = items[0]!\n    const lastItem = items[items.length - 1]!\n    if (event.shiftKey && (document.activeElement === first || document.activeElement === card.current)) {\n      event.preventDefault()\n      lastItem.focus()\n    } else if (!event.shiftKey && document.activeElement === lastItem) {\n      event.preventDefault()\n      first.focus()\n    }\n  }\n\n  const triggerElement =\n    trigger &&\n    React.cloneElement(trigger, {\n      onClick: (event: React.MouseEvent) => {\n        trigger.props.onClick?.(event)\n        if (event.defaultPrevented) return\n        if (stepProp === undefined) setStepState(0)\n        else onStepChange?.(0)\n        setOpen(true)\n      },\n    })\n\n  const renderWords = (step: TourStep, ids: boolean) => (\n    <>\n      {step.media && <div className=\"mb-3 overflow-hidden rounded-md [&_img]:w-full\">{step.media}</div>}\n      <h2 id={ids ? titleId : undefined} className=\"pe-8 text-base leading-snug font-semibold\">\n        {step.title}\n      </h2>\n      {step.description && (\n        <div id={ids ? descriptionId : undefined} className=\"mt-1.5 text-sm text-muted-foreground\">\n          {step.description}\n        </div>\n      )}\n    </>\n  )\n\n  const leavingStep = leaving !== null ? steps[leaving] : undefined\n\n  return (\n    <>\n      {triggerElement}\n      {mounted &&\n        current &&\n        createPortal(\n          <div data-slot=\"product-tour\" dir={dir}>\n            {/* Catches clicks on the page while the tour shows; the dimming is the spotlight's shadow. */}\n            <div aria-hidden className=\"fixed inset-0 z-50\" />\n            <div\n              ref={spotlight}\n              aria-hidden\n              data-slot=\"product-tour-spotlight\"\n              className={cn(\n                \"pointer-events-none fixed z-50 rounded-lg shadow-[0_0_0_9999px_rgb(0_0_0/0.5)] outline-2 outline-white/70 dark:outline-white/40\",\n                \"data-[glide=true]:transition-[left,top,width,height,border-radius] data-[glide=true]:duration-(--duration-considered) data-[glide=true]:ease-standard\",\n                \"data-[empty=true]:outline-transparent\",\n                closing\n                  ? \"animate-out fade-out-0 fill-mode-forwards duration-(--duration-standard)\"\n                  : \"animate-in fade-in-0 duration-(--duration-standard)\",\n                classNames?.spotlight\n              )}\n            />\n            <div\n              ref={card}\n              role=\"dialog\"\n              aria-modal=\"true\"\n              aria-labelledby={titleId}\n              aria-describedby={current.description ? descriptionId : undefined}\n              tabIndex={-1}\n              onKeyDown={onCardKeyDown}\n              data-slot=\"product-tour-card\"\n              className={cn(\n                \"fixed z-50 w-80 max-w-[calc(100vw-24px)] rounded-xl border bg-popover p-4 text-popover-foreground shadow-lg outline-none\",\n                \"data-[glide=true]:transition-[left,top] data-[glide=true]:duration-(--duration-considered) data-[glide=true]:ease-standard\",\n                closing\n                  ? \"animate-out fade-out-0 zoom-out-95 fill-mode-forwards duration-(--duration-fast)\"\n                  : \"animate-in fade-in-0 zoom-in-95\",\n                className,\n                classNames?.card\n              )}\n            >\n              <Button\n                variant=\"ghost\"\n                size=\"icon-sm\"\n                className=\"absolute end-2.5 top-2.5 text-muted-foreground\"\n                aria-label={t(\"close\")}\n                onClick={() => setOpen(false)}\n              >\n                <XIcon />\n              </Button>\n\n              {/* The words: the old step's fade out on top while the new step's fade in, and the card's height glides between them. */}\n              <div\n                ref={body}\n                className=\"relative transition-[height] duration-(--duration-considered) ease-standard motion-reduce:transition-none\"\n                style={{ height: bodyHeight ?? undefined }}\n              >\n                <div\n                  key={index}\n                  ref={content}\n                  className={cn(leaving !== null && \"animate-in fade-in-0 fill-mode-both delay-100 duration-(--duration-standard)\")}\n                >\n                  {renderWords(current, true)}\n                </div>\n                {leavingStep && (\n                  <div\n                    key={`leaving-${leaving}`}\n                    data-tour-leaving\n                    aria-hidden\n                    inert\n                    className=\"absolute inset-x-0 top-0 animate-out fade-out-0 fill-mode-forwards duration-(--duration-fast)\"\n                  >\n                    {renderWords(leavingStep, false)}\n                  </div>\n                )}\n              </div>\n\n              <div className=\"mt-4 flex items-center gap-2\">\n                {steps.length > 1 && (\n                  <div aria-hidden className=\"flex items-center gap-1.5\">\n                    {steps.map((_, i) => (\n                      <span\n                        key={i}\n                        className={cn(\n                          \"h-1.5 rounded-full transition-[width,background-color] duration-(--duration-considered) ease-standard motion-reduce:transition-none\",\n                          i === index ? \"w-4 bg-primary\" : \"w-1.5 bg-foreground/15\"\n                        )}\n                      />\n                    ))}\n                  </div>\n                )}\n                <span className=\"sr-only\" aria-live=\"polite\">\n                  {t(\"tourStep\", { index: index + 1, total: steps.length })}\n                </span>\n                <div className=\"ms-auto flex items-center gap-2\">\n                  {index > 0 && (\n                    <Button variant=\"outline\" size=\"sm\" onClick={() => go(index - 1)}>\n                      {t(\"back\")}\n                    </Button>\n                  )}\n                  <Button size=\"sm\" data-tour-next onClick={() => (last ? finish() : go(index + 1))}>\n                    {last ? t(\"done\") : t(\"next\")}\n                  </Button>\n                </div>\n              </div>\n            </div>\n          </div>,\n          portalContainer ?? document.body\n        )}\n    </>\n  )\n}\n\nexport { ProductTour, type ProductTourProps, type TourStep, type TourTarget }\n"}],"cssVars":{"theme":{"ease-standard":"var(--ease-standard)","ease-enter":"var(--ease-enter)","ease-exit":"var(--ease-exit)","ease-spring":"var(--ease-spring)"},"light":{"duration-fast":"160ms","duration-standard":"240ms","duration-considered":"480ms","ease-standard":"cubic-bezier(0.2, 0, 0, 1)","ease-enter":"cubic-bezier(0, 0, 0, 1)","ease-exit":"cubic-bezier(0.3, 0, 1, 1)","ease-spring":"linear(0, 0.071 4%, 0.234 8%, 0.433 12%, 0.626 17%, 0.791 21%, 0.917 25%, 1.004 29%, 1.055 33%, 1.079 38%, 1.083 42%, 1.075 46%, 1.06 50%, 1.043 54%, 1.027 58%, 1.015 62%, 1.005 67%, 0.998 71%, 0.995 75%, 0.993 79%, 0.993 83%, 0.994 88%, 0.995 92%, 0.997 96%, 1)"},"dark":{}}}