{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"page-dots","type":"registry:component","title":"Page dots","description":"A pill that inches between pages like a worm and counts down to the next.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/page-dots.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport {\n  motion,\n  useMotionValue,\n  useMotionValueEvent,\n  useTransform,\n  type MotionValue,\n} from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nconst DOT = 6;\nconst PILL = 20;\nconst GAP = 6;\n// How far each edge of the pill travels between two pages.\nconst STEP = DOT + GAP;\n\nconst clamp01 = (v: number) => Math.min(Math.max(v, 0), 1);\nconst smooth = (v: number) => v * v * (3 - 2 * v);\n// The leading edge does its travel in the first 60% of the move and the\n// trailing edge in the last 60%, so the pill stretches toward the next dot,\n// then pulls its tail in after it, like a worm.\nconst lead = (t: number) => smooth(clamp01(t / 0.6));\nconst trail = (t: number) => smooth(clamp01((t - 0.4) / 0.6));\n\n/**\n * `progress` is a continuous page index (1.5 is halfway between the second\n * and third page), so the dots can follow a scroll or a drag frame by frame\n * without React rendering anything.\n */\nexport function PageDots({\n  count,\n  progress,\n  onSelect,\n  autoplay,\n  className,\n}: {\n  count: number;\n  progress: MotionValue<number>;\n  onSelect: (index: number) => void;\n  /** Fills the pill over `duration` ms while `running`, then calls `onElapsed`. */\n  autoplay?: {\n    duration: number;\n    running: boolean;\n    onElapsed: (active: number) => void;\n  };\n  className?: string;\n}) {\n  const [active, setActive] = useState(() => Math.round(progress.get()));\n  // Only crossing the halfway point renders, which is what aria-current needs.\n  useMotionValueEvent(progress, \"change\", (p) => setActive(Math.round(p)));\n\n  const fillRef = useRef<HTMLSpanElement>(null);\n  const settle = useRef<Animation>(undefined);\n  const onElapsed = useRef(autoplay?.onElapsed);\n  useEffect(() => {\n    onElapsed.current = autoplay?.onElapsed;\n  });\n  const running = autoplay?.running ?? false;\n  const duration = autoplay?.duration ?? 0;\n\n  // The countdown is the timer: when the fill finishes, the page advances.\n  // WAAPI keeps it on the compositor with no React state per frame, and\n  // restarting it on every page or pause means a resume starts over.\n  useEffect(() => {\n    const fill = fillRef.current;\n    if (!fill || !running) return;\n    settle.current?.cancel();\n    const countdown = fill.animate(\n      [{ transform: \"scaleX(0)\" }, { transform: \"scaleX(1)\" }],\n      { duration, easing: \"linear\" },\n    );\n    countdown.onfinish = () => onElapsed.current?.(active);\n    return () => {\n      countdown.onfinish = null;\n      if (countdown.playState !== \"running\") return;\n      // Paused partway: ease the fill back to full over 200ms rather than\n      // snapping, so a paused pill reads as solid, not half done.\n      const from = getComputedStyle(fill).transform;\n      countdown.cancel();\n      settle.current = fill.animate(\n        [{ transform: from }, { transform: \"scaleX(1)\" }],\n        { duration: 200, easing: \"cubic-bezier(0.23, 1, 0.32, 1)\" },\n      );\n    };\n  }, [running, active, duration]);\n\n  useEffect(() => () => settle.current?.cancel(), []);\n\n  // Pill spans [left, right] across the two pages it is between.\n  const pill = (p: number) => {\n    const k = Math.min(Math.max(Math.floor(p), 0), Math.max(count - 2, 0));\n    const t = clamp01(p - k);\n    const left = k * STEP + STEP * trail(t);\n    const right = k * STEP + PILL + STEP * lead(t);\n    return { left, width: right - left };\n  };\n  const pillX = useTransform(progress, (p) => pill(p).left);\n  const pillWidth = useTransform(progress, (p) => pill(p).width);\n\n  return (\n    <div\n      role=\"group\"\n      aria-label=\"Pages\"\n      className={cn(\"relative h-8 [contain:layout]\", className)}\n      // The row never changes width: the active slot is always one pill\n      // wide, whichever dot owns it.\n      style={{ width: (count - 1) * STEP + PILL }}\n    >\n      {Array.from({ length: count }, (_, i) => (\n        <Dot\n          key={i}\n          index={i}\n          count={count}\n          progress={progress}\n          current={i === active}\n          onSelect={onSelect}\n        />\n      ))}\n      <motion.span\n        aria-hidden\n        className={cn(\n          \"pointer-events-none absolute top-1/2 left-0 h-1.5 -translate-y-1/2 overflow-hidden rounded-full\",\n          // With a countdown the pill's track is a lighter tint, still twice\n          // the dots' 20%, so it stays the active slot before it fills.\n          autoplay ? \"bg-foreground/40\" : \"bg-foreground\",\n        )}\n        style={{ x: pillX, width: pillWidth }}\n      >\n        {autoplay && (\n          // Rests full, so a paused pill looks exactly like a plain one.\n          <span\n            ref={fillRef}\n            className=\"absolute inset-0 origin-left bg-foreground\"\n          />\n        )}\n      </motion.span>\n    </div>\n  );\n}\n\nfunction Dot({\n  index,\n  count,\n  progress,\n  current,\n  onSelect,\n}: {\n  index: number;\n  count: number;\n  progress: MotionValue<number>;\n  current: boolean;\n  onSelect: (index: number) => void;\n}) {\n  // A dot swells toward pill width as the page approaches, so the gray row\n  // makes room for the pill and every gap stays even mid-scroll.\n  const width = useTransform(\n    progress,\n    (p) => DOT + (PILL - DOT) * clamp01(1 - Math.abs(p - index)),\n  );\n  // Everything before this dot is plain dots, plus however much of the\n  // extra pill width sits behind it.\n  const left = useTransform(\n    progress,\n    (p) => index * STEP + (PILL - DOT) * clamp01(index - p),\n  );\n\n  return (\n    <motion.button\n      type=\"button\"\n      aria-label={`Page ${index + 1} of ${count}`}\n      aria-current={current ? \"page\" : undefined}\n      onClick={() => onSelect(index)}\n      // Reaches half the 6px gap past each side of its dot, so the hit areas\n      // tile the row with no dead space between them.\n      className=\"group absolute inset-y-0 -ml-[3px] box-content flex touch-manipulation items-center rounded-full px-[3px] outline-hidden focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground\"\n      style={{ left, width }}\n    >\n      <span className=\"h-1.5 w-full rounded-full bg-foreground/20 transition-[background-color,scale] duration-150 ease-out group-hover:bg-foreground/35 group-active:scale-[0.96]\" />\n    </motion.button>\n  );\n}\n\nconst PAGES = [\n  { title: \"Inbox zero\", note: \"Everything triaged before lunch.\" },\n  { title: \"Focus time\", note: \"Two quiet hours blocked every morning.\" },\n  { title: \"Weekly review\", note: \"Friday at four, fifteen minutes.\" },\n  { title: \"Shared lists\", note: \"Groceries, synced with Sam.\" },\n  { title: \"Offline mode\", note: \"Works on the train, syncs later.\" },\n];\n\n// Long enough to read a card's two lines, short enough to feel alive.\nconst INTERVAL = 3000;\n// A scroll counts as over once no scroll event has arrived for this long,\n// which also covers the momentum after a flick.\nconst SCROLL_QUIET = 200;\nconst ICON_SWAP = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\n\nexport default function PageDotsDemo() {\n  const reduceMotion = useReducedMotion();\n  const scrollerRef = useRef<HTMLDivElement>(null);\n  const toggleRef = useRef<HTMLButtonElement>(null);\n  const regionRef = useRef<HTMLDivElement>(null);\n  const progress = useMotionValue(0);\n\n  // null until the viewer picks, so reduced motion can default to paused.\n  const [choice, setChoice] = useState<boolean | null>(null);\n  const playing = choice ?? !reduceMotion;\n  const [hovered, setHovered] = useState(false);\n  const [focused, setFocused] = useState(false);\n  const [scrolling, setScrolling] = useState(false);\n  const [visible, setVisible] = useState(true);\n  const running = playing && !hovered && !focused && !scrolling && visible;\n\n  useEffect(() => {\n    const scroller = scrollerRef.current;\n    if (!scroller) return;\n    // Scroll events can outpace frames on high-rate trackpads; reading\n    // layout once per frame is all the dots can show anyway.\n    let frame = 0;\n    const read = () => {\n      frame = 0;\n      const max = scroller.scrollWidth - scroller.clientWidth;\n      progress.set(\n        max > 0 ? (scroller.scrollLeft / max) * (PAGES.length - 1) : 0,\n      );\n    };\n\n    // Only wheel and touch mark a scroll as the viewer's, so autoplay's own\n    // smooth scrolls never pause autoplay.\n    let touching = false;\n    let busy = false;\n    let quiet: ReturnType<typeof setTimeout> | undefined;\n    const settleSoon = () => {\n      clearTimeout(quiet);\n      quiet = setTimeout(() => {\n        if (touching) return;\n        busy = false;\n        setScrolling(false);\n      }, SCROLL_QUIET);\n    };\n    const start = () => {\n      busy = true;\n      setScrolling(true);\n    };\n    const onScroll = () => {\n      if (!frame) frame = requestAnimationFrame(read);\n      if (busy) settleSoon();\n    };\n    const onWheel = () => {\n      start();\n      settleSoon();\n    };\n    const onTouchStart = () => {\n      touching = true;\n      clearTimeout(quiet);\n      start();\n    };\n    const onTouchEnd = () => {\n      touching = false;\n      settleSoon();\n    };\n\n    const passive = { passive: true } as const;\n    scroller.addEventListener(\"scroll\", onScroll, passive);\n    scroller.addEventListener(\"wheel\", onWheel, passive);\n    scroller.addEventListener(\"touchstart\", onTouchStart, passive);\n    scroller.addEventListener(\"touchend\", onTouchEnd, passive);\n    scroller.addEventListener(\"touchcancel\", onTouchEnd, passive);\n    return () => {\n      scroller.removeEventListener(\"scroll\", onScroll);\n      scroller.removeEventListener(\"wheel\", onWheel);\n      scroller.removeEventListener(\"touchstart\", onTouchStart);\n      scroller.removeEventListener(\"touchend\", onTouchEnd);\n      scroller.removeEventListener(\"touchcancel\", onTouchEnd);\n      cancelAnimationFrame(frame);\n      clearTimeout(quiet);\n    };\n  }, [progress]);\n\n  useEffect(() => {\n    const onChange = () => setVisible(!document.hidden);\n    onChange();\n    document.addEventListener(\"visibilitychange\", onChange);\n    return () => document.removeEventListener(\"visibilitychange\", onChange);\n  }, []);\n\n  const goTo = (index: number) => {\n    const scroller = scrollerRef.current;\n    if (!scroller) return;\n    const max = scroller.scrollWidth - scroller.clientWidth;\n    scroller.scrollTo({\n      left: (index / (PAGES.length - 1)) * max,\n      behavior: reduceMotion ? \"auto\" : \"smooth\",\n    });\n  };\n\n  // Past the last page it scrolls back to the first rather than jumping,\n  // and the pill crawls home through every dot, so the loop reads as a\n  // deliberate rewind.\n  const advance = (active: number) => goTo((active + 1) % PAGES.length);\n\n  const insideRegion = (node: EventTarget | null) =>\n    node instanceof Node &&\n    !!regionRef.current?.contains(node) &&\n    !toggleRef.current?.contains(node);\n\n  return (\n    <div\n      ref={regionRef}\n      className=\"flex w-[min(400px,100%)] flex-col items-center gap-4\"\n      // The toggle is left out on purpose: hovering it to press play must\n      // not be what keeps autoplay paused.\n      onPointerOver={(e) => {\n        if (e.pointerType !== \"touch\") setHovered(insideRegion(e.target));\n      }}\n      onPointerLeave={() => setHovered(false)}\n      onFocus={(e) => {\n        // Only keyboard focus pauses; a mouse click on a dot leaves focus\n        // behind that would otherwise hold autoplay forever.\n        if (insideRegion(e.target) && e.target.matches(\":focus-visible\"))\n          setFocused(true);\n      }}\n      onBlur={(e) => {\n        if (!insideRegion(e.relatedTarget)) setFocused(false);\n      }}\n    >\n      <div\n        ref={scrollerRef}\n        tabIndex={0}\n        role=\"region\"\n        aria-label=\"Features\"\n        aria-roledescription=\"carousel\"\n        // Announcing every automatic slide would talk over the viewer.\n        aria-live={running ? \"off\" : \"polite\"}\n        // Keeps the horizontal swipe from also scrolling the page sideways\n        // or triggering back navigation.\n        className=\"flex w-full snap-x snap-mandatory gap-4 overflow-x-auto overscroll-x-contain rounded-[20px] outline-hidden [scrollbar-width:none] focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground [&::-webkit-scrollbar]:hidden\"\n      >\n        {PAGES.map((page, i) => (\n          <div\n            key={page.title}\n            role=\"group\"\n            aria-roledescription=\"slide\"\n            aria-label={`${i + 1} of ${PAGES.length}`}\n            className=\"flex h-55 w-full shrink-0 snap-center snap-always flex-col justify-end rounded-[20px] border border-border bg-background p-6\"\n          >\n            <p className=\"text-sm text-muted-foreground tabular-nums\">\n              {String(i + 1).padStart(2, \"0\")}\n            </p>\n            <p className=\"mt-1.5 text-lg font-medium text-foreground\">\n              {page.title}\n            </p>\n            <p className=\"mt-0.5 text-[15px] text-muted-foreground\">{page.note}</p>\n          </div>\n        ))}\n      </div>\n      {/* The 32px toggle sits on the right with a matching 32px spacer on the\n          left, so the dots stay centered under the cards. */}\n      <div className=\"flex items-center gap-4\">\n        <span aria-hidden className=\"size-8\" />\n        <PageDots\n          count={PAGES.length}\n          progress={progress}\n          onSelect={goTo}\n          autoplay={{ duration: INTERVAL, running, onElapsed: advance }}\n        />\n        <button\n          ref={toggleRef}\n          type=\"button\"\n          aria-label=\"Pause autoplay\"\n          aria-pressed={!playing}\n          onClick={() => setChoice(!playing)}\n          className=\"relative flex size-8 touch-manipulation items-center justify-center rounded-full text-muted-foreground outline-hidden transition-[scale,color,background-color] duration-150 ease-out hover:bg-muted hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-[color,background-color] after:absolute after:-inset-1.5 after:rounded-full\"\n        >\n          <span className=\"grid\" aria-hidden>\n            <SwapIcon visible={playing} reduceMotion={reduceMotion}>\n              <path d=\"M5.75 3.75v8.5M10.25 3.75v8.5\" />\n            </SwapIcon>\n            <SwapIcon visible={!playing} reduceMotion={reduceMotion}>\n              <path d=\"M5 3.9v8.2a.6.6 0 0 0 .9.5l6.6-4.1a.6.6 0 0 0 0-1L5.9 3.4a.6.6 0 0 0-.9.5Z\" />\n            </SwapIcon>\n          </span>\n        </button>\n      </div>\n    </div>\n  );\n}\n\nfunction SwapIcon({\n  visible,\n  reduceMotion,\n  children,\n}: {\n  visible: boolean;\n  reduceMotion: boolean | null;\n  children: React.ReactNode;\n}) {\n  // Reduced motion keeps the cross-fade but drops the scale and blur.\n  const hidden = reduceMotion\n    ? { opacity: 0 }\n    : { scale: 0.25, opacity: 0, filter: \"blur(4px)\" };\n  return (\n    <motion.svg\n      viewBox=\"0 0 16 16\"\n      className=\"col-start-1 row-start-1 size-4\"\n      fill=\"none\"\n      stroke=\"currentColor\"\n      strokeWidth={1.5}\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n      initial={false}\n      animate={visible ? { scale: 1, opacity: 1, filter: \"blur(0px)\" } : hidden}\n      transition={ICON_SWAP}\n    >\n      {children}\n    </motion.svg>\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"categories":["navigation"],"docs":"From ui lab: https://lab.xevrion.dev/lab/page-dots"}