# Integrate `TimelineScrubber` from Motion Garden

You are helping me add the **TimelineScrubber** component to an existing project.
Everything you need is below — full source, dependencies, props and the
behavioural contract. Read it all before writing anything.

- **Component:** TimelineScrubber
- **Category:** Power-User Systems
- **Summary:** Drag the head, snap it to markers, zoom into the track and let the viewport follow playback. One derived number — pixels per second — places the ticks, the pips, the head, the drag target and the follow scroll, so nothing on screen can disagree about where a time actually is.
- **Reference:** https://motion-garden.netlify.app/components/timeline-scrubber
- **Full catalog (for you, the agent):** https://motion-garden.netlify.app/llms.txt

## Stack this source assumes

- React 19 with the Next.js App Router (never the `pages/` directory)
- TypeScript, strict
- Tailwind CSS v4, CSS-first config (utilities are inline; no `tailwind.config` needed)

If my project differs, adapt the integration — but do not rewrite the animation math to suit a different stack. Ask me first.

## Dependencies

```bash
bun add lucide-react clsx tailwind-merge
```

## Design tokens this source uses

Some classes in the source are Motion Garden theme tokens, not stock Tailwind (`text-ink`, `bg-panel`, `font-display` and the like). Without them, parts of the component render unstyled. Add this to my global CSS, after the Tailwind import:

```css
@theme {
  --font-display: "Space Mono", ui-monospace, "SFMono-Regular", monospace;
}

@theme inline {
  --color-surface: var(--sg-surface);
  --color-panel: var(--sg-panel);
  --color-raised: var(--sg-raised);
  --color-hairline: var(--sg-hairline);
  --color-ink: var(--sg-ink);
  --color-ink-dim: var(--sg-ink-dim);
  --color-ink-mute: var(--sg-ink-mute);
  --color-accent: var(--sg-accent);
}

:root {
  --sg-surface: #f9f9fb;
  --sg-panel: #ffffff;
  --sg-raised: #eceaef;
  --sg-hairline: #dde2e7;
  --sg-ink: #16191d;
  --sg-ink-dim: #545b64;
  --sg-ink-mute: #878e97;
  --sg-accent: #7e22ce;
}

.dark {
  --sg-surface: #0a0b0c;
  --sg-panel: #101215;
  --sg-raised: #191d21;
  --sg-hairline: #2a2f36;
  --sg-ink: #e2e6e9;
  --sg-ink-dim: #bcc2c8;
  --sg-ink-mute: #6c737c;
  --sg-accent: #a855f7;
}
```

The values are Motion Garden's own light and dark themes. If my project already has tokens for these roles, point the `--sg-*` variables at mine instead and tell me which you mapped. `.dark` assumes class-based dark mode — adapt the selector to how my project switches themes.

`font-display` expects Space Mono, and this CSS only names it. Load the font (with `next/font/google`, for example) or put my own display face first in the stack; until then it falls back to the system monospace.

## Files to create

10 files — all of them are required. Paths are as shipped; the component may live anywhere in my project, but keep every peer file at the exact path shown so the import aliases resolve.

### 1. `components/registry/timeline-scrubber/timeline-scrubber.tsx`

