{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "video-scrub",
  "type": "registry:block",
  "title": "Video Scrub",
  "description": "A pinned product film scrubbed by scroll, with chapters that follow the film. Bring your own film, encoded with a keyframe every few frames.",
  "dependencies": [
    "svg-scroll-draw"
  ],
  "files": [
    {
      "path": "registry/blocks/video-scrub.tsx",
      "content": "'use client';\n\n/**\n * video-scrub — a product film pinned to the screen and scrubbed by the scroll,\n * with numbered chapters beside it that follow the film.\n *\n * Built on svg-scroll-draw (MIT): https://svg-scroll-draw.vercel.app/blocks\n * Needs: react, svg-scroll-draw 2.18 or later (`scrollVideo` from\n * `svg-scroll-draw/video`, with `triggerElement` and `onProgress`).\n * Styling: Tailwind CSS.\n *\n * Props: `src` is required, the URL of your film; there is no default film.\n * Optional: `fallbackSrc` (an MP4 copy for browsers that cannot play `src`),\n * `poster`, `label` (what the film shows, for screen readers), `chapters`,\n * `from` and `to` (the stretch of the file to scrub, in seconds) and\n * `className`. The default chapters and label are placeholders: replace them.\n *\n * The track is four screens tall and the stage inside it is sticky, so the\n * stage stays stuck for three screens of scroll, and that stretch is the film.\n * For more or less scroll per film, change `h-[400vh]` on the track. The scrub\n * is measured on the track, not the video: a video in a sticky stage moves with\n * the scroll, so its own box gives the wrong window, and a phone's address bar\n * showing or hiding is a resize that measures it wrong again.\n *\n * Encode the film for scrubbing. Every scroll frame is a seek, and a seek\n * decodes from the last keyframe; exports usually put one every few seconds.\n * Put one every few frames (`-g 3`): measured in Chromium on a 5-second film,\n * that kept every seek under 7.3 ms, against up to 53.6 ms with one keyframe\n * for the whole clip. `-an` drops the audio, and `-auto-alt-ref 0` turns off\n * alternate reference frames, which tripled seek times on a test film.\n *\n *   ffmpeg -i film.mov -an -c:v libvpx -cpu-used 1 -pix_fmt yuv420p \\\n *     -g 3 -auto-alt-ref 0 -b:v 2400k -crf 4 -qmin 0 -qmax 26 film.webm\n *\n * For `fallbackSrc`, keep the same short keyframe interval:\n *\n *   ffmpeg -i film.mov -an -c:v libx264 -pix_fmt yuv420p -g 3 -crf 20 \\\n *     -movflags +faststart film.mp4\n *\n * Serve the film from a server that answers Range requests (206 Partial\n * Content, Accept-Ranges: bytes), or it will not scrub once deployed. Sticky\n * does not work inside an ancestor with `overflow: hidden`, `auto` or `scroll`;\n * use `overflow: clip` there, or keep this block out of one.\n *\n * Below the `md` breakpoint the stage shows one chapter at a time, so it still\n * fits one screen. Reduced motion is handled by the library for the film: it\n * shows the last frame and does not scrub. This block then shows every chapter\n * and drops the scroll room, so nobody scrolls three screens past a still.\n */\n\nimport { useEffect, useRef, useState } from 'react';\nimport { scrollVideo } from 'svg-scroll-draw/video';\n\nexport interface FilmChapter {\n  /** Where this chapter takes over: a point in the film from 0 (start) to 1 (end). */\n  from: number;\n  title: string;\n  body: string;\n}\n\nexport interface VideoScrubProps {\n  /** Required. A muted film encoded for scrubbing (see above). */\n  src: string;\n  /** An MP4 copy of the film, encoded the same way, for browsers that cannot play `src`. */\n  fallbackSrc?: string;\n  /** Image shown until the film's first frame is ready. */\n  poster?: string;\n  /** What the film shows, for screen readers. */\n  label?: string;\n  /** In film order, the first from 0. Each one shows until the next one's `from`. */\n  chapters?: FilmChapter[];\n  /** Where the scrub starts in the file, in seconds. Default 0. */\n  from?: number;\n  /** Where the scrub stops in the file, in seconds. Leave it out to use the whole file. */\n  to?: number;\n  className?: string;\n}\n\nconst DEFAULT_CHAPTERS: FilmChapter[] = [\n  { from: 0, title: 'Built to be worn all day', body: 'A sprung steel band and memory-foam cushions, 254 g all in.' },\n  { from: 0.45, title: 'Taken apart', body: 'The cup comes apart layer by layer: the cap, the shell, the board.' },\n  { from: 0.75, title: 'The part you hear', body: 'A 40 mm driver with a beryllium-coated dome, 4 Hz to 40 kHz.' },\n];\n\n/** The last chapter that has started at film progress `p` (0 to 1). */\nfunction chapterAt(chapters: FilmChapter[], p: number): number {\n  return chapters.reduce((at, chapter, i) => (p >= chapter.from ? i : at), 0);\n}\n\nexport function VideoScrub({\n  src,\n  fallbackSrc,\n  poster,\n  label = 'Headphones turning, then taken apart layer by layer',\n  chapters = DEFAULT_CHAPTERS,\n  from,\n  to,\n  className = '',\n}: VideoScrubProps) {\n  const trackRef = useRef<HTMLElement>(null);\n  const videoRef = useRef<HTMLVideoElement>(null);\n  const chaptersRef = useRef(chapters);\n  // The film's progress (0 to 1), kept only when it crosses into another\n  // chapter, and the current chapter is worked out from it on every render.\n  // Keeping every frame's progress would re-render 60 times a second. Keeping\n  // a chapter number would go stale when `chapters` changes and no frame\n  // follows, as under reduced motion, where the film reports only once.\n  const [progress, setProgress] = useState(0);\n  const [motionChanges, setMotionChanges] = useState(0);\n\n  // The progress callback reads the latest chapters through a ref, so new\n  // chapters do not restart the film.\n  useEffect(() => {\n    chaptersRef.current = chapters;\n  }, [chapters]);\n\n  // scrollVideo reads prefers-reduced-motion once, when it starts, while the\n  // layout below follows the setting live (motion-safe / motion-reduce). Start\n  // the film again when the setting changes, so the two never disagree.\n  useEffect(() => {\n    const query = window.matchMedia('(prefers-reduced-motion: reduce)');\n    const onChange = () => setMotionChanges((n) => n + 1);\n    query.addEventListener('change', onChange);\n    return () => query.removeEventListener('change', onChange);\n  }, []);\n\n  useEffect(() => {\n    const track = trackRef.current;\n    const video = videoRef.current;\n    if (!track || !video) return;\n\n    const film = scrollVideo(video, {\n      from,\n      to,\n      // The stage is sticky, so the video's own box moves with the scroll.\n      // Measure the track that holds the scroll room instead: `top top` to\n      // `bottom bottom` is exactly the stretch the stage is stuck.\n      triggerElement: track,\n      trigger: { start: 'top top', end: 'bottom bottom' },\n      // Runs every frame while the film is on screen. Handing back the same\n      // value while the chapter is unchanged lets React skip the render. Under\n      // reduced motion it runs once, with 1, for the last frame.\n      onProgress: (p) => {\n        const list = chaptersRef.current;\n        setProgress((kept) => (chapterAt(list, kept) === chapterAt(list, p) ? kept : p));\n      },\n    });\n    // StrictMode mounts effects twice in development: destroy() removes every\n    // listener and observer, so the second run starts clean.\n    return () => film.destroy();\n    // A new `src` or `fallbackSrc` remounts the <video> (see its `key`), so\n    // bind the new element.\n  }, [src, fallbackSrc, from, to, motionChanges]);\n\n  const current = chapterAt(chapters, progress);\n\n  return (\n    // The track holds the scroll room: the stage stays stuck for its height\n    // minus one screen, and the film runs exactly that long. Under reduced\n    // motion there is nothing to scroll through, so it collapses to the stage.\n    <section\n      ref={trackRef}\n      className={`relative h-[400vh] bg-[#121212] text-[#ece8e1] motion-reduce:h-auto ${className}`}\n    >\n      {/* One screen tall, measured on the small viewport (svh) so a phone's\n          address bar never hides the bottom of it; plain vh where svh is not\n          supported. A minimum rather than a fixed height, so content that does\n          not fit (every chapter at once, under reduced motion) grows the stage\n          instead of spilling out of it. */}\n      <div className=\"sticky top-0 box-border grid min-h-screen grid-cols-1 content-center items-center gap-5 px-[6vw] supports-[height:100svh]:min-h-[100svh] md:grid-cols-[minmax(0,1.3fr)_minmax(0,1fr)] md:gap-12 motion-reduce:py-16\">\n        {/* No autoplay and no controls: the scroll is the playhead. With a\n            fallback, the two files become <source>s, tried in order. */}\n        <video\n          key={`${src}|${fallbackSrc ?? ''}`}\n          ref={videoRef}\n          src={fallbackSrc ? undefined : src}\n          poster={poster}\n          muted\n          playsInline\n          preload=\"auto\"\n          aria-label={label}\n          className=\"block aspect-[4/3] h-auto max-h-[80vh] w-full object-cover\"\n        >\n          {fallbackSrc && (\n            <>\n              <source src={src} />\n              <source src={fallbackSrc} type=\"video/mp4\" />\n            </>\n          )}\n        </video>\n\n        {/* On a phone the chapters share one grid cell and cross-fade, so the\n            stage keeps the height of the tallest one and the film above never\n            jumps. Under reduced motion they are all shown, in full, in order. */}\n        <ol className=\"m-0 grid list-none gap-7 p-0\">\n          {chapters.map((chapter, i) => {\n            const isCurrent = i === current;\n            return (\n              <li\n                key={chapter.title}\n                aria-current={isCurrent ? 'step' : undefined}\n                className={`transition-[opacity,visibility,color] duration-300 motion-reduce:transition-none max-md:motion-safe:col-start-1 max-md:motion-safe:row-start-1 ${\n                  isCurrent\n                    ? 'opacity-100'\n                    : 'text-[#817f7c] motion-reduce:text-[#ece8e1] max-md:motion-safe:invisible max-md:motion-safe:opacity-0'\n                }`}\n              >\n                {/* Not the current chapter: greyed by colour, not opacity, so it keeps WCAG AA on the dark ground (at 32% opacity it measured under 2:1). */}\n                <span className={`font-mono text-xs font-semibold leading-none ${isCurrent ? 'text-[#d0a15c]' : 'text-[#9b7947] motion-reduce:text-[#d0a15c]'}`}>\n                  {String(i + 1).padStart(2, '0')}\n                </span>\n                <h3 className=\"mb-1.5 mt-2 text-2xl font-semibold leading-[1.2]\">{chapter.title}</h3>\n                <p className=\"m-0 max-w-[34ch] text-base leading-[1.6]\">{chapter.body}</p>\n              </li>\n            );\n          })}\n        </ol>\n      </div>\n    </section>\n  );\n}\n\nexport default VideoScrub;\n",
      "type": "registry:component",
      "target": "components/scroll/video-scrub.tsx"
    }
  ],
  "categories": [
    "scroll",
    "video"
  ]
}
