{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "scrubber",
  "type": "registry:ui",
  "title": "Scrubber",
  "description": "The time bar of a player: a slider over the length of a clip that shows what has played and what has loaded, marks chapters, and can show the time and a picture for the moment under the pointer.",
  "categories": [
    "ui"
  ],
  "dependencies": [
    "radix-ui"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/cn",
    "@rivier-ui/use-controllable-state",
    "@rivier-ui/use-media"
  ],
  "files": [
    {
      "path": "registry/ui/scrubber.tsx",
      "type": "registry:ui",
      "target": "components/ui/scrubber.tsx",
      "content": "\"use client\";\n/**\n * @name scrubber\n * @category ui\n * @description The time bar of a player: a slider over the length of a clip that shows what has played and what has loaded, marks chapters, and can show the time and a picture for the moment under the pointer.\n * @when Seeking in audio, video or any timeline measured in seconds. video-player and audio-player already contain one bound to their media; use this directly for a custom player or a timeline. For choosing a number that is not a time use slider. Time runs left to right in every language (as on players everywhere: the bar is a picture of time, like a clock face, not a line of text), so the bar and its arrow keys are not mirrored in right-to-left pages; pass `dir=\"rtl\"` if a product decides otherwise, and the keys follow what is drawn.\n * @example\n * // Uncontrolled\n * <Scrubber duration={200} defaultValue={65} aria-label=\"Seek\" onValueCommit={(time) => player.seek(time)} />\n *\n * // Controlled by the player's clock, with chapters and a preview picture from a sprite sheet\n * <Scrubber\n *   value={time}\n *   duration={duration}\n *   buffered={[[0, 90]]}\n *   marks={[{ time: 0, label: \"Opening\" }, { time: 60, label: \"The climb\" }]}\n *   onValueCommit={seek}\n *   aria-label=\"Seek\"\n * >\n *   <ScrubberTrack />\n *   <ScrubberThumb />\n *   <ScrubberPreview thumbnail={{ url: \"/sprite.jpg\", columns: 10, rows: 10, interval: 2 }} />\n * </Scrubber>\n */\nimport { Slider as SliderPrimitive } from \"radix-ui\";\nimport { createContext, use, useRef, useState, type ComponentProps, type KeyboardEvent, type PointerEvent, type ReactNode } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport { useControllableState } from \"@/lib/use-controllable-state\";\nimport { describeMediaTime, formatMediaTime } from \"@/lib/use-media\";\n\n/** A named moment on the bar: the start of a chapter or a scene. */\nexport type ScrubberMark = { time: number; label: string };\n\n/** One picture file holding a grid of stills, one every `interval` seconds, left to right then top to bottom. */\nexport type ScrubberSprite = { url: string; columns: number; rows: number; interval: number; aspect?: number };\n\ntype ScrubberContextValue = {\n  value: number;\n  duration: number;\n  buffered: readonly (readonly [number, number])[];\n  marks: readonly ScrubberMark[];\n  locale: string | undefined;\n  label: { \"aria-label\"?: string | undefined; \"aria-labelledby\"?: string | undefined; \"aria-describedby\"?: string | undefined };\n  valueText: string;\n  /** The time the preview shows, or null when it is hidden. */\n  previewTime: number | null;\n  setThumbFocused: (focused: boolean) => void;\n};\n\nconst ScrubberContext = createContext<ScrubberContextValue | null>(null);\n\nfunction useScrubber(part: string): ScrubberContextValue {\n  const context = use(ScrubberContext);\n  if (!context) throw new Error(`<${part}> must be used inside <Scrubber>.`);\n  return context;\n}\n\n/** The mark a time falls in: the last one that starts at or before it. */\nexport function markAt(marks: readonly ScrubberMark[], time: number): ScrubberMark | undefined {\n  let found: ScrubberMark | undefined;\n  for (const mark of marks) if (mark.time <= time && (!found || mark.time >= found.time)) found = mark;\n  return found;\n}\n\nexport type ScrubberProps = Omit<ComponentProps<typeof SliderPrimitive.Root>, \"value\" | \"defaultValue\" | \"onValueChange\" | \"onValueCommit\" | \"min\" | \"max\" | \"orientation\" | \"inverted\" | \"minStepsBetweenThumbs\"> & {\n  /** The current time in seconds: controlled, usually the player's clock. */\n  value?: number;\n  /** The starting time when uncontrolled. Default 0. */\n  defaultValue?: number;\n  /** Called while the thumb is dragged and on every key press. */\n  onValueChange?: (time: number) => void;\n  /** Called once when the drag ends or a key is pressed: seek here. */\n  onValueCommit?: (time: number) => void;\n  /** The length in seconds. 0 or less (not known yet) disables the bar. */\n  duration: number;\n  /** Loaded ranges as [start, end] in seconds, drawn under the played part. */\n  buffered?: readonly (readonly [number, number])[];\n  /** Chapters or scenes: ticks on the bar, and their names in the preview and in what a screen reader says. */\n  marks?: readonly ScrubberMark[];\n  /** What Left and Right move by, in seconds. Default 5. */\n  keyStep?: number;\n  /** What Page Up and Page Down (and Shift with an arrow) move by, in seconds. Default 30. */\n  pageStep?: number;\n  /** The language tag times are formatted for. */\n  locale?: string;\n  /** What a screen reader says for a position. Default: \"1 minute 5 seconds of 3 minutes 20 seconds\", then the chapter. Replace it to translate \"of\". */\n  valueText?: (time: number, duration: number, mark: ScrubberMark | undefined) => string;\n  /** The parts. Default: ScrubberTrack and ScrubberThumb. */\n  children?: ReactNode;\n};\n\n/**\n * A slider (role=\"slider\" on the thumb). Right moves forward and Left back by `keyStep`; Page Up and Page\n * Down by `pageStep`; Home and End go to the start and the end. While the thumb is dragged the bar shows the\n * drag, not `value`, so a clock that keeps running does not pull the thumb away. Name it with `aria-label`\n * (\"Seek\") or `aria-labelledby`.\n */\nexport function Scrubber({\n  className,\n  value,\n  defaultValue = 0,\n  onValueChange,\n  onValueCommit,\n  duration,\n  buffered = [],\n  marks = [],\n  step = 0.1,\n  keyStep = 5,\n  pageStep = 30,\n  dir = \"ltr\",\n  locale,\n  valueText,\n  disabled,\n  children,\n  onKeyDown,\n  onPointerDown,\n  onPointerMove,\n  onPointerLeave,\n  onPointerUp,\n  onPointerCancel,\n  \"aria-label\": ariaLabel,\n  \"aria-labelledby\": ariaLabelledBy,\n  \"aria-describedby\": ariaDescribedBy,\n  ...props\n}: ScrubberProps) {\n  const known = Number.isFinite(duration) && duration > 0;\n  const length = known ? duration : 1;\n  const [time, setTime] = useControllableState({ value, defaultValue, onChange: onValueChange });\n  /** Where the thumb is being dragged to, until it is let go. */\n  const [drag, setDrag] = useState<number | null>(null);\n  const [pressed, setPressed] = useState(false);\n  /** The same as `pressed`, readable in the handlers of the press that set it. */\n  const pressing = useRef(false);\n  const [pointerTime, setPointerTime] = useState<number | null>(null);\n  const [thumbFocused, setThumbFocused] = useState(false);\n  const shown = Math.min(length, Math.max(0, drag ?? time));\n\n  const timeAt = (event: PointerEvent<HTMLElement>): number => {\n    const rect = event.currentTarget.getBoundingClientRect();\n    const fraction = rect.width > 0 ? Math.min(1, Math.max(0, (event.clientX - rect.left) / rect.width)) : 0;\n    return (dir === \"rtl\" ? 1 - fraction : fraction) * length;\n  };\n\n  const handleKeyDown = (event: KeyboardEvent<HTMLSpanElement>): void => {\n    onKeyDown?.(event);\n    if (event.defaultPrevented) return;\n    const forward = dir === \"rtl\" ? \"ArrowLeft\" : \"ArrowRight\";\n    const back = dir === \"rtl\" ? \"ArrowRight\" : \"ArrowLeft\";\n    const large = event.shiftKey ? pageStep : keyStep;\n    const moves: Record<string, number | undefined> = { [forward]: large, [back]: -large, ArrowUp: large, ArrowDown: -large, PageUp: pageStep, PageDown: -pageStep };\n    const move = moves[event.key];\n    if (move === undefined) return;\n    // The slider's own arrow step is its pointer resolution (a tenth of a second); a key press moves by seconds.\n    event.preventDefault();\n    const next = Math.min(length, Math.max(0, shown + move));\n    setTime(next);\n    onValueCommit?.(next);\n  };\n\n  const mark = markAt(marks, shown);\n  const text = !known ? \"\" : valueText ? valueText(shown, duration, mark) : defaultValueText(shown, duration, mark, locale);\n  const previewTime = !known ? null : pressed ? shown : (pointerTime ?? (thumbFocused ? shown : null));\n\n  return (\n    <ScrubberContext\n      value={{\n        value: shown,\n        duration: length,\n        buffered,\n        marks,\n        locale,\n        label: { \"aria-label\": ariaLabel, \"aria-labelledby\": ariaLabelledBy, \"aria-describedby\": ariaDescribedBy },\n        valueText: text,\n        previewTime,\n        setThumbFocused,\n      }}\n    >\n      <SliderPrimitive.Root\n        data-slot=\"scrubber\"\n        dir={dir}\n        min={0}\n        max={length}\n        step={step}\n        value={[shown]}\n        disabled={disabled || !known}\n        onValueChange={([next]) => {\n          if (next === undefined) return;\n          // Only a pointer drags: Home and End commit at once.\n          if (pressing.current) setDrag(next);\n          setTime(next);\n        }}\n        onValueCommit={([next]) => {\n          setDrag(null);\n          if (next !== undefined) onValueCommit?.(next);\n        }}\n        onKeyDown={handleKeyDown}\n        onPointerDown={(event) => {\n          onPointerDown?.(event);\n          pressing.current = true;\n          setPressed(true);\n        }}\n        onPointerMove={(event) => {\n          onPointerMove?.(event);\n          setPointerTime(timeAt(event));\n        }}\n        onPointerLeave={(event) => {\n          onPointerLeave?.(event);\n          setPointerTime(null);\n        }}\n        onPointerUp={(event) => {\n          onPointerUp?.(event);\n          pressing.current = false;\n          setPressed(false);\n          setDrag(null);\n          if (event.pointerType !== \"mouse\") setPointerTime(null);\n        }}\n        onPointerCancel={(event) => {\n          onPointerCancel?.(event);\n          pressing.current = false;\n          setPressed(false);\n          setDrag(null);\n          setPointerTime(null);\n        }}\n        className={cn(\n          \"group/scrubber relative flex h-6 w-full min-w-0 touch-none items-center select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 pointer-coarse:h-10\",\n          className,\n        )}\n        {...props}\n      >\n        {children ?? (\n          <>\n            <ScrubberTrack />\n            <ScrubberThumb />\n          </>\n        )}\n      </SliderPrimitive.Root>\n    </ScrubberContext>\n  );\n}\n\nfunction defaultValueText(time: number, duration: number, mark: ScrubberMark | undefined, locale?: string): string {\n  const position = `${describeMediaTime(time, locale)} of ${describeMediaTime(duration, locale)}`;\n  return mark ? `${position}, ${mark.label}` : position;\n}\n\n/** A position along the bar as an inline-start offset, so it follows the bar's own direction. */\nconst along = (time: number, duration: number): string => `${Math.min(100, Math.max(0, (time / duration) * 100))}%`;\n\n/** The bar: what has loaded, what has played, and the marks. */\nexport function ScrubberTrack({ className, children, ...props }: ComponentProps<typeof SliderPrimitive.Track>) {\n  const { buffered, duration } = useScrubber(\"ScrubberTrack\");\n  return (\n    <SliderPrimitive.Track data-slot=\"scrubber-track\" className={cn(\"relative h-1.5 w-full grow overflow-hidden rounded-full bg-border-strong\", className)} {...props}>\n      {buffered.map(([start, end]) => (\n        <span\n          key={`${start}-${end}`}\n          data-slot=\"scrubber-buffered\"\n          className=\"absolute inset-y-0 bg-muted-foreground opacity-50\"\n          style={{ insetInlineStart: along(start, duration), width: along(end - start, duration) }}\n        />\n      ))}\n      <SliderPrimitive.Range data-slot=\"scrubber-range\" className=\"absolute h-full bg-primary\" />\n      {children ?? <ScrubberMarks />}\n    </SliderPrimitive.Track>\n  );\n}\n\n/** A gap in the bar where each chapter or scene starts. Decoration: the names are in the preview and in the slider's value text. */\nexport function ScrubberMarks({ className, ...props }: ComponentProps<\"span\">) {\n  const { marks, duration } = useScrubber(\"ScrubberMarks\");\n  return (\n    <span data-slot=\"scrubber-marks\" aria-hidden=\"true\" className={cn(\"pointer-events-none absolute inset-0\", className)} {...props}>\n      {marks\n        .filter((mark) => mark.time > 0 && mark.time < duration)\n        .map((mark) => (\n          <span key={mark.time} data-slot=\"scrubber-mark\" className=\"absolute inset-y-0 w-0.5 bg-background\" style={{ insetInlineStart: along(mark.time, duration) }} />\n        ))}\n    </span>\n  );\n}\n\n/** The handle: the element that is the slider. Its target is 40px whatever its drawn size. */\nexport function ScrubberThumb({ className, onFocus, onBlur, ...props }: ComponentProps<typeof SliderPrimitive.Thumb>) {\n  const { label, valueText, setThumbFocused } = useScrubber(\"ScrubberThumb\");\n  return (\n    <SliderPrimitive.Thumb\n      data-slot=\"scrubber-thumb\"\n      aria-valuetext={valueText}\n      onFocus={(event) => {\n        onFocus?.(event);\n        // Only for a keyboard: a pointer shows the preview where it points.\n        setThumbFocused(event.currentTarget.matches(\":focus-visible\"));\n      }}\n      onBlur={(event) => {\n        onBlur?.(event);\n        setThumbFocused(false);\n      }}\n      className={cn(\n        \"relative block size-4 shrink-0 rounded-full border border-primary bg-background transition-transform duration-instant ease-out after:absolute after:-inset-3 active:scale-110 motion-reduce:transition-none motion-reduce:active:scale-100\",\n        className,\n      )}\n      {...label}\n      {...props}\n    />\n  );\n}\n\nexport type ScrubberPreviewProps = Omit<ComponentProps<\"div\">, \"children\"> & {\n  /** The picture for a moment: a function of the time that returns an element, or a sprite sheet. Left out, the preview shows the time alone. */\n  thumbnail?: ((time: number) => ReactNode) | ScrubberSprite;\n  /** Replaces the time and chapter line. */\n  children?: (time: number, mark: ScrubberMark | undefined) => ReactNode;\n};\n\n/**\n * A small surface above the bar at the moment under the pointer (or at the thumb, while it is dragged or\n * has keyboard focus). It stays inside the ends of the bar. Hidden from assistive technology: the slider\n * already says the time and the chapter. Its width is `--rui-preview-w`; set that in `className` to resize it.\n */\nexport function ScrubberPreview({ className, style, thumbnail, children, ...props }: ScrubberPreviewProps) {\n  const { previewTime, duration, marks, locale } = useScrubber(\"ScrubberPreview\");\n  if (previewTime === null) return null;\n  const mark = markAt(marks, previewTime);\n  return (\n    <div\n      data-slot=\"scrubber-preview\"\n      aria-hidden=\"true\"\n      className={cn(\n        \"pointer-events-none absolute bottom-full z-10 mb-1 flex w-(--rui-preview-w) flex-col items-center gap-1 text-xs text-popover-foreground\",\n        thumbnail ? \"[--rui-preview-w:8rem]\" : \"[--rui-preview-w:6rem]\",\n        className,\n      )}\n      style={{ insetInlineStart: `clamp(0px, calc(${along(previewTime, duration)} - var(--rui-preview-w) / 2), calc(100% - var(--rui-preview-w)))`, ...style }}\n      {...props}\n    >\n      {thumbnail ? (\n        <div data-slot=\"scrubber-preview-picture\" className=\"w-full overflow-hidden rounded-control border border-border-strong bg-muted\">\n          {typeof thumbnail === \"function\" ? thumbnail(previewTime) : <SpriteFrame sprite={thumbnail} time={previewTime} />}\n        </div>\n      ) : null}\n      <div data-slot=\"scrubber-preview-label\" className=\"flex max-w-full flex-col items-center rounded-control border border-border-strong bg-popover px-1.5 py-0.5 text-center tabular-nums\">\n        {children ? (\n          children(previewTime, mark)\n        ) : (\n          <>\n            {mark ? <span className=\"max-w-full truncate font-medium\">{mark.label}</span> : null}\n            <span>{formatMediaTime(previewTime, locale)}</span>\n          </>\n        )}\n      </div>\n    </div>\n  );\n}\n\n/** One still out of a sprite sheet, picked by time. */\nfunction SpriteFrame({ sprite, time }: { sprite: ScrubberSprite; time: number }) {\n  const count = sprite.columns * sprite.rows;\n  const index = Math.min(count - 1, Math.max(0, Math.floor(time / sprite.interval)));\n  const column = index % sprite.columns;\n  const row = Math.floor(index / sprite.columns);\n  const position = (at: number, of: number): string => (of > 1 ? `${(at / (of - 1)) * 100}%` : \"0%\");\n  return (\n    <div\n      data-slot=\"scrubber-sprite\"\n      data-frame={index}\n      className=\"w-full bg-no-repeat\"\n      style={{\n        aspectRatio: String(sprite.aspect ?? 16 / 9),\n        backgroundImage: `url(${JSON.stringify(sprite.url)})`,\n        backgroundSize: `${sprite.columns * 100}% ${sprite.rows * 100}%`,\n        backgroundPosition: `${position(column, sprite.columns)} ${position(row, sprite.rows)}`,\n      }}\n    />\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "Seeking in audio, video or any timeline measured in seconds. video-player and audio-player already contain one bound to their media; use this directly for a custom player or a timeline. For choosing a number that is not a time use slider. Time runs left to right in every language (as on players everywhere: the bar is a picture of time, like a clock face, not a line of text), so the bar and its arrow keys are not mirrored in right-to-left pages; pass `dir=\"rtl\"` if a product decides otherwise, and the keys follow what is drawn.",
    "example": "// Uncontrolled\n<Scrubber duration={200} defaultValue={65} aria-label=\"Seek\" onValueCommit={(time) => player.seek(time)} />\n\n// Controlled by the player's clock, with chapters and a preview picture from a sprite sheet\n<Scrubber\n  value={time}\n  duration={duration}\n  buffered={[[0, 90]]}\n  marks={[{ time: 0, label: \"Opening\" }, { time: 60, label: \"The climb\" }]}\n  onValueCommit={seek}\n  aria-label=\"Seek\"\n>\n  <ScrubberTrack />\n  <ScrubberThumb />\n  <ScrubberPreview thumbnail={{ url: \"/sprite.jpg\", columns: 10, rows: 10, interval: 2 }} />\n</Scrubber>",
    "client": true
  }
}