```tsx
"use client";

import {
  useCallback,
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type PointerEvent as ReactPointerEvent,
} from "react";
import { cn } from "@/lib/utils";
import Markers from "./markers";
import Playhead from "./playhead";
import Ruler from "./ruler";
import Transport from "./transport";
import { useTimeline } from "./use-timeline";
import { clamp, formatTimecode, snapToMarkers } from "./util";
import type { FollowMode, TimelineMarker } from "./types";

const MAX_ZOOM = 40;

export interface TimelineScrubberProps {
  markers?: TimelineMarker[];
  className?: string;
  duration?: number;
  fps?: number;
  zoom?: number;
  snapThreshold?: number;
  showRuler?: boolean;
  showMarkers?: boolean;
  loop?: boolean;
  playbackRate?: number;
  follow?: FollowMode;
  trackHeight?: number;
  accent?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  onTimeChange?: (time: number) => void;
}

export default function TimelineScrubber({
  markers = [],
  className,
  duration = 24,
  fps = 30,
  zoom = 1,
  snapThreshold = 10,
  showRuler = true,
  showMarkers = true,
  loop = true,
  playbackRate = 1,
  follow = "page",
  trackHeight = 72,
  accent = "#a855f7",
  paused = false,
  reducedMotion = false,
  onTimeChange,
}: TimelineScrubberProps) {
  const contentRef = useRef<HTMLDivElement>(null);
  const [dragging, setDragging] = useState(false);

  const [zoomLevel, setZoomLevel] = useState(zoom);
  const [seededFrom, setSeededFrom] = useState(zoom);
  if (zoom !== seededFrom) {
    setSeededFrom(zoom);
    setZoomLevel(zoom);
  }

  const timeline = useTimeline({ duration, playbackRate, loop, paused });
  const { time, playing, width, viewportRef, seek, nudge, toggle } = timeline;

  const pxPerSecond = duration > 0 ? (width / duration) * zoomLevel : 0;
  const contentWidth = Math.floor(duration * pxPerSecond);

  useEffect(() => onTimeChange?.(time), [time, onTimeChange]);

  const seekFromClientX = useCallback(
    (clientX: number, bypassSnap: boolean) => {
      const rect = contentRef.current?.getBoundingClientRect();
      if (!rect || pxPerSecond <= 0) return;
      const raw = (clientX - rect.left) / pxPerSecond;
      const snapped =
        bypassSnap || !showMarkers
          ? raw
          : snapToMarkers(raw, markers, snapThreshold / pxPerSecond);
      seek(snapped);
    },
    [markers, pxPerSecond, seek, showMarkers, snapThreshold],
  );

  const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
    if (event.button !== 0 && event.pointerType === "mouse") return;
    event.currentTarget.setPointerCapture(event.pointerId);
    setDragging(true);
    seekFromClientX(event.clientX, event.altKey);
  };

  const onPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {
    if (!dragging) return;
    seekFromClientX(event.clientX, event.altKey);
  };

  const endDrag = (event: ReactPointerEvent<HTMLDivElement>) => {
    if (event.currentTarget.hasPointerCapture(event.pointerId)) {
      event.currentTarget.releasePointerCapture(event.pointerId);
    }
    setDragging(false);
  };

  const anchor = useRef<{ time: number; offset: number } | null>(null);

  useEffect(() => {
    const viewport = viewportRef.current;
    if (!viewport) return;

    const onWheel = (event: WheelEvent) => {
      if (!event.ctrlKey && !event.metaKey) return;
      event.preventDefault();

      const rect = viewport.getBoundingClientRect();
      const offset = event.clientX - rect.left;
      setZoomLevel((current) => {
        const next = clamp(
          current * Math.exp(-event.deltaY * 0.002),
          1,
          MAX_ZOOM,
        );
        if (next === current) return current;
        const factor =
          duration > 0 && width > 0 ? (width / duration) * current : 0;
        if (factor > 0) {
          anchor.current = {
            time: (viewport.scrollLeft + offset) / factor,
            offset,
          };
        }
        return next;
      });
    };

    viewport.addEventListener("wheel", onWheel, { passive: false });
    return () => viewport.removeEventListener("wheel", onWheel);
  }, [duration, viewportRef, width]);

  useLayoutEffect(() => {
    const viewport = viewportRef.current;
    const pending = anchor.current;
    if (!viewport || !pending || pxPerSecond <= 0) return;
    anchor.current = null;
    viewport.scrollLeft = pending.time * pxPerSecond - pending.offset;
  }, [pxPerSecond, viewportRef]);

  useEffect(() => {
    const viewport = viewportRef.current;
    if (!viewport || !playing || follow === "off" || pxPerSecond <= 0) return;

    const head = time * pxPerSecond;
    if (follow === "center") {
      viewport.scrollLeft = head - viewport.clientWidth / 2;
      return;
    }
    const EDGE = 24;
    if (
      head > viewport.scrollLeft + viewport.clientWidth - EDGE ||
      head < viewport.scrollLeft
    ) {
      viewport.scrollLeft = head - EDGE;
    }
  }, [time, playing, follow, pxPerSecond, viewportRef]);

  const frame = 1 / Math.max(fps, 1);

  return (
    <div
      className={cn(
        "flex w-full flex-col gap-3 rounded-2xl border border-hairline bg-panel p-3",
        className,
      )}
    >
      <Transport
        playing={playing}
        timecode={formatTimecode(time, fps)}
        accent={accent}
        onToggle={toggle}
        onStart={() => seek(0)}
        onEnd={() => seek(duration)}
        onStepBack={() => nudge(-frame)}
        onStepForward={() => nudge(frame)}
      />

      <div className="w-full overflow-hidden rounded-lg border border-hairline bg-surface focus-within:border-accent">
        <div
          ref={viewportRef}
          tabIndex={0}
          role="slider"
          aria-label="Timeline position"
          aria-valuemin={0}
          aria-valuemax={duration}
          aria-valuenow={Number(time.toFixed(2))}
          aria-valuetext={formatTimecode(time, fps)}
          className="relative w-full overflow-x-auto overscroll-x-contain outline-none"
          onKeyDown={(event) => {
            if (event.key === " ") {
              event.preventDefault();
              toggle();
              return;
            }
            if (event.key === "Home") {
              event.preventDefault();
              seek(0);
              return;
            }
            if (event.key === "End") {
              event.preventDefault();
              seek(duration);
              return;
            }
            const back = event.key === "ArrowLeft";
            const forward = event.key === "ArrowRight";
            if (!back && !forward) return;
            event.preventDefault();
            const stride = event.shiftKey ? 1 : frame;
            nudge(forward ? stride : -stride);
          }}
        >
          <div
            ref={contentRef}
            className="relative"
            style={{ width: contentWidth || "100%" }}
          >
            {showRuler ? (
              <Ruler
              duration={duration}
              fps={fps}
              pxPerSecond={pxPerSecond}
              width={contentWidth}
            />
            ) : null}

            <div
              className="relative cursor-crosshair"
              style={{ height: trackHeight }}
              onPointerDown={onPointerDown}
              onPointerMove={onPointerMove}
              onPointerUp={endDrag}
              onPointerCancel={endDrag}
            >
              <div
                aria-hidden
                className="absolute inset-0 opacity-40"
                style={{
                  backgroundImage: `repeating-linear-gradient(90deg, color-mix(in oklab, var(--color-raised) 90%, transparent) 0 1px, transparent 1px ${Math.max(pxPerSecond, 1)}px)`,
                }}
              />
              <div
                aria-hidden
                className="absolute inset-x-0 top-1/2 h-8 -translate-y-1/2 rounded-md border border-hairline bg-raised/60"
              />
              {showMarkers ? (
                <Markers
                  markers={markers}
                  pxPerSecond={pxPerSecond}
                  accent={accent}
                  onSeek={seek}
                />
              ) : null}
            </div>

            <Playhead
              x={time * pxPerSecond}
              accent={accent}
              dragging={dragging && !reducedMotion}
            />
          </div>
        </div>
      </div>
    </div>
  );
}
```

