{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"story-progress","type":"registry:component","title":"Story progress","description":"Tap through stories, hold to pause.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/story-progress.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport { AnimatePresence, motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\n// Long enough to read a short caption, the same as Instagram's default.\nconst DURATION = 4000;\n// Shorter presses are taps that navigate; longer ones are holds that pause.\nconst HOLD_MS = 200;\nconst ICON_SWAP = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\n\nexport type Story = { value: string; caption: string };\n\nexport function StoryProgress({\n  stories,\n  className,\n}: {\n  stories: Story[];\n  className?: string;\n}) {\n  const reduce = useReducedMotion();\n  const [index, setIndex] = useState(0);\n  // Auto-advancing stays silent; only stories the user moved to are announced.\n  const [manual, setManual] = useState(false);\n  const [pressing, setPressing] = useState(false);\n  const [held, setHeld] = useState(false);\n  const [toggled, setToggled] = useState(false);\n  const [hidden, setHidden] = useState(false);\n\n  const paused = pressing || toggled || hidden;\n  const pausedRef = useRef(paused);\n  const fills = useRef<(HTMLSpanElement | null)[]>([]);\n  const timer = useRef<Animation>(null);\n  const holdTimer = useRef<ReturnType<typeof setTimeout>>(undefined);\n  const count = stories.length;\n\n  const go = (step: number) => {\n    setManual(true);\n    setIndex((i) => (i + step + count) % count);\n  };\n\n  // A compositor-driven transform animation is the timer itself: when it\n  // finishes, the story advances, so the bar and the content can't drift.\n  useEffect(() => {\n    const fill = fills.current[index];\n    if (!fill) return;\n    const animation = fill.animate(\n      [{ transform: \"scaleX(0)\" }, { transform: \"scaleX(1)\" }],\n      { duration: DURATION, easing: \"linear\", fill: \"forwards\" },\n    );\n    if (pausedRef.current) animation.pause();\n    animation.onfinish = () => {\n      setManual(false);\n      setIndex((i) => (i + 1) % count);\n    };\n    timer.current = animation;\n    return () => animation.cancel();\n  }, [index, count]);\n\n  useEffect(() => {\n    pausedRef.current = paused;\n    const animation = timer.current;\n    if (!animation) return;\n    if (paused) animation.pause();\n    else if (animation.playState === \"paused\") animation.play();\n  }, [paused]);\n\n  useEffect(() => {\n    const sync = () => setHidden(document.hidden);\n    document.addEventListener(\"visibilitychange\", sync);\n    return () => document.removeEventListener(\"visibilitychange\", sync);\n  }, []);\n\n  useEffect(() => () => clearTimeout(holdTimer.current), []);\n\n  const release = (navigate: boolean, clientX = 0, box?: DOMRect) => {\n    clearTimeout(holdTimer.current);\n    setPressing(false);\n    if (held) setHeld(false);\n    else if (navigate && box) go(clientX < box.left + box.width / 2 ? -1 : 1);\n  };\n\n  const story = stories[index];\n  const dimmed = held || toggled;\n\n  return (\n    <div\n      role=\"region\"\n      aria-roledescription=\"stories\"\n      aria-label=\"Stories\"\n      tabIndex={0}\n      className={cn(\n        \"relative flex h-[480px] w-[min(320px,100%)] touch-manipulation flex-col overflow-hidden rounded-3xl bg-muted text-foreground shadow-raised outline-hidden select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground\",\n        className,\n      )}\n      onPointerDown={(e) => {\n        if (e.button !== 0) return;\n        e.currentTarget.setPointerCapture(e.pointerId);\n        // The fill freezes the moment you press; the dim waits until it is\n        // clearly a hold, so quick taps don't flicker.\n        setPressing(true);\n        holdTimer.current = setTimeout(() => setHeld(true), HOLD_MS);\n      }}\n      onPointerUp={(e) =>\n        release(true, e.clientX, e.currentTarget.getBoundingClientRect())\n      }\n      onPointerCancel={() => release(false)}\n      onContextMenu={(e) => e.preventDefault()}\n      onKeyDown={(e) => {\n        if (e.key === \"ArrowRight\") go(1);\n        else if (e.key === \"ArrowLeft\") go(-1);\n        else if (e.key === \" \" && !e.repeat) setToggled((t) => !t);\n        else return;\n        e.preventDefault();\n      }}\n    >\n      <div className=\"flex gap-1 px-3 pt-3\" aria-hidden>\n        {stories.map((_, i) => (\n          <span\n            key={i}\n            className=\"h-[3px] flex-1 overflow-hidden rounded-full bg-foreground/15\"\n          >\n            <span\n              ref={(el) => {\n                fills.current[i] = el;\n              }}\n              className=\"block h-full origin-left rounded-full bg-foreground\"\n              style={{ transform: `scaleX(${i < index ? 1 : 0})` }}\n            />\n          </span>\n        ))}\n      </div>\n\n      <div className=\"flex h-11 items-center justify-between px-4\">\n        <span className=\"text-xs text-muted-foreground tabular-nums\">\n          {index + 1} / {count}\n        </span>\n        {/* Static cue for the paused state, so the frozen bar isn't the only signal. */}\n        <button\n          type=\"button\"\n          aria-label={toggled ? \"Play\" : \"Pause\"}\n          className=\"relative -mr-2 grid size-10 place-items-center rounded-full text-muted-foreground transition-[scale,color] duration-150 ease-out hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96]\"\n          onPointerDown={(e) => e.stopPropagation()}\n          onPointerUp={(e) => e.stopPropagation()}\n          onKeyDown={(e) => {\n            // Let Space reach the button's own click instead of toggling twice.\n            if (e.key === \" \" || e.key === \"Enter\") e.stopPropagation();\n          }}\n          onClick={() => setToggled((t) => !t)}\n        >\n          <PlayPause paused={dimmed} />\n        </button>\n      </div>\n\n      <div\n        className={cn(\n          \"relative flex-1 transition-[opacity] duration-200 ease-out\",\n          dimmed && \"opacity-60\",\n        )}\n      >\n        <AnimatePresence initial={false}>\n          <motion.div\n            key={index}\n            aria-hidden\n            className=\"absolute inset-0 flex flex-col justify-end gap-2 p-6\"\n            initial={{ opacity: 0, filter: reduce ? \"blur(0px)\" : \"blur(4px)\" }}\n            animate={{\n              opacity: 1,\n              filter: \"blur(0px)\",\n              transition: { duration: 0.25, ease: [0.23, 1, 0.32, 1] },\n            }}\n            exit={{\n              opacity: 0,\n              filter: reduce ? \"blur(0px)\" : \"blur(4px)\",\n              transition: { duration: 0.15, ease: [0.23, 1, 0.32, 1] },\n            }}\n          >\n            <span className=\"text-7xl font-medium tracking-tight tabular-nums\">\n              {story.value}\n            </span>\n            <span className=\"text-[15px] text-pretty text-muted-foreground\">\n              {story.caption}\n            </span>\n          </motion.div>\n        </AnimatePresence>\n        {/* A persistent region: one that mounts with its content is rarely read. */}\n        <p className=\"sr-only\" aria-live={manual ? \"polite\" : \"off\"}>\n          {story.value}. {story.caption}\n        </p>\n      </div>\n\n      {/* Reachable by screen readers; pointer taps are handled by the card,\n          so a real click (detail > 0) is ignored here to avoid a double step. */}\n      <div className=\"absolute inset-x-0 top-[60px] bottom-0 flex\">\n        <button\n          type=\"button\"\n          tabIndex={-1}\n          aria-label=\"Previous story\"\n          className=\"flex-1 outline-hidden\"\n          onClick={(e) => e.detail === 0 && go(-1)}\n        />\n        <button\n          type=\"button\"\n          tabIndex={-1}\n          aria-label=\"Next story\"\n          className=\"flex-1 outline-hidden\"\n          onClick={(e) => e.detail === 0 && go(1)}\n        />\n      </div>\n    </div>\n  );\n}\n\nfunction PlayPause({ paused }: { paused: boolean }) {\n  return (\n    <span className=\"grid size-4\">\n      <motion.svg\n        viewBox=\"0 0 16 16\"\n        className=\"col-start-1 row-start-1 size-4\"\n        fill=\"currentColor\"\n        initial={false}\n        animate={\n          paused\n            ? { scale: 0.25, opacity: 0, filter: \"blur(4px)\" }\n            : { scale: 1, opacity: 1, filter: \"blur(0px)\" }\n        }\n        transition={ICON_SWAP}\n      >\n        <rect x=\"4\" y=\"3\" width=\"2.5\" height=\"10\" rx=\"1\" />\n        <rect x=\"9.5\" y=\"3\" width=\"2.5\" height=\"10\" rx=\"1\" />\n      </motion.svg>\n      <motion.svg\n        viewBox=\"0 0 16 16\"\n        className=\"col-start-1 row-start-1 size-4\"\n        fill=\"currentColor\"\n        initial={false}\n        animate={\n          paused\n            ? { scale: 1, opacity: 1, filter: \"blur(0px)\" }\n            : { scale: 0.25, opacity: 0, filter: \"blur(4px)\" }\n        }\n        transition={ICON_SWAP}\n      >\n        {/* Nudged right of centre so the triangle looks optically centred. */}\n        <path d=\"M5.5 3.4v9.2a.6.6 0 0 0 .9.5l7-4.6a.6.6 0 0 0 0-1L6.4 2.9a.6.6 0 0 0-.9.5Z\" />\n      </motion.svg>\n    </span>\n  );\n}\n\nconst STORIES: Story[] = [\n  { value: \"12k\", caption: \"People tried the lab this week.\" },\n  { value: \"4.8\", caption: \"Average rating across every component.\" },\n  { value: \"38%\", caption: \"Fewer layout shifts since the last release.\" },\n  { value: \"212\", caption: \"Commits that were only about easing curves.\" },\n  { value: \"0\", caption: \"Components that animate from scale zero.\" },\n];\n\nexport default function StoryProgressDemo() {\n  return <StoryProgress stories={STORIES} />;\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"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["feedback"],"docs":"From ui lab: https://lab.xevrion.dev/lab/story-progress"}