---
title: "Video player"
url: "https://sarthakmishra.com/riff-ui/components/video-player"
description: "Video with custom controls, a seek preview, captions, speeds and shortcuts. Accessible React 19 source on UI SDK, installed with the shadcn CLI."
image: "https://sarthakmishra.com/og-images/riff-ui/video-player.webp"
---

[View HTML](https://sarthakmishra.com/riff-ui/components/video-player) · [Site index](https://sarthakmishra.com/llms.txt)

# Video player

Video with custom controls, a seek preview, captions, speeds and shortcuts.

## Installation

### CLI

```bash
pnpm dlx shadcn@latest add @riff/video-player
```

### Manual

1. Install UI SDK

   ```bash
   pnpm add @ui-sdk/react @ui-sdk/core
   ```

2. Copy the component

   Save this as `components/ui/video-player.tsx`:

   ```tsx
   'use client';
   import {
     useEffect,
     useLayoutEffect,
     useRef,
     useState,
     type CSSProperties,
     type KeyboardEvent,
     type PointerEvent,
     type ReactNode,
     type RefObject,
   } from 'react';
   import {
     Menu,
     MenuCheckboxItem,
     MenuContent,
     MenuGroupLabel,
     MenuItemIndicator,
     MenuRadioGroup,
     MenuRadioItem,
     MenuSeparator,
     MenuTrigger,
   } from '@ui-sdk/react/menu';
   import './video-player.css';

   type CustomProperties = CSSProperties & Record<`--${string}`, string | number>;
   /** Custom properties for `style`, typed without a global declaration. */
   const cssVars = (values: CustomProperties): CSSProperties => values;

   /** A sprite sheet of evenly spaced frames, shown above the seek bar. */
   export type VideoPreview = {
     src: string;
     /** One frame's size in CSS pixels. */
     width: number;
     height: number;
     columns: number;
     frames: number;
     /** Seconds between frames. */
     interval: number;
   };

   const RATES = [0.5, 0.75, 1, 1.25, 1.5, 2] as const;
   const IDLE_MS = 2000;
   const SEEK_STEP = 5;

   function formatTime(seconds: number) {
     const total = Number.isFinite(seconds) ? Math.max(0, Math.floor(seconds)) : 0;
     const hours = Math.floor(total / 3600);
     const minutes = Math.floor((total % 3600) / 60);
     const rest = String(total % 60).padStart(2, '0');
     return hours
       ? `${hours}:${String(minutes).padStart(2, '0')}:${rest}`
       : `${minutes}:${rest}`;
   }

   type Snapshot = {
     time: number;
     duration: number;
     buffered: number;
     paused: boolean;
     muted: boolean;
     volume: number;
     rate: number;
     waiting: boolean;
     failed: boolean;
   };

   const EVENTS = [
     'timeupdate',
     'durationchange',
     'progress',
     'play',
     'pause',
     'ended',
     'volumechange',
     'ratechange',
     'loadedmetadata',
     'waiting',
     'playing',
     'canplay',
     'seeked',
     'error',
   ] as const;

   function read(video: HTMLVideoElement): Snapshot {
     const time = video.currentTime;
     let buffered = 0;
     for (let index = 0; index < video.buffered.length; index++)
       if (video.buffered.start(index) <= time + 0.05)
         buffered = Math.max(buffered, video.buffered.end(index));
     return {
       time,
       duration: Number.isFinite(video.duration) ? video.duration : 0,
       buffered,
       paused: video.paused,
       muted: video.muted,
       volume: video.volume,
       rate: video.playbackRate,
       waiting: !video.paused && video.readyState < 3,
       failed: video.error !== null,
     };
   }

   function useVideo(video: RefObject<HTMLVideoElement | null>) {
     const [state, setState] = useState<Snapshot>({
       time: 0,
       duration: 0,
       buffered: 0,
       paused: true,
       muted: false,
       volume: 1,
       rate: 1,
       waiting: false,
       failed: false,
     });
     useLayoutEffect(() => {
       const element = video.current;
       if (!element) return;
       const update = () => setState(read(element));
       for (const event of EVENTS) element.addEventListener(event, update);
       update();
       return () => {
         for (const event of EVENTS) element.removeEventListener(event, update);
       };
     }, [video]);
     return state;
   }

   function Icon({ children }: { children: ReactNode }) {
     return (
       <svg
         aria-hidden="true"
         className="riff-video-icon"
         viewBox="0 0 24 24"
         fill="none"
         stroke="currentColor"
         strokeWidth="2"
         strokeLinecap="round"
         strokeLinejoin="round"
       >
         {children}
       </svg>
     );
   }

   const PLAY = <path d="M6 4.5v15l13-7.5z" fill="currentColor" stroke="none" />;
   const PAUSE = (
     <path d="M7 4h3v16H7zM14 4h3v16h-3z" fill="currentColor" stroke="none" />
   );

   /**
    * A video with its own controls: a large play button, a seek bar with a
    * hover preview, volume, a settings menu for speed and captions, and
    * fullscreen. Controls fade while it plays and the pointer rests. Server
    * HTML and no-JS readers get the browser's native controls.
    *
    * Keys while focused: Space or K plays and pauses, ← and → seek 5 seconds,
    * M mutes, C toggles captions and F toggles fullscreen.
    */
   export function VideoPlayer({
     src,
     title,
     poster,
     captions,
     preview,
     aspectRatio = '16 / 9',
     autoPlay = false,
     muted = false,
     loop = false,
     type,
     attach,
   }: {
     /** An MP4 or WebM file, or a stream that `attach` loads. */
     src: string;
     /** The source's MIME type, so browsers that can't play it skip it. */
     type?: string;
     /** Names the player for screen readers. */
     title: string;
     poster?: string;
     /** A WebVTT file of English captions. */
     captions?: string;
     preview?: VideoPreview;
     aspectRatio?: string;
     autoPlay?: boolean;
     muted?: boolean;
     loop?: boolean;
     /**
      * Loads `src` into the video yourself, such as an HLS stream with hls.js.
      * It gets the element with its `<source>` removed. Return a function that
      * detaches it.
      */
     attach?: (video: HTMLVideoElement, src: string) => (() => void) | undefined;
   }) {
     const frame = useRef<HTMLDivElement>(null);
     const video = useRef<HTMLVideoElement>(null);
     const track = useRef<HTMLTrackElement>(null);
     const idle = useRef<ReturnType<typeof setTimeout>>(undefined);
     const state = useVideo(video);
     const [enhanced, setEnhanced] = useState(false);
     const [started, setStarted] = useState(false);
     const [awake, setAwake] = useState(true);
     const [menuOpen, setMenuOpen] = useState(false);
     const [captionsOn, setCaptionsOn] = useState(false);
     const [fullscreen, setFullscreen] = useState(false);

     // Hand over from native controls once scripts run.
     useLayoutEffect(() => {
       const element = video.current;
       if (!element) return;
       element.controls = false;
       setEnhanced(true);
       if (!element.paused || element.currentTime > 0) setStarted(true);
       const onPlay = () => setStarted(true);
       element.addEventListener('play', onPlay);
       return () => {
         element.removeEventListener('play', onPlay);
         element.controls = true;
       };
     }, []);

     const attachRef = useRef(attach);
     useEffect(() => {
       const element = video.current;
       const load = attachRef.current;
       if (!element || !load) return;
       // Engines need an empty element; the <source> serves no-JS readers.
       for (const source of element.querySelectorAll('source')) source.remove();
       element.removeAttribute('src');
       element.load();
       return load(element, src);
     }, [src]);

     useEffect(() => {
       const text = track.current?.track;
       if (text) text.mode = captionsOn ? 'showing' : 'hidden';
     }, [captionsOn]);

     useEffect(() => {
       const update = () =>
         setFullscreen(document.fullscreenElement === frame.current);
       document.addEventListener('fullscreenchange', update);
       return () => {
         document.removeEventListener('fullscreenchange', update);
         clearTimeout(idle.current);
       };
     }, []);

     const wake = () => {
       setAwake(true);
       clearTimeout(idle.current);
       idle.current = setTimeout(() => setAwake(false), IDLE_MS);
     };
     const togglePlay = () => {
       const element = video.current;
       if (!element) return;
       wake();
       if (element.paused) void element.play().catch(() => {});
       else element.pause();
     };
     const seek = (time: number) => {
       const element = video.current;
       if (!element || !Number.isFinite(element.duration)) return;
       element.currentTime = Math.min(element.duration, Math.max(0, time));
       wake();
     };
     const toggleMute = () => {
       const element = video.current;
       if (!element) return;
       if (element.volume === 0) element.volume = 1;
       element.muted = !(element.muted || element.volume === 0);
     };
     const setVolume = (volume: number) => {
       const element = video.current;
       if (!element) return;
       element.volume = volume;
       element.muted = volume === 0;
     };
     const toggleFullscreen = async () => {
       const element = frame.current;
       const media:
         | (HTMLVideoElement & { webkitEnterFullscreen?: () => void })
         | null = video.current;
       try {
         if (document.fullscreenElement) await document.exitFullscreen();
         else if (element && document.fullscreenEnabled)
           await element.requestFullscreen();
         // iPhone only fullscreens the video element itself.
         else media?.webkitEnterFullscreen?.();
       } catch {
         // The browser refused; the player stays inline.
       }
     };
     const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
       const { target } = event;
       if (
         event.altKey ||
         event.ctrlKey ||
         event.metaKey ||
         menuOpen ||
         (target instanceof HTMLInputElement && target.type !== 'range')
       )
         return;
       const time = video.current?.currentTime ?? 0;
       const actions: Record<string, () => void> = {
         ' ': togglePlay,
         k: togglePlay,
         m: toggleMute,
         c: () => setCaptionsOn((on) => !on),
         f: () => void toggleFullscreen(),
         arrowleft: () => seek(time - SEEK_STEP),
         arrowright: () => seek(time + SEEK_STEP),
       };
       // A focused button presses itself with Space; the range seeks with arrows.
       if (event.key === ' ' && target instanceof HTMLButtonElement) return;
       if (target instanceof HTMLInputElement && event.key.startsWith('Arrow'))
         return;
       const action = actions[event.key.toLowerCase()];
       if (!action) return;
       event.preventDefault();
       action();
       wake();
     };

     const silent = state.muted || state.volume === 0;
     const visible = !enhanced || awake || state.paused || menuOpen;
     let volumeIcon: ReactNode = (
       <>
         <path d="M11 5 6 9H3v6h3l5 4z" />
         <path d="M15.5 8.5a5 5 0 0 1 0 7M18.5 5.5a9 9 0 0 1 0 13" />
       </>
     );
     if (silent)
       volumeIcon = (
         <>
           <path d="M11 5 6 9H3v6h3l5 4z" />
           <path d="m22 9-6 6M16 9l6 6" />
         </>
       );
     else if (state.volume <= 0.5)
       volumeIcon = (
         <>
           <path d="M11 5 6 9H3v6h3l5 4z" />
           <path d="M15.5 8.5a5 5 0 0 1 0 7" />
         </>
       );

     return (
       <div className="riff-video" role="group" aria-label={title}>
         <div
           ref={frame}
           className="riff-video-frame"
           style={{ aspectRatio }}
           data-enhanced={enhanced ? '' : undefined}
           data-controls={visible ? 'visible' : 'hidden'}
           onPointerMove={wake}
           onPointerDown={wake}
           // Capture, so shortcuts work from any control inside the player.
           onKeyDownCapture={onKeyDown}
         >
           {/* oxlint-disable-next-line jsx-a11y/media-has-caption -- Captions are optional. */}
           <video
             ref={video}
             className="riff-video-media"
             poster={poster}
             muted={muted}
             loop={loop}
             autoPlay={autoPlay}
             playsInline
             controls
             preload="metadata"
             aria-label={title}
             onClick={togglePlay}
           >
             <source src={src} {...(type && { type })} />
             {captions && (
               <track
                 ref={track}
                 kind="captions"
                 src={captions}
                 srcLang="en"
                 label="English"
               />
             )}
           </video>
           {enhanced && state.failed && (
             <p className="riff-video-message" role="alert">
               This video couldn’t play.
             </p>
           )}
           {enhanced && !state.failed && !started && (
             <button
               type="button"
               className="riff-video-start"
               aria-label="Play"
               onClick={togglePlay}
             >
               <Icon>{PLAY}</Icon>
             </button>
           )}
           {enhanced && started && state.waiting && (
             <span
               className="riff-video-spinner"
               role="status"
               aria-label="Loading"
             />
           )}
           {enhanced && started && !state.failed && (
             <div className="riff-video-controls">
               <Scrubber
                 time={state.time}
                 duration={state.duration}
                 buffered={state.buffered}
                 preview={preview}
                 onSeek={seek}
               />
               <div className="riff-video-toolbar">
                 <button
                   type="button"
                   className="riff-video-button"
                   aria-label={state.paused ? 'Play' : 'Pause'}
                   aria-keyshortcuts="k"
                   onClick={togglePlay}
                 >
                   <Icon>{state.paused ? PLAY : PAUSE}</Icon>
                 </button>
                 <div className="riff-video-volume">
                   <button
                     type="button"
                     className="riff-video-button"
                     aria-label={silent ? 'Unmute' : 'Mute'}
                     aria-keyshortcuts="m"
                     onClick={toggleMute}
                   >
                     <Icon>{volumeIcon}</Icon>
                   </button>
                   <input
                     type="range"
                     className="riff-video-range riff-video-volume-range"
                     aria-label="Volume"
                     aria-valuetext={`${Math.round((silent ? 0 : state.volume) * 100)}%`}
                     min={0}
                     max={1}
                     step={0.05}
                     value={silent ? 0 : state.volume}
                     style={cssVars({
                       '--riff-video-fill': `${(silent ? 0 : state.volume) * 100}%`,
                     })}
                     onChange={(event) =>
                       setVolume(event.currentTarget.valueAsNumber)
                     }
                   />
                 </div>
                 <span className="riff-video-time" aria-hidden="true">
                   {formatTime(state.time)} / {formatTime(state.duration)}
                 </span>
                 <span className="riff-video-spacer" />
                 <Menu open={menuOpen} onOpenChange={setMenuOpen}>
                   <MenuTrigger
                     className="riff-video-button"
                     aria-label="Settings"
                   >
                     <Icon>
                       <path d="M4 6h10M18 6h2M4 12h4M12 12h8M4 18h12M20 18h0" />
                       <circle cx="16" cy="6" r="2" />
                       <circle cx="10" cy="12" r="2" />
                       <circle cx="18" cy="18" r="2" />
                     </Icon>
                   </MenuTrigger>
                   <MenuContent
                     className="riff-video-menu"
                     side="top"
                     align="end"
                     sideOffset={8}
                   >
                     {captions && (
                       <>
                         <MenuCheckboxItem
                           className="riff-video-menu-item"
                           value="captions"
                           checked={captionsOn}
                           onCheckedChange={setCaptionsOn}
                         >
                           <MenuItemIndicator
                             keepMounted
                             className="riff-video-menu-check"
                           >
                             <Icon>
                               <path d="m5 12 5 5 9-10" />
                             </Icon>
                           </MenuItemIndicator>
                           Captions
                         </MenuCheckboxItem>
                         <MenuSeparator className="riff-video-menu-separator" />
                       </>
                     )}
                     <MenuRadioGroup
                       value={String(state.rate)}
                       onValueChange={(value) => {
                         if (video.current)
                           video.current.playbackRate = Number(value);
                       }}
                     >
                       <MenuGroupLabel className="riff-video-menu-label">
                         Speed
                       </MenuGroupLabel>
                       {RATES.map((rate) => (
                         <MenuRadioItem
                           key={rate}
                           className="riff-video-menu-item"
                           value={String(rate)}
                         >
                           <MenuItemIndicator
                             keepMounted
                             className="riff-video-menu-check"
                           >
                             <Icon>
                               <path d="m5 12 5 5 9-10" />
                             </Icon>
                           </MenuItemIndicator>
                           {rate === 1 ? 'Normal' : `${rate}×`}
                         </MenuRadioItem>
                       ))}
                     </MenuRadioGroup>
                   </MenuContent>
                 </Menu>
                 <button
                   type="button"
                   className="riff-video-button"
                   aria-label={fullscreen ? 'Exit fullscreen' : 'Fullscreen'}
                   aria-keyshortcuts="f"
                   onClick={() => void toggleFullscreen()}
                 >
                   <Icon>
                     {fullscreen ? (
                       <path d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5" />
                     ) : (
                       <path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" />
                     )}
                   </Icon>
                 </button>
               </div>
             </div>
           )}
         </div>
       </div>
     );
   }

   /** The seek bar: buffered range, played range, and a time and frame preview. */
   function Scrubber({
     time,
     duration,
     buffered,
     preview,
     onSeek,
   }: {
     time: number;
     duration: number;
     buffered: number;
     preview?: VideoPreview | undefined;
     onSeek: (time: number) => void;
   }) {
     const [hover, setHover] = useState<{ time: number; left: number } | null>(
       null,
     );
     const [shown, setShown] = useState(false);
     const inset = (preview?.width ?? 64) / 2 + 6;
     const show = (event: PointerEvent<HTMLInputElement>) => {
       if (event.pointerType === 'touch' || !duration) return;
       const box = event.currentTarget.getBoundingClientRect();
       const x = Math.max(0, Math.min(box.width, event.clientX - box.left));
       setHover({
         time: (x / box.width) * duration,
         left: Math.max(inset, Math.min(box.width - inset, x)),
       });
       setShown(true);
     };
     const percent = (value: number) => (duration ? (value / duration) * 100 : 0);
     const frameIndex =
       preview && hover
         ? Math.min(preview.frames - 1, Math.floor(hover.time / preview.interval))
         : 0;
     return (
       <div className="riff-video-scrubber">
         {hover && (
           <div
             className="riff-video-preview"
             aria-hidden="true"
             data-visible={shown ? '' : undefined}
             style={{ left: hover.left }}
           >
             {preview && (
               <span
                 className="riff-video-thumb"
                 style={{
                   width: preview.width,
                   height: preview.height,
                   backgroundImage: `url(${JSON.stringify(preview.src)})`,
                   backgroundSize: `${preview.width * preview.columns}px auto`,
                   backgroundPosition: `${-(frameIndex % preview.columns) * preview.width}px ${-Math.floor(frameIndex / preview.columns) * preview.height}px`,
                 }}
               />
             )}
             <span>{formatTime(hover.time)}</span>
           </div>
         )}
         <input
           type="range"
           className="riff-video-range riff-video-seek"
           aria-label="Seek"
           aria-valuetext={`${formatTime(time)} of ${formatTime(duration)}`}
           min={0}
           max={duration || 1}
           step={0.1}
           value={Math.min(time, duration)}
           disabled={!duration}
           style={cssVars({
             '--riff-video-fill': `${percent(time)}%`,
             '--riff-video-buffer': `${percent(buffered)}%`,
           })}
           onChange={(event) => onSeek(event.currentTarget.valueAsNumber)}
           onPointerEnter={show}
           onPointerMove={show}
           onPointerLeave={() => setShown(false)}
         />
       </div>
     );
   }
   ```

3. Copy its styles

   Save this beside it as `video-player.css`:

   ```css
   /* The player keeps its own dark chrome so controls stay legible over any
      frame in either page theme; focus rings still read --color-ring. */
   @layer components {
     .riff-video {
       --riff-video-ink: #fff;
       --riff-video-ground: #000;
       --riff-video-hover: rgb(255 255 255 / 16%);
       --riff-video-track: rgb(255 255 255 / 28%);
       --riff-video-ease: cubic-bezier(0.23, 1, 0.32, 1);
       width: 100%;
     }
     .riff-video-frame {
       position: relative;
       width: 100%;
       overflow: clip;
       border-radius: 0.75rem;
       background-color: var(--riff-video-ground);
       color: var(--riff-video-ink);
       container-type: inline-size;
       &:fullscreen {
         border-radius: 0;
       }
       &[data-controls='hidden'] {
         cursor: none;
       }
     }
     .riff-video-media {
       position: absolute;
       inset: 0;
       width: 100%;
       height: 100%;
       object-fit: contain;
       &::cue {
         background-color: rgb(0 0 0 / 70%);
         color: var(--riff-video-ink);
         font-family: inherit;
         font-size: clamp(0.8125rem, 4cqw, 1.0625rem);
       }
     }
     .riff-video-icon {
       width: 1.25rem;
       height: 1.25rem;
     }
     .riff-video-start {
       position: absolute;
       top: 50%;
       left: 50%;
       display: grid;
       width: 5rem;
       height: 5rem;
       place-items: center;
       border: 0;
       border-radius: 999px;
       background-color: rgb(0 0 0 / 60%);
       box-shadow: 0 10px 30px rgb(0 0 0 / 30%);
       color: var(--riff-video-ink);
       cursor: pointer;
       translate: -50% -50%;
       backdrop-filter: blur(8px);
       transition:
         scale 250ms var(--riff-video-ease),
         background-color 150ms var(--riff-video-ease);
       & > .riff-video-icon {
         width: 2.25rem;
         height: 2.25rem;
         translate: 2px 0;
       }
       &:active {
         scale: 0.96;
       }
     }
     .riff-video-message {
       position: absolute;
       inset: 0;
       display: grid;
       margin: 0;
       place-items: center;
       font-size: 0.875rem;
     }
     .riff-video-spinner {
       position: absolute;
       top: calc(50% - 1.25rem);
       left: calc(50% - 1.25rem);
       width: 2.5rem;
       height: 2.5rem;
       border: 3px solid rgb(255 255 255 / 25%);
       border-top-color: var(--riff-video-ink);
       border-radius: 999px;
       animation: riff-video-spin 800ms linear infinite;
       pointer-events: none;
     }
     @keyframes riff-video-spin {
       to {
         rotate: 1turn;
       }
     }
     .riff-video-controls {
       position: absolute;
       right: 0;
       bottom: 0;
       left: 0;
       padding: 1.5rem 0.5rem 0.5rem;
       background: linear-gradient(to top, rgb(0 0 0 / 75%), transparent);
       transition: opacity 150ms ease;
       .riff-video-frame[data-controls='hidden'] & {
         opacity: 0;
         pointer-events: none;
       }
     }
     .riff-video-toolbar {
       display: flex;
       min-width: 0;
       align-items: center;
       gap: 0.125rem;
     }
     .riff-video-spacer {
       flex: 1;
     }
     .riff-video-time {
       padding-inline: 0.25rem;
       font-size: 0.8125rem;
       font-variant-numeric: tabular-nums;
       font-weight: 500;
       white-space: nowrap;
     }
     .riff-video-button {
       display: grid;
       width: 2rem;
       height: 2rem;
       flex: none;
       place-items: center;
       border: 0;
       border-radius: 0.375rem;
       padding: 0;
       background: none;
       color: inherit;
       cursor: pointer;
       transition: background-color 150ms var(--riff-video-ease);
       &[data-open] {
         background-color: var(--riff-video-hover);
       }
     }
     .riff-video-button,
     .riff-video-start,
     .riff-video-range {
       &:focus-visible {
         outline: 2px solid var(--color-ring, Highlight);
         outline-offset: 1px;
       }
     }
     /* Ranges: a 4px track filled to --riff-video-fill, with a 12px thumb. */
     .riff-video-range {
       --riff-video-rail: linear-gradient(
         to right,
         var(--riff-video-ink) var(--riff-video-fill, 0%),
         transparent var(--riff-video-fill, 0%)
       );
       height: 1rem;
       margin: 0;
       background: none;
       appearance: none;
       cursor: pointer;
       &::-webkit-slider-runnable-track {
         height: 4px;
         border-radius: 999px;
         background: var(--riff-video-rail), var(--riff-video-track);
       }
       &::-moz-range-track {
         height: 4px;
         border-radius: 999px;
         background: var(--riff-video-rail), var(--riff-video-track);
       }
       &::-webkit-slider-thumb {
         width: 12px;
         height: 12px;
         margin-top: -4px;
         border: 0;
         border-radius: 999px;
         background: var(--riff-video-ink);
         appearance: none;
       }
       &::-moz-range-thumb {
         width: 12px;
         height: 12px;
         border: 0;
         border-radius: 999px;
         background: var(--riff-video-ink);
       }
     }
     .riff-video-scrubber {
       position: relative;
       margin: 0 0.25rem 0.25rem;
     }
     .riff-video-seek {
       display: block;
       width: 100%;
       /* The buffered range sits between the track and the played fill. */
       --riff-video-rail:
         linear-gradient(
           to right,
           var(--riff-video-ink) var(--riff-video-fill, 0%),
           transparent var(--riff-video-fill, 0%)
         ),
         linear-gradient(
           to right,
           rgb(255 255 255 / 45%) var(--riff-video-buffer, 0%),
           transparent var(--riff-video-buffer, 0%)
         );
     }
     /* Volume slides out beside its button on hover or focus. */
     .riff-video-volume {
       display: flex;
       align-items: center;
     }
     .riff-video-volume-range {
       width: 0;
       opacity: 0;
       transition:
         width 200ms var(--riff-video-ease),
         opacity 150ms var(--riff-video-ease);
     }
     .riff-video-volume:is(:hover, :focus-within) .riff-video-volume-range {
       width: 4.5rem;
       margin-inline: 0.25rem 0.5rem;
       opacity: 1;
     }
     .riff-video-preview {
       position: absolute;
       bottom: calc(100% + 0.5rem);
       display: flex;
       flex-direction: column;
       align-items: center;
       gap: 0.25rem;
       border: 1px solid rgb(255 255 255 / 20%);
       border-radius: 0.5rem;
       padding: 0.25rem;
       background-color: rgb(0 0 0 / 75%);
       font-size: 0.75rem;
       font-variant-numeric: tabular-nums;
       white-space: nowrap;
       opacity: 0;
       pointer-events: none;
       translate: -50% 0;
       transition: opacity 125ms var(--riff-video-ease);
       &[data-visible] {
         opacity: 1;
       }
     }
     .riff-video-thumb {
       display: block;
       border-radius: 0.25rem;
       background-repeat: no-repeat;
     }
     /* The settings menu keeps the player's dark chrome. */
     .riff-video-menu {
       min-width: 10rem;
       border: 1px solid rgb(255 255 255 / 14%);
       border-radius: 0.625rem;
       padding: 0.25rem;
       background-color: rgb(28 28 28 / 96%);
       box-shadow: 0 12px 32px rgb(0 0 0 / 35%);
       color: var(--riff-video-ink);
       font-size: 0.8125rem;
       transform-origin: var(--transform-origin);
       transition:
         opacity 150ms var(--riff-video-ease),
         scale 150ms var(--riff-video-ease);
       &:is([data-starting-style], [data-ending-style]) {
         opacity: 0;
         scale: 0.96;
       }
     }
     .riff-video-menu-label {
       padding: 0.375rem 0.5rem 0.25rem;
       color: rgb(255 255 255 / 60%);
       font-size: 0.75rem;
     }
     .riff-video-menu-item {
       display: flex;
       min-height: 2rem;
       align-items: center;
       gap: 0.5rem;
       border-radius: 0.375rem;
       padding: 0 0.5rem;
       cursor: pointer;
       outline: none;
       &[data-highlighted] {
         background-color: var(--riff-video-hover);
       }
     }
     .riff-video-menu-check {
       display: grid;
       width: 1rem;
       place-items: center;
       &[data-unchecked] {
         visibility: hidden;
       }
       & .riff-video-icon {
         width: 0.875rem;
         height: 0.875rem;
       }
     }
     .riff-video-menu-separator {
       height: 1px;
       margin: 0.25rem;
       background-color: rgb(255 255 255 / 14%);
     }
     @container (width < 340px) {
       .riff-video-time {
         display: none;
       }
     }
     @media (hover: hover) {
       .riff-video-button:hover {
         background-color: var(--riff-video-hover);
       }
       .riff-video-start:hover {
         background-color: rgb(0 0 0 / 75%);
       }
     }
     @media (prefers-reduced-motion: reduce) {
       .riff-video-start,
       .riff-video-controls,
       .riff-video-button,
       .riff-video-volume-range,
       .riff-video-preview,
       .riff-video-menu {
         transition: none;
       }
     }
     @media (forced-colors: active) {
       .riff-video-controls {
         background: Canvas;
         color: CanvasText;
       }
       .riff-video-menu-item[data-highlighted] {
         outline: 1px solid Highlight;
       }
     }
   }
   ```

## Usage

```tsx
import { VideoPlayer } from '@/components/ui/video-player';

<VideoPlayer
  src="/videos/demo.mp4"
  title="Product demo"
  poster="/videos/demo.webp"
  captions="/videos/demo.vtt"
/>;
```

Before scripts run, the browser’s own controls work. Then the player takes over: Space or K plays and pauses, the arrows seek 5 seconds, M mutes, C toggles captions and F goes fullscreen. Pass `preview` with a sprite sheet to show frames above the seek bar.

For HLS where the browser has no native support, load the stream in `attach`, for example with hls.js:

```tsx
<VideoPlayer
  src="/stream.m3u8"
  title="Talk"
  attach={(video, src) => {
    const hls = new Hls();
    hls.loadSource(src);
    hls.attachMedia(video);
    return () => hls.destroy();
  }}
/>
```

## Props

| Prop                    | Type                         | Default    | Description                                        |
| ----------------------- | ---------------------------- | ---------- | -------------------------------------------------- |
| `src`                   | `string`                     |            | An MP4 or WebM file, or the stream `attach` loads. |
| `title`                 | `string`                     |            | Names the player.                                  |
| `poster`                | `string`                     |            | The image before playback.                         |
| `captions`              | `string`                     |            | A WebVTT file of English captions.                 |
| `preview`               | `VideoPreview`               |            | A frame sprite for the seek preview.               |
| `aspectRatio`           | `string`                     | `'16 / 9'` | The frame’s ratio.                                 |
| `autoPlay, muted, loop` | `boolean`                    | `false`    | As on `<video>`.                                   |
| `attach`                | `(video, src) => () => void` |            | Loads `src` with your own engine.                  |

## Structured data

```json
{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "WebSite",
      "@id": "https://sarthakmishra.com/#website",
      "url": "https://sarthakmishra.com/",
      "name": "Sarthak Mishra",
      "publisher": {
        "@id": "https://sarthakmishra.com/#person"
      },
      "inLanguage": "en"
    },
    {
      "@type": "Person",
      "@id": "https://sarthakmishra.com/#person",
      "name": "Sarthak Mishra",
      "url": "https://sarthakmishra.com/about",
      "jobTitle": "Design Engineer",
      "image": "https://sarthakmishra.com/og-images/sarthak-mishra.webp",
      "sameAs": [
        "https://github.com/SarthakMishra",
        "https://www.linkedin.com/in/itssarthakmishra/",
        "https://x.com/MishraMishry"
      ]
    },
    {
      "@type": "WebPage",
      "@id": "https://sarthakmishra.com/riff-ui/components/video-player#webpage",
      "url": "https://sarthakmishra.com/riff-ui/components/video-player",
      "name": "Video player React Component - Riff UI",
      "description": "Video with custom controls, a seek preview, captions, speeds and shortcuts. Accessible React 19 source on UI SDK, installed with the shadcn CLI.",
      "inLanguage": "en",
      "isPartOf": {
        "@id": "https://sarthakmishra.com/#website"
      },
      "about": {
        "@id": "https://sarthakmishra.com/#person"
      }
    }
  ]
}
```