### 2. `components/registry/timeline-scrubber/types.ts` — supporting file, required

```tsx
export interface TimelineMarker {
  id: string;
  time: number;
  label: string;
  color?: string;
}

export type FollowMode = "off" | "page" | "center";
```

### 3. `components/registry/timeline-scrubber/util.ts` — supporting file, required

```tsx
import type { TimelineMarker } from "./types";

export function clamp(value: number, min: number, max: number): number {
  return value < min ? min : value > max ? max : value;
}

const pad = (value: number) => String(Math.floor(value)).padStart(2, "0");

export function formatTimecode(seconds: number, fps: number): string {
  const safe = Math.max(0, seconds);
  const whole = Math.floor(safe);
  const frames = Math.floor((safe - whole) * fps);
  return `${pad(whole / 60)}:${pad(whole % 60)}:${pad(frames)}`;
}

const LADDER = [1 / 24, 0.1, 0.25, 0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600];

export function tickStep(pxPerSecond: number, minGapPx = 72): number {
  for (const step of LADDER) {
    if (step * pxPerSecond >= minGapPx) return step;
  }
  return LADDER[LADDER.length - 1];
}

export function buildTicks(duration: number, step: number): number[] {
  const count = Math.floor(duration / step);
  const out: number[] = [];
  for (let i = 0; i <= count; i++) out.push(i * step);
  return out;
}

export function snapToMarkers(
  time: number,
  markers: TimelineMarker[],
  tolerance: number,
): number {
  let best = time;
  let bestDelta = tolerance;
  for (const marker of markers) {
    const delta = Math.abs(marker.time - time);
    if (delta < bestDelta) {
      bestDelta = delta;
      best = marker.time;
    }
  }
  return best;
}
```

### 4. `components/registry/timeline-scrubber/use-timeline.ts` — supporting file, required

