{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "time-slider",
  "type": "registry:ui",
  "title": "Time Slider",
  "description": "Step a chart through time: a play button, a slider with one stop per frame (a year, a survey wave, a season), and the current frame printed large beside them. Any chart goes inside: the slider owns which frame is showing, and the chart is drawn for that…",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "data",
    "chart"
  ],
  "dependencies": [
    "@base-ui/react",
    "lucide-react"
  ],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/button.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/slider.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/charts/time-slider.tsx",
      "target": "components/ui/charts/time-slider.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/time-slider v1.0.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/time-slider\n// What changed since: https://ds.interlace.tools/c/time-slider#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — TimeSlider\n *\n * Step a chart through time: a play button, a slider with one stop per\n * frame (a year, a survey wave, a season), and the current frame printed\n * large beside them. Any chart goes inside: the slider owns which frame is\n * showing, and the chart is drawn for that frame by a render function.\n *\n *   <TimeSlider frames={[2016, 2018, 2020, 2022, 2024]}>\n *     {(year) => <ShareChart categories={…} rows={rowsFor(year)} />}\n *   </TimeSlider>\n *\n * ## Content first\n *\n * The server HTML holds the chart for the opening frame (`defaultValue`,\n * the latest frame unless you say otherwise), so a reader without scripts,\n * a search engine and a screenshot all get a whole chart. The controls work\n * once scripts load.\n *\n * ## Play\n *\n * Play steps one frame every `frameDuration` ms (1200 by default) and\n * stops on the last frame, or starts over with `loop`. Pressed on the last\n * frame, it starts from the first, so play always shows a change. Nothing\n * plays on its own: the reader starts it, the same button stops it (WCAG\n * 2.2.2), and touching the slider stops it too. Under reduced motion play\n * still steps, because a step is a change of data the reader asked for,\n * not an animation; the chart inside decides how it draws the new frame.\n *\n * ## Words for every reader\n *\n * The slider's thumb speaks the frame (\"2020\"), not its index. The printed\n * frame is a polite live region while paused, so a keyboard step is\n * announced; while playing it is quiet, so a screen reader is not talked\n * over once a second, and the frame it stops on is announced. Every fixed\n * word comes from `labels`, and numbers print in `locale` without grouping\n * (`formatFrame` in `time-slider-model.ts`, which is pure and exported with\n * `nextFrame`, `playStart` and `clampFrame`).\n *\n * ## Right to left\n *\n * The slider reads the page's direction once it mounts and hands it to Base\n * UI, so in a right-to-left page time runs from right to left, the arrow\n * keys follow it, and the ends swap sides with it.\n *\n * ## MIN_VIEWPORT — 320\n *\n * One row: button, slider, frame. The first and last frames sit under the\n * rail's ends. A tick marks every stop while there are 40 or fewer.\n *\n * ## Anatomy\n *\n *   <div data-slot=\"time-slider\" data-state=\"playing|paused\">\n *     <div data-slot=\"time-slider-stage\">{children(frame, index)}</div>\n *     <div data-slot=\"time-slider-controls\">\n *       <Button data-slot=\"time-slider-play\" />               (Play / Pause)\n *       <div data-slot=\"time-slider-scale\">\n *         <Slider />                                           (one stop per frame)\n *         <div data-slot=\"time-slider-ticks\" aria-hidden />\n *         <div data-slot=\"time-slider-ends\" aria-hidden />     (first and last frame)\n *       </div>\n *       <output data-slot=\"time-slider-value\" />               (the current frame)\n *     </div>\n *   </div>\n *\n * | Rule | Concept                   | Where in this file                                       |\n * | ---- | ------------------------- | -------------------------------------------------------- |\n * | R4   | Extends native el         | `React.ComponentProps<'div'>`                            |\n * | R6   | data-slot per part        | time-slider / -stage / -controls / -play / -scale / -ticks / -ends / -value |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                        |\n * | R9   | Controlled + uncontrolled | `value` / `defaultValue` / `onValueChange`               |\n * | R10  | Composition seam          | `children(frame, index)` draws any chart                 |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                     |\n * | R18  | Tailwind only             | zero inline `style`                                      |\n * | R19  | Tokens only               | primary, input, border, muted-foreground                 |\n * | R25  | Client component          | play timing and the slider run in the browser            |\n * | R26  | A11y                      | labelled slider with value text, named play button, quiet live region while playing |\n */\n\nimport { DirectionProvider } from '@base-ui/react/direction-provider';\nimport { Pause, Play } from 'lucide-react';\n\nimport { cn } from '@/lib/utils';\nimport { Button } from '@/components/ui/button';\nimport { Slider, SliderControl, SliderIndicator, SliderThumb, SliderTrack } from '@/components/ui/slider';\nimport { clampFrame, formatFrame, nextFrame, playStart, type TimeFrame } from '@/components/ui/charts/time-slider-model';\n\nexport { clampFrame, formatFrame, nextFrame, playStart, type TimeFrame } from '@/components/ui/charts/time-slider-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\n/** Ticks are drawn for every stop up to this many frames; past it the rail alone reads better. */\nconst MAX_TICKS = 40;\n/** The fastest play allowed, so a frame is on screen long enough to read. */\nconst MIN_FRAME_MS = 250;\n\nexport type TimeSliderLabels = {\n  /** The play button's name while paused. */\n  play: string;\n  /** The play button's name while playing. */\n  pause: string;\n  /** The slider's name. Name what the frames are, such as \"Year\". */\n  slider: string;\n};\n\nconst LABELS: TimeSliderLabels = {\n  play: 'Play',\n  pause: 'Pause',\n  slider: 'Time',\n};\n\nexport interface TimeSliderProps extends Omit<React.ComponentProps<'div'>, 'children' | 'defaultValue'> {\n  /** The frames, in time order: years, dates, waves. */\n  frames: readonly TimeFrame[];\n  /** Draws the chart for a frame. */\n  children: (frame: TimeFrame, index: number) => React.ReactNode;\n  /** The showing frame's index (controlled). */\n  value?: number;\n  /** The opening frame's index. @default the last frame */\n  defaultValue?: number;\n  /** Called with the new index and its frame on every step: slider, keys or play. */\n  onValueChange?: (index: number, frame: TimeFrame) => void;\n  /** How long each frame shows while playing, in ms. At least 250. @default 1200 */\n  frameDuration?: number;\n  /** Start over from the first frame after the last one while playing. @default false */\n  loop?: boolean;\n  /** A BCP 47 locale for numeric frames. @default the reader's */\n  locale?: string;\n  /** Print a frame yourself, such as a date range. @default `formatFrame` */\n  formatFrame?: (frame: TimeFrame) => string;\n  /** Fixed words, for pages in another language. */\n  labels?: Partial<TimeSliderLabels>;\n}\n\nexport const TimeSlider = React.forwardRef<HTMLDivElement, TimeSliderProps>(function TimeSlider(\n  {\n    frames,\n    children,\n    value,\n    defaultValue,\n    onValueChange,\n    frameDuration = 1200,\n    loop = false,\n    locale,\n    formatFrame: formatProp,\n    labels: labelsProp,\n    className,\n    ...props\n  },\n  ref,\n) {\n  const labels = { ...LABELS, ...labelsProp };\n  const count = frames.length;\n  const [own, setOwn] = React.useState(() => clampFrame(defaultValue ?? count - 1, count));\n  const index = clampFrame(value ?? own, count);\n  const [playing, setPlaying] = React.useState(false);\n  const [direction, setDirection] = React.useState<'ltr' | 'rtl'>('ltr');\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  React.useImperativeHandle(ref, () => rootRef.current as HTMLDivElement);\n\n  const print = React.useCallback(\n    (frame: TimeFrame) => (formatProp ? formatProp(frame) : formatFrame(frame, locale)),\n    [formatProp, locale],\n  );\n\n  // The latest callback and frames, read by the play timer without restarting it.\n  const latest = React.useRef({ onValueChange, frames });\n  latest.current = { onValueChange, frames };\n\n  const go = React.useCallback((next: number) => {\n    const { frames: all, onValueChange: notify } = latest.current;\n    const at = clampFrame(next, all.length);\n    setOwn(at);\n    // Only the controls call this, and they are disabled without frames.\n    notify?.(at, all[at] as TimeFrame);\n  }, []);\n\n  // The page's direction decides which way time runs. Read after mount: the\n  // server cannot know it, and the first paint is the same either way.\n  React.useLayoutEffect(() => {\n    setDirection(getComputedStyle(rootRef.current as HTMLDivElement).direction === 'rtl' ? 'rtl' : 'ltr');\n  }, []);\n\n  // One timeout per frame (not an interval), so a slow render never queues\n  // steps, and pausing is just not scheduling the next one.\n  const duration = Math.max(MIN_FRAME_MS, Number.isFinite(frameDuration) ? frameDuration : 1200);\n  React.useEffect(() => {\n    if (!playing) return;\n    const id = window.setTimeout(() => {\n      const next = nextFrame(index, count, loop);\n      if (next === null) setPlaying(false);\n      else go(next);\n    }, duration);\n    return () => window.clearTimeout(id);\n  }, [playing, index, count, loop, duration, go]);\n\n  // Stop when the frames run out under a playing slider.\n  React.useEffect(() => {\n    if (count <= 1) setPlaying(false);\n  }, [count]);\n\n  const toggle = () => {\n    if (playing) {\n      setPlaying(false);\n      return;\n    }\n    const start = playStart(index, count);\n    if (start !== index) go(start);\n    setPlaying(true);\n  };\n\n  const frame = frames[index];\n  const current = frame === undefined ? '' : print(frame);\n  // Read only when there are two frames or more.\n  const first = frames[0] as TimeFrame;\n  const last = frames[count - 1] as TimeFrame;\n\n  return (\n    <div\n      ref={rootRef}\n      data-slot=\"time-slider\"\n      data-state={playing ? 'playing' : 'paused'}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('flex flex-col gap-4', className)}\n      {...props}\n    >\n      <div data-slot=\"time-slider-stage\" className=\"min-w-0\">\n        {frame === undefined ? null : children(frame, index)}\n      </div>\n\n      <div data-slot=\"time-slider-controls\" className=\"flex items-center gap-4\">\n        <Button\n          type=\"button\"\n          data-slot=\"time-slider-play\"\n          variant=\"outline\"\n          size=\"icon\"\n          aria-label={playing ? labels.pause : labels.play}\n          disabled={count <= 1}\n          onClick={toggle}\n        >\n          {playing ? <Pause aria-hidden /> : <Play aria-hidden />}\n        </Button>\n\n        <div data-slot=\"time-slider-scale\" className=\"flex min-w-0 flex-1 flex-col gap-1\">\n          <DirectionProvider direction={direction}>\n            <Slider\n              value={index}\n              min={0}\n              max={Math.max(1, count - 1)}\n              step={1}\n              disabled={count <= 1}\n              onValueChange={(v) => {\n                setPlaying(false);\n                // One thumb, so Base UI hands back a number.\n                go(v as number);\n              }}\n            >\n              <SliderControl className=\"h-control-xs\">\n                <SliderTrack>\n                  <SliderIndicator />\n                </SliderTrack>\n                <SliderThumb aria-label={labels.slider} getAriaValueText={() => current} />\n              </SliderControl>\n            </Slider>\n          </DirectionProvider>\n          {count > 1 && count <= MAX_TICKS ? (\n            <div data-slot=\"time-slider-ticks\" aria-hidden className=\"flex justify-between\">\n              {frames.map((f, i) => (\n                <span\n                  key={`${String(f)}-${i}`}\n                  className={cn('h-1.5 w-px', i <= index ? 'bg-primary' : 'bg-input')}\n                />\n              ))}\n            </div>\n          ) : null}\n          {count > 1 ? (\n            <div\n              data-slot=\"time-slider-ends\"\n              aria-hidden\n              className=\"flex justify-between gap-2 text-sm tabular-nums text-muted-foreground\"\n            >\n              <span>{print(first)}</span>\n              <span>{print(last)}</span>\n            </div>\n          ) : null}\n        </div>\n\n        <output\n          data-slot=\"time-slider-value\"\n          aria-live={playing ? 'off' : 'polite'}\n          className=\"min-w-[4ch] text-end text-lg font-semibold tabular-nums\"\n        >\n          {current}\n        </output>\n      </div>\n    </div>\n  );\n});\nTimeSlider.displayName = 'TimeSlider';\n"
    },
    {
      "path": "registry/interlace-ui/charts/time-slider-model.ts",
      "target": "components/ui/charts/time-slider-model.ts",
      "type": "registry:ui",
      "content": "export type TimeFrame = string | number;\n\n/** Keep an index inside `0 … count - 1`. A non-finite index lands on the last frame. */\nexport function clampFrame(index: number, count: number): number {\n  if (count <= 0) return 0;\n  if (!Number.isFinite(index)) return count - 1;\n  return Math.min(count - 1, Math.max(0, Math.round(index)));\n}\n\n/**\n * The frame after `index` while playing, or `null` when play should stop.\n * With `loop`, the last frame is followed by the first.\n */\nexport function nextFrame(index: number, count: number, loop = false): number | null {\n  if (count <= 1) return null;\n  const at = clampFrame(index, count);\n  if (at < count - 1) return at + 1;\n  return loop ? 0 : null;\n}\n\n/**\n * Where pressing play starts: from the current frame, unless it is the last\n * one, in which case from the first, so play always shows a change.\n */\nexport function playStart(index: number, count: number): number {\n  const at = clampFrame(index, count);\n  return at >= count - 1 ? 0 : at;\n}\n\n/**\n * Print a frame. Numbers go through `Intl.NumberFormat` without grouping, so\n * the year 2024 prints as \"2024\" and not \"2,024\", in the locale's digits.\n */\nexport function formatFrame(frame: TimeFrame, locale?: string): string {\n  if (typeof frame === 'number') {\n    return Number.isFinite(frame) ? new Intl.NumberFormat(locale, { useGrouping: false }).format(frame) : '';\n  }\n  return frame;\n}\n\n/**\n * @interlace/ui — time slider model\n *\n * The pure steps behind `TimeSlider`: which frame comes next, where play\n * starts, and how a frame is printed. No React and no timers, so a server or\n * a test can step through the same frames the reader does.\n */\n\n/** A frame's key: a year, a date string, a season. */\n"
    }
  ],
  "meta": {
    "tier": "chart",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.0.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/time-slider\n\nInstalled to `components/ui/charts/time-slider.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/charts/time-slider';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/time-slider\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
