{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "captions",
  "type": "registry:ui",
  "title": "Captions",
  "description": "Captions drawn by the page instead of the browser, on a solid ground that reads on any picture, and a transcript: every line of a clip as a list that can be pressed to go there.",
  "categories": [
    "ui"
  ],
  "dependencies": [],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/cn",
    "@rivier-ui/use-media"
  ],
  "files": [
    {
      "path": "registry/ui/captions.tsx",
      "type": "registry:ui",
      "target": "components/ui/captions.tsx",
      "content": "\"use client\";\n/**\n * @name captions\n * @category ui\n * @description Captions drawn by the page instead of the browser, on a solid ground that reads on any picture, and a transcript: every line of a clip as a list that can be pressed to go there.\n * @when Inside video-player (Captions sits above the controls and moves with them) or beside audio-player (Transcript, or Captions with `inline`). Captions are for people who cannot hear the sound; a Transcript is also the alternative for people who cannot see or play it, so offer one for anything spoken. The lines come from a caption track of the media element (`<track kind=\"captions\">`), or from `cues` the project passes. Not a live region: with the sound on, a screen reader would talk over it.\n * @example\n * // In a video player: the lines of the element's caption track\n * <VideoPlayer aria-label=\"Loading the kiln\" defaultCaptions>\n *   <VideoPlayerVideo src=\"/kiln.mp4\"><track kind=\"captions\" src=\"/kiln.en.vtt\" srcLang=\"en\" label=\"English\" /></VideoPlayerVideo>\n *   <Captions />\n *   <VideoPlayerControls>…</VideoPlayerControls>\n * </VideoPlayer>\n *\n * // Beside an audio player: cues from the project, as a transcript\n * const cues = [{ start: 0, end: 4, text: \"Welcome.\" }, { start: 4, end: 9, text: \"This is the yard.\" }];\n * <AudioPlayer aria-label=\"A walk through the yard\">\n *   <AudioPlayerAudio src=\"/yard.mp3\" />\n *   <AudioPlayerPlay /> <AudioPlayerWaveform peaks={peaks} />\n *   <Transcript cues={cues} aria-label=\"Transcript\" lang=\"en\" />\n * </AudioPlayer>\n */\nimport { useCallback, useEffect, useRef, useSyncExternalStore, type ComponentProps } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport { formatMediaTime, useOptionalMediaContext } from \"@/lib/use-media\";\n\n/** One line: when it starts and ends, in seconds, and what is said. */\nexport type Cue = { start: number; end: number; text: string };\n\n/** The text of a WebVTT cue without its markup (<v Name>, <i>, timestamps). */\nconst plain = (text: string): string => text.replace(/<[^>]*>/g, \"\").trim();\n\n/** Shows the chosen caption track without the browser drawing it (\"hidden\" loads its cues and fires cue changes), and switches the others off. */\nfunction chooseTrack(media: HTMLMediaElement, chosen: number | null): void {\n  for (let index = 0; index < media.textTracks.length; index += 1) {\n    const track = media.textTracks[index];\n    if (!track || (track.kind !== \"captions\" && track.kind !== \"subtitles\")) continue;\n    track.mode = index === chosen ? \"hidden\" : \"disabled\";\n  }\n}\n\nfunction cuesOf(track: TextTrack | null | undefined): Cue[] {\n  const list: Cue[] = [];\n  const cues = track?.cues;\n  if (!cues) return list;\n  for (let index = 0; index < cues.length; index += 1) {\n    const cue = cues[index];\n    if (cue) list.push({ start: cue.startTime, end: cue.endTime, text: plain((cue as VTTCue).text ?? \"\") });\n  }\n  return list;\n}\n\n/**\n * The cues of one of an element's caption tracks, kept current as the track loads. The snapshot is the\n * cues as text, so it is compared by value.\n */\nfunction useTrackCues(media: HTMLMediaElement | null, index: number | null, enabled: boolean): Cue[] {\n  const subscribe = useCallback(\n    (onChange: () => void): (() => void) => {\n      if (!media || !enabled) return () => {};\n      chooseTrack(media, index);\n      const track = index === null ? undefined : media.textTracks[index];\n      const elements = [...media.querySelectorAll(\"track\")];\n      track?.addEventListener(\"cuechange\", onChange);\n      media.addEventListener(\"loadedmetadata\", onChange);\n      media.textTracks.addEventListener(\"addtrack\", onChange);\n      for (const element of elements) element.addEventListener(\"load\", onChange);\n      return () => {\n        track?.removeEventListener(\"cuechange\", onChange);\n        media.removeEventListener(\"loadedmetadata\", onChange);\n        media.textTracks.removeEventListener(\"addtrack\", onChange);\n        for (const element of elements) element.removeEventListener(\"load\", onChange);\n      };\n    },\n    [media, index, enabled],\n  );\n  const snapshot = useSyncExternalStore(\n    subscribe,\n    () => (media && enabled && index !== null ? JSON.stringify(cuesOf(media.textTracks[index])) : \"[]\"),\n    () => \"[]\",\n  );\n  return JSON.parse(snapshot) as Cue[];\n}\n\ntype CueSource = {\n  /** The lines, when the project has them. Left out, they are read from the media element's caption track. */\n  cues?: readonly Cue[];\n  /** The current time in seconds. Left out, it is the player's. */\n  time?: number;\n  /** The media element. Left out, it is the player's. */\n  media?: HTMLMediaElement | null;\n};\n\nfunction useCues({ cues, time, media }: CueSource): { cues: readonly Cue[]; time: number; language: string | undefined } {\n  const context = useOptionalMediaContext();\n  const element = media ?? context?.media ?? null;\n  const index = context ? context.captionTrack : firstCaptionTrack(element);\n  const fromTrack = useTrackCues(element, index, cues === undefined);\n  const language = cues === undefined && element && index !== null ? element.textTracks[index]?.language || undefined : undefined;\n  return { cues: cues ?? fromTrack, time: time ?? context?.state.time ?? 0, language };\n}\n\nfunction firstCaptionTrack(media: HTMLMediaElement | null): number | null {\n  if (!media) return null;\n  for (let index = 0; index < media.textTracks.length; index += 1) {\n    const kind = media.textTracks[index]?.kind;\n    if (kind === \"captions\" || kind === \"subtitles\") return index;\n  }\n  return null;\n}\n\nexport type CaptionsProps = Omit<ComponentProps<\"div\">, \"children\"> &\n  CueSource & {\n    /** Whether they show. Left out, it is the player's captions switch (on when there is no player). */\n    show?: boolean;\n    /** A normal block in the flow (beside an audio player) instead of a layer over the bottom of a video frame. */\n    inline?: boolean;\n  };\n\n/**\n * The lines being said now. Over a video it sits along the bottom and moves up when the controls show, so\n * the two never overlap. The text is on a solid ground from the theme (it reads on any picture, in both\n * modes), its size follows the width of the frame, and it carries `lang` and `dir=\"auto\"` so a caption in\n * another script is shaped and read the right way. Give `lang` when the cues are passed in; a track's own\n * language is used otherwise.\n */\nexport function Captions({ className, cues, time, media, show, inline = false, lang, ...props }: CaptionsProps) {\n  const context = useOptionalMediaContext();\n  const source = useCues({ cues, time, media });\n  const on = show ?? context?.captions ?? true;\n  const lines = on ? source.cues.filter((cue) => cue.start <= source.time && source.time < cue.end).flatMap((cue) => cue.text.split(\"\\n\")) : [];\n  return (\n    <div\n      data-slot=\"captions\"\n      data-state={on ? \"on\" : \"off\"}\n      className={cn(\n        inline\n          ? \"flex min-h-[2lh] items-end justify-center text-base\"\n          : \"pointer-events-none absolute inset-x-0 bottom-0 z-10 flex justify-center px-[4cqi] pb-[3cqi] text-[clamp(0.875rem,3.4cqi,1.75rem)] transition-transform duration-base ease-out group-data-[controls=shown]/player:translate-y-[calc(var(--rui-controls-h,0px)*-1)] motion-reduce:transition-none\",\n        className,\n      )}\n      {...props}\n    >\n      {lines.length > 0 ? (\n        <p data-slot=\"captions-text\" lang={lang ?? source.language} dir=\"auto\" className=\"max-w-full text-center leading-normal font-medium\">\n          {lines.map((line, index) => (\n            <span key={index} className=\"block\">\n              <span className=\"bg-background box-decoration-clone px-[0.4em] py-[0.1em] text-foreground\">{line}</span>\n            </span>\n          ))}\n        </p>\n      ) : null}\n    </div>\n  );\n}\n\nexport type TranscriptProps = Omit<ComponentProps<\"div\">, \"children\"> &\n  CueSource & {\n    /** Called with a line's start time when it is pressed. Left out, the player seeks there. */\n    onSeek?: (time: number) => void;\n    /** Show each line's time before it. Default true. */\n    times?: boolean;\n    /** The language tag times are formatted for. Left out, it is the player's. */\n    locale?: string;\n  };\n\n/**\n * Every line, in order, each a button that goes to its moment; the line being said is marked with\n * `aria-current` and a bar at its start. The list scrolls inside its own box (give it a height with\n * `className`, default about six lines) and follows the playing line, unless the person has scrolled away:\n * then it leaves the list where they put it until the playing line is back in view. Name it with\n * `aria-label` (\"Transcript\").\n */\nexport function Transcript({ className, cues, time, media, onSeek, times = true, locale, lang, ...props }: TranscriptProps) {\n  const context = useOptionalMediaContext();\n  const source = useCues({ cues, time, media });\n  const current = source.cues.findIndex((cue) => cue.start <= source.time && source.time < cue.end);\n  const list = useRef<HTMLOListElement>(null);\n  /** The person scrolled the list away from the playing line. */\n  const away = useRef(false);\n\n  const visible = (item: HTMLElement, box: HTMLElement): boolean => item.offsetTop >= box.scrollTop && item.offsetTop + item.offsetHeight <= box.scrollTop + box.clientHeight;\n\n  useEffect(() => {\n    const box = list.current;\n    const item = box?.querySelector<HTMLElement>('[data-current=\"true\"]');\n    if (!box || !item || away.current || visible(item, box)) return;\n    const reduced = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n    box.scrollTo({ top: item.offsetTop - (box.clientHeight - item.offsetHeight) / 2, behavior: reduced ? \"instant\" : \"smooth\" });\n  }, [current]);\n\n  const leave = (): void => {\n    away.current = true;\n  };\n\n  return (\n    <div data-slot=\"transcript\" role=\"group\" className={cn(\"min-w-0 rounded-surface border bg-card text-card-foreground\", className)} {...props}>\n      <ol\n        ref={list}\n        data-slot=\"transcript-list\"\n        lang={lang ?? source.language}\n        className=\"relative flex max-h-48 flex-col overflow-y-auto overscroll-contain p-1\"\n        onWheel={leave}\n        onTouchMove={leave}\n        onKeyDown={(event) => {\n          if ([\"PageUp\", \"PageDown\"].includes(event.key)) leave();\n        }}\n        onScroll={(event) => {\n          const item = event.currentTarget.querySelector<HTMLElement>('[data-current=\"true\"]');\n          if (item && visible(item, event.currentTarget)) away.current = false;\n        }}\n      >\n        {source.cues.map((cue, index) => (\n          <li key={`${cue.start}-${index}`} data-current={index === current ? \"true\" : undefined}>\n            <button\n              type=\"button\"\n              data-slot=\"transcript-cue\"\n              aria-current={index === current ? \"true\" : undefined}\n              onClick={() => (onSeek ?? context?.actions.seek)?.(cue.start)}\n              className=\"flex min-h-8 w-full items-baseline gap-3 rounded-control border-s-2 border-transparent px-2 py-1.5 text-start text-sm text-muted-foreground transition-colors duration-instant ease-out hover:bg-accent hover:text-foreground aria-[current=true]:border-primary aria-[current=true]:bg-highlight-soft aria-[current=true]:font-medium aria-[current=true]:text-foreground motion-reduce:transition-none pointer-coarse:min-h-(--control-h)\"\n            >\n              {times ? (\n                <span data-slot=\"transcript-time\" className=\"shrink-0 text-xs tabular-nums\">\n                  {formatMediaTime(cue.start, locale ?? context?.locale)}\n                </span>\n              ) : null}\n              <span dir=\"auto\" className=\"min-w-0 whitespace-pre-line\">\n                {cue.text}\n              </span>\n            </button>\n          </li>\n        ))}\n      </ol>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "Inside video-player (Captions sits above the controls and moves with them) or beside audio-player (Transcript, or Captions with `inline`). Captions are for people who cannot hear the sound; a Transcript is also the alternative for people who cannot see or play it, so offer one for anything spoken. The lines come from a caption track of the media element (`<track kind=\"captions\">`), or from `cues` the project passes. Not a live region: with the sound on, a screen reader would talk over it.",
    "example": "// In a video player: the lines of the element's caption track\n<VideoPlayer aria-label=\"Loading the kiln\" defaultCaptions>\n  <VideoPlayerVideo src=\"/kiln.mp4\"><track kind=\"captions\" src=\"/kiln.en.vtt\" srcLang=\"en\" label=\"English\" /></VideoPlayerVideo>\n  <Captions />\n  <VideoPlayerControls>…</VideoPlayerControls>\n</VideoPlayer>\n\n// Beside an audio player: cues from the project, as a transcript\nconst cues = [{ start: 0, end: 4, text: \"Welcome.\" }, { start: 4, end: 9, text: \"This is the yard.\" }];\n<AudioPlayer aria-label=\"A walk through the yard\">\n  <AudioPlayerAudio src=\"/yard.mp3\" />\n  <AudioPlayerPlay /> <AudioPlayerWaveform peaks={peaks} />\n  <Transcript cues={cues} aria-label=\"Transcript\" lang=\"en\" />\n</AudioPlayer>",
    "client": true
  }
}