```tsx
"use client";

import {
  useCallback,
  useLayoutEffect,
  useRef,
  useState,
  type RefObject,
} from "react";
import { useAnimationLoop } from "@/hooks/use-animation-loop";
import { clamp } from "./util";

export interface UseTimelineOptions {
  duration: number;
  playbackRate: number;
  loop: boolean;
  paused: boolean;
}

export interface Timeline {
  time: number;
  playing: boolean;
  width: number;
  viewportRef: RefObject<HTMLDivElement | null>;
  play(): void;
  pause(): void;
  toggle(): void;
  seek(time: number): void;
  nudge(delta: number): void;
}

export function useTimeline(options: UseTimelineOptions): Timeline {
  const viewportRef = useRef<HTMLDivElement>(null);

  const [time, setTime] = useState(0);
  const [playing, setPlaying] = useState(false);
  const [width, setWidth] = useState(0);

  const live = useRef(options);
  useLayoutEffect(() => {
    live.current = options;
  });

  const timeRef = useRef(0);

  const seek = useCallback((next: number) => {
    const clamped = clamp(next, 0, live.current.duration);
    timeRef.current = clamped;
    setTime(clamped);
  }, []);

  useAnimationLoop({
    target: viewportRef,
    halted: !playing || options.paused,
    onResize: ({ width: measured }) => setWidth(measured),
    onFrame: ({ dt }) => {
      const { duration, playbackRate, loop } = live.current;
      const next = timeRef.current + dt * playbackRate;

      if (next < duration) {
        timeRef.current = next;
        setTime(next);
        return;
      }

      if (loop) {
        const wrapped = duration > 0 ? next % duration : 0;
        timeRef.current = wrapped;
        setTime(wrapped);
        return;
      }

      timeRef.current = duration;
      setTime(duration);
      setPlaying(false);
      return false;
    },
  });

  const play = useCallback(() => {
    if (timeRef.current >= live.current.duration) seek(0);
    setPlaying(true);
  }, [seek]);

  const pause = useCallback(() => setPlaying(false), []);
  const toggle = useCallback(() => {
    if (playing) pause();
    else play();
  }, [playing, pause, play]);

  const nudge = useCallback((delta: number) => seek(timeRef.current + delta), [seek]);

  return { time, playing, width, viewportRef, play, pause, toggle, seek, nudge };
}
```

### 5. `components/registry/timeline-scrubber/ruler.tsx` — supporting file, required

```tsx
"use client";

import { cn } from "@/lib/utils";
import { buildTicks, formatTimecode, tickStep } from "./util";

export default function Ruler({
  duration,
  fps,
  pxPerSecond,
  width,
  className,
}: {
  duration: number;
  fps: number;
  pxPerSecond: number;
  width: number;
  className?: string;
}) {
  const major = tickStep(pxPerSecond);
  const minor = major / 5;

  const inside = (time: number) => time * pxPerSecond < width - 0.5;

  return (
    <div
      className={cn(
        "relative h-7 border-b border-hairline select-none",
        className,
      )}
      style={{ width }}
      aria-hidden
    >
      {buildTicks(duration, minor)
        .filter(inside)
        .map((time) => (
          <span
            key={`m-${time}`}
            className="absolute bottom-0 w-px bg-hairline"
            style={{ left: time * pxPerSecond, height: 6 }}
          />
        ))}

      {buildTicks(duration, major)
        .filter(inside)
        .map((time) => (
          <div
            key={`M-${time}`}
            className="absolute bottom-0 flex flex-col items-start"
            style={{ left: time * pxPerSecond }}
          >
            <span className="pl-1 font-mono text-[10px] tabular-nums text-ink-mute">
              {formatTimecode(time, fps)}
            </span>
            <span className="w-px bg-ink-mute/60" style={{ height: 10 }} />
          </div>
        ))}
    </div>
  );
}
```

### 6. `components/registry/timeline-scrubber/markers.tsx` — supporting file, required

