{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "use-media",
  "type": "registry:lib",
  "title": "Use Media",
  "description": "Follows an audio or video element (playing, time, duration, buffered, volume, rate, text tracks, waiting, error) as React state, with the actions to drive it, the context player parts share, and time formatting through Intl.",
  "categories": [
    "lib"
  ],
  "dependencies": [],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/use-controllable-state"
  ],
  "files": [
    {
      "path": "registry/lib/use-media.ts",
      "type": "registry:lib",
      "target": "lib/use-media.ts",
      "content": "\"use client\";\n/**\n * @name use-media\n * @category lib\n * @description Follows an audio or video element (playing, time, duration, buffered, volume, rate, text tracks, waiting, error) as React state, with the actions to drive it, the context player parts share, and time formatting through Intl.\n * @when Building player parts around a `<video>` or `<audio>` element the project renders. video-player, audio-player, captions and scene-strip are built on it; use it directly for a control they do not have. The element stays the source of truth: sources, HLS and DRM are attached to it by the project, and nothing here loads or decodes media.\n * @example\n * function Elapsed() {\n *   const { state, locale } = useMediaContext(\"Elapsed\");\n *   return <span>{formatMediaTime(state.time, locale)}</span>;\n * }\n *\n * // Without a player around it\n * const [audio, setAudio] = useState<HTMLAudioElement | null>(null);\n * const state = useMediaState(audio);\n * <audio ref={setAudio} src=\"/note.mp3\" />\n * <Button onClick={() => mediaActions(audio).toggle()}>{state.playing ? \"Pause\" : \"Play\"}</Button>\n */\nimport { createContext, use, useMemo, useState, useSyncExternalStore } from \"react\";\nimport { useControllableState } from \"@/lib/use-controllable-state\";\n\nexport type MediaTrack = { index: number; label: string; language: string; kind: string };\n\nexport type MediaState = {\n  /** False until the element is known (on the server, before it mounts). */\n  bound: boolean;\n  playing: boolean;\n  /** Seconds. */\n  time: number;\n  /** Seconds; 0 while it is not known (before metadata, or for a live stream). */\n  duration: number;\n  /** Loaded ranges as [start, end] in seconds. */\n  buffered: [number, number][];\n  muted: boolean;\n  /** 0 to 1. */\n  volume: number;\n  rate: number;\n  ended: boolean;\n  /** Playback wants to continue but is waiting for data. */\n  waiting: boolean;\n  /** The element's error message or code, or null. */\n  error: string | null;\n  /** Caption and subtitle tracks of the element, in its order. */\n  tracks: MediaTrack[];\n};\n\nconst IDLE: MediaState = { bound: false, playing: false, time: 0, duration: 0, buffered: [], muted: false, volume: 1, rate: 1, ended: false, waiting: false, error: null, tracks: [] };\n\nconst EVENTS = [\"play\", \"playing\", \"pause\", \"ended\", \"timeupdate\", \"durationchange\", \"loadedmetadata\", \"progress\", \"seeking\", \"seeked\", \"waiting\", \"canplay\", \"volumechange\", \"ratechange\", \"error\", \"emptied\", \"loadstart\"] as const;\n\nfunction read(media: HTMLMediaElement, previous: MediaState): MediaState {\n  const buffered: [number, number][] = [];\n  for (let index = 0; index < media.buffered.length; index += 1) buffered.push([media.buffered.start(index), media.buffered.end(index)]);\n  const tracks: MediaTrack[] = [];\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\")) tracks.push({ index, label: track.label, language: track.language, kind: track.kind });\n  }\n  const same = <T,>(next: T[], before: T[]): T[] => (JSON.stringify(next) === JSON.stringify(before) ? before : next);\n  return {\n    bound: true,\n    playing: !media.paused && !media.ended,\n    time: media.currentTime,\n    duration: Number.isFinite(media.duration) ? media.duration : 0,\n    buffered: same(buffered, previous.buffered),\n    muted: media.muted,\n    volume: media.volume,\n    rate: media.playbackRate,\n    ended: media.ended,\n    // readyState 2 (HAVE_CURRENT_DATA) or less while it should be playing or is seeking: it is waiting.\n    waiting: media.error === null && media.networkState !== 3 && media.readyState < 3 && (!media.paused || media.seeking),\n    error: media.error ? media.error.message || `code ${media.error.code}` : null,\n    tracks: same(tracks, previous.tracks),\n  };\n}\n\nfunction shallowEqual(a: MediaState, b: MediaState): boolean {\n  return (Object.keys(a) as (keyof MediaState)[]).every((key) => Object.is(a[key], b[key]));\n}\n\ntype Store = { subscribe: (onChange: () => void) => () => void; get: () => MediaState };\n\nfunction createStore(media: HTMLMediaElement | null): Store {\n  if (!media) return { subscribe: () => () => {}, get: () => IDLE };\n  let snapshot = read(media, IDLE);\n  const refresh = (): boolean => {\n    const next = read(media, snapshot);\n    if (shallowEqual(next, snapshot)) return false;\n    snapshot = next;\n    return true;\n  };\n  return {\n    subscribe(onChange) {\n      const update = (): void => {\n        if (refresh()) onChange();\n      };\n      for (const event of EVENTS) media.addEventListener(event, update);\n      media.textTracks.addEventListener(\"addtrack\", update);\n      media.textTracks.addEventListener(\"removetrack\", update);\n      // timeupdate fires about four times a second; reading ten times a second while playing keeps a time bar even.\n      let frame = 0;\n      let last = 0;\n      const tick = (now: number): void => {\n        if (!media.paused && now - last >= 100) {\n          last = now;\n          update();\n        }\n        frame = requestAnimationFrame(tick);\n      };\n      frame = requestAnimationFrame(tick);\n      refresh();\n      return () => {\n        for (const event of EVENTS) media.removeEventListener(event, update);\n        media.textTracks.removeEventListener(\"addtrack\", update);\n        media.textTracks.removeEventListener(\"removetrack\", update);\n        cancelAnimationFrame(frame);\n      };\n    },\n    get: () => snapshot,\n  };\n}\n\nconst idle = (): MediaState => IDLE;\n\n/** The element's state, kept current from its events. Give it the element from a `ref` held in state (not a ref object). */\nexport function useMediaState(media: HTMLMediaElement | null): MediaState {\n  const store = useMemo(() => createStore(media), [media]);\n  return useSyncExternalStore(store.subscribe, store.get, idle);\n}\n\nexport type MediaActions = {\n  play: () => void;\n  pause: () => void;\n  toggle: () => void;\n  /** Goes to a time in seconds, kept inside the media. */\n  seek: (time: number) => void;\n  seekBy: (seconds: number) => void;\n  setVolume: (volume: number) => void;\n  setMuted: (muted: boolean) => void;\n  toggleMuted: () => void;\n  setRate: (rate: number) => void;\n  /** Loads the sources again: what a retry button calls after an error. */\n  reload: () => void;\n};\n\n/** Actions on a media element. Every one is safe to call with null (it does nothing). */\nexport function mediaActions(media: HTMLMediaElement | null): MediaActions {\n  const limit = (time: number): number => {\n    const end = media && Number.isFinite(media.duration) ? media.duration : Number.MAX_SAFE_INTEGER;\n    return Math.min(end, Math.max(0, time));\n  };\n  const play = (): void => {\n    // A browser may refuse to play (no gesture yet, no source): the element stays paused and its state says so.\n    media?.play().catch(() => {});\n  };\n  return {\n    play,\n    pause: () => media?.pause(),\n    toggle: () => {\n      if (!media) return;\n      if (media.paused || media.ended) play();\n      else media.pause();\n    },\n    seek: (time) => {\n      if (media) media.currentTime = limit(time);\n    },\n    seekBy: (seconds) => {\n      if (media) media.currentTime = limit(media.currentTime + seconds);\n    },\n    setVolume: (volume) => {\n      if (!media) return;\n      media.volume = Math.min(1, Math.max(0, volume));\n      if (media.volume > 0) media.muted = false;\n    },\n    setMuted: (muted) => {\n      if (media) media.muted = muted;\n    },\n    toggleMuted: () => {\n      if (media) media.muted = !media.muted;\n    },\n    setRate: (rate) => {\n      if (media) media.playbackRate = rate;\n    },\n    reload: () => media?.load(),\n  };\n}\n\nexport type MediaContextValue = {\n  media: HTMLMediaElement | null;\n  /** The `ref` of the media element: the element part of a player passes it on. */\n  setMedia: (media: HTMLMediaElement | null) => void;\n  state: MediaState;\n  actions: MediaActions;\n  /** The language tag times and numbers are formatted for. Undefined: the runtime's own. */\n  locale: string | undefined;\n  /** Whether captions are shown, and which of the element's caption tracks (an index into its textTracks). */\n  captions: boolean;\n  setCaptions: (on: boolean) => void;\n  captionTrack: number | null;\n  setCaptionTrack: (index: number) => void;\n};\n\nexport const MediaContext = createContext<MediaContextValue | null>(null);\n\n/** The player a part is inside. `part` names the caller in the error. */\nexport function useMediaContext(part: string): MediaContextValue {\n  const context = use(MediaContext);\n  if (!context) throw new Error(`<${part}> must be used inside a player (<VideoPlayer> or <AudioPlayer>).`);\n  return context;\n}\n\n/** The same, or null outside a player: for parts that can also be given their media by props. */\nexport function useOptionalMediaContext(): MediaContextValue | null {\n  return use(MediaContext);\n}\n\nexport type MediaProviderOptions = {\n  locale?: string | undefined;\n  /** Captions shown: controlled. */\n  captions?: boolean | undefined;\n  defaultCaptions?: boolean | undefined;\n  onCaptionsChange?: ((on: boolean) => void) | undefined;\n};\n\n/** What a player root calls to make the value of MediaContext. */\nexport function useMediaProvider({ locale, captions, defaultCaptions = false, onCaptionsChange }: MediaProviderOptions): MediaContextValue {\n  const [media, setMedia] = useState<HTMLMediaElement | null>(null);\n  const state = useMediaState(media);\n  const actions = useMemo(() => mediaActions(media), [media]);\n  const [captionsOn, setCaptions] = useControllableState({ value: captions, defaultValue: defaultCaptions, onChange: onCaptionsChange });\n  const [chosenTrack, setCaptionTrack] = useState<number | null>(null);\n  const captionTrack = chosenTrack !== null && state.tracks.some((track) => track.index === chosenTrack) ? chosenTrack : (state.tracks[0]?.index ?? null);\n  return { media, setMedia, state, actions, locale, captions: captionsOn, setCaptions, captionTrack, setCaptionTrack };\n}\n\n/** A time as a clock: \"1:05\", \"1:02:09\". Digits follow the locale. */\nexport function formatMediaTime(seconds: number, locale?: string): string {\n  const total = Math.max(0, Math.floor(Number.isFinite(seconds) ? seconds : 0));\n  const two = new Intl.NumberFormat(locale, { minimumIntegerDigits: 2, useGrouping: false });\n  const one = new Intl.NumberFormat(locale, { useGrouping: false });\n  const hours = Math.floor(total / 3600);\n  const minutes = Math.floor((total % 3600) / 60);\n  const rest = two.format(total % 60);\n  return hours > 0 ? `${one.format(hours)}:${two.format(minutes)}:${rest}` : `${one.format(minutes)}:${rest}`;\n}\n\n/** A time in words, for a screen reader: \"1 minute 5 seconds\". Units and digits follow the locale. */\nexport function describeMediaTime(seconds: number, locale?: string): string {\n  const total = Math.max(0, Math.floor(Number.isFinite(seconds) ? seconds : 0));\n  const unit = (value: number, name: \"hour\" | \"minute\" | \"second\"): string => new Intl.NumberFormat(locale, { style: \"unit\", unit: name, unitDisplay: \"long\" }).format(value);\n  const hours = Math.floor(total / 3600);\n  const minutes = Math.floor((total % 3600) / 60);\n  const parts = [hours > 0 ? unit(hours, \"hour\") : null, hours > 0 || minutes > 0 ? unit(minutes, \"minute\") : null, unit(total % 60, \"second\")].filter((part): part is string => part !== null);\n  return new Intl.ListFormat(locale, { style: \"narrow\", type: \"unit\" }).format(parts);\n}\n\n/** A playback rate as text: \"1.5×\". */\nexport function formatMediaRate(rate: number, locale?: string): string {\n  return `${new Intl.NumberFormat(locale, { maximumFractionDigits: 2 }).format(rate)}×`;\n}\n\n/** The rate after `rate` in `rates`, going round. */\nexport function nextMediaRate(rates: readonly number[], rate: number): number {\n  const index = rates.findIndex((candidate) => Math.abs(candidate - rate) < 0.001);\n  return rates[(index + 1) % rates.length] ?? 1;\n}\n\n/** Whether a key press should be left alone by a player's shortcuts: it was typed into a field or belongs to a control that uses it. */\nexport function isTypingTarget(target: EventTarget | null): boolean {\n  if (!(target instanceof HTMLElement)) return false;\n  return target.isContentEditable || target.closest(\"input, textarea, select, [role=textbox], [role=combobox], [role=menu], [role=listbox]\") !== null;\n}\n"
    }
  ],
  "meta": {
    "category": "lib",
    "when": "Building player parts around a `<video>` or `<audio>` element the project renders. video-player, audio-player, captions and scene-strip are built on it; use it directly for a control they do not have. The element stays the source of truth: sources, HLS and DRM are attached to it by the project, and nothing here loads or decodes media.",
    "example": "function Elapsed() {\n  const { state, locale } = useMediaContext(\"Elapsed\");\n  return <span>{formatMediaTime(state.time, locale)}</span>;\n}\n\n// Without a player around it\nconst [audio, setAudio] = useState<HTMLAudioElement | null>(null);\nconst state = useMediaState(audio);\n<audio ref={setAudio} src=\"/note.mp3\" />\n<Button onClick={() => mediaActions(audio).toggle()}>{state.playing ? \"Pause\" : \"Play\"}</Button>",
    "client": true
  }
}