```tsx
"use client";

import { cn } from "@/lib/utils";
import type { TimelineMarker } from "./types";

export default function Markers({
  markers,
  pxPerSecond,
  accent,
  onSeek,
  className,
}: {
  markers: TimelineMarker[];
  pxPerSecond: number;
  accent: string;
  onSeek: (time: number) => void;
  className?: string;
}) {
  return (
    <div className={cn("pointer-events-none absolute inset-0", className)}>
      {markers.map((marker) => (
        <button
          key={marker.id}
          type="button"
          onClick={() => onSeek(marker.time)}
          title={marker.label}
          aria-label={`Jump to ${marker.label}`}
          className={cn(
            "pointer-events-auto absolute top-0 flex -translate-x-1/2 flex-col items-center gap-1 outline-none",
            "focus-visible:ring-1 focus-visible:ring-(--marker-color) rounded-sm",
          )}
          style={
            {
              left: marker.time * pxPerSecond,
              "--marker-color": marker.color ?? accent,
            } as React.CSSProperties
          }
        >
          <span
            className="h-2 w-2 rotate-45 rounded-[2px]"
            style={{ backgroundColor: marker.color ?? accent }}
          />
          <span className="max-w-24 truncate font-display text-[9px] tracking-[0.14em] text-ink-mute uppercase">
            {marker.label}
          </span>
        </button>
      ))}
    </div>
  );
}
```

### 7. `components/registry/timeline-scrubber/playhead.tsx` — supporting file, required

```tsx
"use client";

import { cn } from "@/lib/utils";

export default function Playhead({
  x,
  accent,
  dragging,
  className,
}: {
  x: number;
  accent: string;
  dragging: boolean;
  className?: string;
}) {
  return (
    <div
      className={cn("pointer-events-none absolute inset-y-0 left-0 z-20", className)}
      style={{ transform: `translate3d(${x}px, 0, 0)` }}
      aria-hidden
    >
      <span
        className="absolute inset-y-0 -left-px w-0.5"
        style={{ backgroundColor: accent }}
      />
      <span
        className={cn(
          "pointer-events-auto absolute -top-1 -left-1.5 h-3 w-3 cursor-grab rounded-[3px] transition-transform",
          dragging && "scale-125 cursor-grabbing",
        )}
        style={{ backgroundColor: accent }}
      />
    </div>
  );
}
```

### 8. `components/registry/timeline-scrubber/transport.tsx` — supporting file, required

```tsx
"use client";

import {
  ChevronFirst,
  ChevronLast,
  Pause,
  Play,
  SkipBack,
  SkipForward,
} from "lucide-react";
import { cn } from "@/lib/utils";

export default function Transport({
  playing,
  timecode,
  accent,
  onToggle,
  onStart,
  onEnd,
  onStepBack,
  onStepForward,
  className,
}: {
  playing: boolean;
  timecode: string;
  accent: string;
  onToggle: () => void;
  onStart: () => void;
  onEnd: () => void;
  onStepBack: () => void;
  onStepForward: () => void;
  className?: string;
}) {
  const button =
    "flex h-7 w-7 items-center justify-center rounded-md border border-hairline bg-raised text-ink-dim outline-none transition-colors hover:text-ink focus-visible:text-ink [&_svg]:h-3.5 [&_svg]:w-3.5";

  return (
    <div className={cn("flex items-center gap-2", className)}>
      <button type="button" onClick={onStart} aria-label="Go to start" className={button}>
        <ChevronFirst />
      </button>
      <button type="button" onClick={onStepBack} aria-label="Previous frame" className={button}>
        <SkipBack />
      </button>

      <button
        type="button"
        onClick={onToggle}
        aria-label={playing ? "Pause" : "Play"}
        aria-pressed={playing}
        className={cn(button, "h-8 w-8")}
        style={playing ? { borderColor: accent, color: accent } : undefined}
      >
        {playing ? <Pause /> : <Play />}
      </button>

      <button type="button" onClick={onStepForward} aria-label="Next frame" className={button}>
        <SkipForward />
      </button>
      <button type="button" onClick={onEnd} aria-label="Go to end" className={button}>
        <ChevronLast />
      </button>

      <span className="ml-1 font-mono text-xs tabular-nums text-ink">{timecode}</span>
    </div>
  );
}
```

### 9. `lib/utils.ts` — peer util, required

```tsx
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}
```

### 10. `hooks/use-animation-loop.ts` — peer hook, required

```tsx
"use client";

import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react";

export interface Metrics {
  width: number;
  height: number;
  dpr: number;
  bufferWidth: number;
  bufferHeight: number;
}

export interface FrameInfo {
  now: number;
  dt: number;
  elapsed: number;
  frame: number;
}

export interface AnimationLoopHandle {
  start(): void;
  stop(): void;
  paint(): void;
  resize(): void;
  readonly running: boolean;
}

export interface AnimationLoopOptions {
  target: React.RefObject<HTMLElement | null>;
  halted?: boolean;
  dpr?: number | "auto";
  onResize?(metrics: Metrics): void;
  onFrame?(info: FrameInfo): void | false;
  paintWhenHalted?: boolean;
  resizeDebounceMs?: number;
  gl?(): WebGLRenderingContext | WebGL2RenderingContext | null | undefined;
  onDispose?(): void;
  deps?: unknown[];
}

const MAX_DT = 1 / 15;

export function useAnimationLoop(
  options: AnimationLoopOptions,
): AnimationLoopHandle {
  const opts = useRef(options);
  useLayoutEffect(() => {
    opts.current = options;
  });

  const raf = useRef<number | null>(null);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const running = useRef(false);
  const disposed = useRef(false);
  const startedAt = useRef(0);
  const last = useRef(0);
  const frame = useRef(0);

  const measure = useCallback((): Metrics | null => {
    const el = opts.current.target.current;
    if (!el) return null;
    const rect = el.getBoundingClientRect();
    const cap = opts.current.dpr ?? "auto";
    const limit = cap === "auto" ? 2 : cap;
    const dpr = Math.min(
      typeof window === "undefined" ? 1 : window.devicePixelRatio || 1,
      limit,
    );
    return {
      width: rect.width,
      height: rect.height,
      dpr,
      bufferWidth: Math.max(1, Math.round(rect.width * dpr)),
      bufferHeight: Math.max(1, Math.round(rect.height * dpr)),
    };
  }, []);

  const tick = useCallback(function tick(now: number) {
    if (disposed.current) return;

    if (startedAt.current === 0) startedAt.current = now;
    const dt = last.current === 0 ? 0 : Math.min((now - last.current) / 1000, MAX_DT);
    last.current = now;

    const info: FrameInfo = {
      now,
      dt,
      elapsed: (now - startedAt.current) / 1000,
      frame: frame.current++,
    };

    const verdict = opts.current.onFrame?.(info);

    if (disposed.current) return;

    if (verdict === false || opts.current.halted) {
      running.current = false;
      raf.current = null;
      return;
    }
    raf.current = requestAnimationFrame(tick);
  }, []);

  const start = useCallback(() => {
    if (disposed.current || running.current) return;
    running.current = true;
    last.current = 0;
    raf.current = requestAnimationFrame(tick);
  }, [tick]);

  const stop = useCallback(() => {
    running.current = false;
    if (raf.current !== null) {
      cancelAnimationFrame(raf.current);
      raf.current = null;
    }
  }, []);

  const paint = useCallback(() => start(), [start]);

  const resize = useCallback(() => {
    const metrics = measure();
    if (!metrics) return;
    opts.current.onResize?.(metrics);
    if (opts.current.paintWhenHalted !== false) paint();
    else if (!opts.current.halted) start();
  }, [measure, paint, start]);

  const deps = options.deps ?? [];

  useEffect(() => {
    disposed.current = false;
    const el = opts.current.target.current;
    if (!el) return;

    const run = () => {
      if (disposed.current) return;
      resize();
    };

    const observer = new ResizeObserver(() => {
      const wait = opts.current.resizeDebounceMs ?? 0;
      if (wait <= 0) {
        run();
        return;
      }
      if (timer.current !== null) clearTimeout(timer.current);
      timer.current = setTimeout(() => {
        timer.current = null;
        run();
      }, wait);
    });
    observer.observe(el);

    resize();
    if (!opts.current.halted) start();

    return () => {
      disposed.current = true;
      running.current = false;
      if (raf.current !== null) {
        cancelAnimationFrame(raf.current);
        raf.current = null;
      }
      if (timer.current !== null) {
        clearTimeout(timer.current);
        timer.current = null;
      }
      observer.disconnect();
      opts.current.onDispose?.();
      const context = opts.current.gl?.();
      context?.getExtension("WEBGL_lose_context")?.loseContext();
      startedAt.current = 0;
      last.current = 0;
      frame.current = 0;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);

  const halted = options.halted ?? false;
  useEffect(() => {
    if (!halted) start();
  }, [halted, start]);

  return useMemo<AnimationLoopHandle>(
    () => ({
      start,
      stop,
      paint,
      resize,
      get running() {
        return running.current;
      },
    }),
    [start, stop, paint, resize],
  );
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `duration` | `number` | `24` | Total length of the timeline. Everything on screen is a fraction of it, so shortening it zooms the whole track in rather than trimming the right-hand end off. Range 4–600 s. |
| `fps` | `number` | `30` | Frames per second. Sets the last field of the timecode and the size of an arrow-key step — one frame, because a finer step would move the head without moving the readout, which reads as the control being broken. Range 8–120. |
| `zoom` | `number` | `1` | Initial horizontal zoom; Ctrl/Cmd + wheel overrides it live and holds the time under the cursor fixed while it does. 1 fits the whole duration in the viewport, which is the only zoom at which the scrollbar is guaranteed absent. Range 1–40 ×. |
| `snapThreshold` | `number` | `10` | How close the pointer has to be to a marker to snap onto it. Specified in pixels and converted through the current zoom, because what makes a snap feel right is the distance on screen — a tolerance in seconds is generous zoomed out, unusable zoomed in, and needs re-tuning at every zoom. Hold Alt while dragging to bypass it. Range 0–40 px. |
| `showRuler` | `boolean` | `true` | Show the tick ruler above the lane. Its divisions come off a fixed 1-2-5 ladder rather than being computed, so zooming walks through the same handful of intervals instead of inventing a new one at every step. |
| `showMarkers` | `boolean` | `true` | Show the marker pips. Off also disables snapping — there is nothing to snap to, and leaving invisible snap targets on the track is how a scrubber earns a reputation for fighting you. |
| `loop` | `boolean` | `true` | Wrap to the start on reaching the end. The overshoot carries across the wrap rather than being discarded, so a looping timeline does not run gradually slow at high playback rates. |
| `playbackRate` | `number` | `1` | Playback speed. The clock advances by real elapsed time from the runtime host, not by a fixed increment per frame, so a dropped frame costs a frame of smoothness and never a frame of time. Range 0.1–8 ×. |
| `follow` | `"off" | "page" | "center"` | `"page"` | What the viewport does when the head runs past its edge while playing. Page jumps a whole viewport and leaves the ruler still most of the time, which is what makes it readable; center pins the head and moves the world instead, which never loses it but never lets the ruler rest. |
| `trackHeight` | `number` | `72` | Height of the lane under the ruler. The playhead spans ruler and lane together, so this changes how much of the track the head has to cross rather than how tall the component's chrome is. Range 40–180 px. |
| `accent` | `string (hex)` | `"#a855f7"` | Playhead, the active transport button, and any marker that does not carry its own colour. |

## Usage

```tsx
import TimelineScrubber from "@/components/registry/timeline-scrubber/timeline-scrubber";

<TimelineScrubber
  duration={24}
  fps={30}
  zoom={1}
  snapThreshold={10}
  showRuler={true}
  showMarkers={true}
  loop={true}
  playbackRate={1}
  follow="page"
  trackHeight={72}
  accent="#a855f7"
/>
```

The import path matches the file path above; change it if you move the component. Every value shown is the documented default — pass only what you actually want to change. The snippet lists the tunable props only: if the component's props type in the source requires others (content, handlers, data), pass those too.

## Integration rules

- Keep the `"use client"` directive. This is a client component and will not render as a Server Component.
- It fills its parent. Give the wrapper an explicit height (or a definite grid area) — against a height-auto parent it collapses to nothing.
- It takes a `reducedMotion` prop and quiesces when true. Wire it to a `prefers-reduced-motion` listener rather than hardcoding `false`.
- It runs a free-running animation loop. Halt it when off-screen or backgrounded if you care about battery.
- The peer hook is required, not optional. Copy it to `hooks/use-animation-loop.ts` so the component's `@/hooks/use-animation-loop` import resolves.
- `lib/utils.ts` is required, not optional. It exports the `cn` helper the component imports from `@/lib/utils` — keep it at that path, or rewrite every `cn` import to wherever you already keep yours. If your project is shadcn-based you almost certainly have this file already; keep yours and drop mine.
- The supporting files are part of the component, not examples. Copy every file listed, preserving the directory layout — they import each other by relative path.
- It owns a GPU/canvas context and releases it on unmount. Preserve the cleanup return — leaking contexts kills the tab after a few navigations.

## Your task

1. Tell me where in my project this should live and why.
2. Create the files above verbatim.
3. Add the design tokens to my global CSS, or map them to tokens I already have.
4. Wire the component into the place I point you at, with sensible props for that context.
5. Flag anything in my setup that conflicts with the stack assumptions above.

Do not restyle the component or alter the animation math unless I ask.
