# Video player

> Native video with a themed control bar: seek, volume, speed, captions and fullscreen. Plain controls without script.

- Kind: ui · Category: Data display · Interactivity: script
- Install: `npx shadcn@latest add @haze/video-player`
- File: `src/components/haze/ui/video-player.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/ui/video-player

## Use when
- A product walkthrough or short tutorial clip hosted as a file you control
- Media that needs captions, a visible seek bar and keyboard shortcuts in the site's own style
- A recording embedded in docs or a changelog entry where autoplay would be rude

## Avoid when
- Live streams, DRM or adaptive streaming need a dedicated player library.
- A decorative looping background clip needs no controls; use a plain video element.
- Audio-only content such as a podcast is better served by a native audio element.

## Alternatives
- [aspect-ratio](https://hazeui.com/ui/aspect-ratio.md)
- [story-viewer](https://hazeui.com/ui/story-viewer.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique on the page. Becomes the id of the video element. |
| src | `string` | "/media/video-player/demo.mp4" | no | URL of the video file (MP4 with H.264 plays everywhere). |
| poster | `string` |  | no | Image shown before the first play. Without one, the browser shows the first frame. |
| title | `string` | "Product walkthrough clip" | no | Accessible name of the player region. |
| captions | `{ src: string; srclang: string; label: string } \| null` | demo WebVTT file | no | WebVTT captions track. Pass null for none; the captions button is then omitted. |
| aspect | `string` | "aspect-video" | no | Tailwind aspect-ratio class for the picture area. |
| class | `string` |  | no | Extra classes on the player frame. |

## Accessibility
- Without script the browser's own controls stay on, so the video is fully usable. The script removes them and adds the themed bar.
- The frame is a labelled region. The seek slider is a native range input with aria-valuetext such as "1:05 of 2:30".
- Mute, captions and fullscreen are toggle buttons with aria-pressed; the play button changes its label between Play and Pause.
- Speed, mute and captions changes are announced through a polite status region.
- Nothing autoplays, with or without reduced-motion settings. Captions need a WebVTT track; transcripts for longer clips belong next to the player.
- Key Space / K: Play or pause from the video or the seek slider
- Key Left / Right (seek slider): Jump back or forward 5 seconds
- Key Tab / Shift+Tab: Move between play, mute, volume, speed, captions and fullscreen
- Key Enter / Space (button): Activate the focused control

## Agent prompts

### Install and use

Install the Haze UI component "Video player" with `npx shadcn@latest add @haze/video-player`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import VideoPlayer from "@/components/haze/ui/video-player.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/video-player.md

### Customize with real content

Adapt the Haze video-player ui for our product. Replace the demo values of these props with our real content: id, src, poster, title, captions, aspect, class. Keep the layout, the heading level rules and these accessibility details: Without script the browser's own controls stay on, so the video is fully usable. The script removes them and adds the themed bar. The frame is a labelled region. The seek slider is a native range input with aria-valuetext such as "1:05 of 2:30". Mute, captions and fullscreen are toggle buttons with aria-pressed; the play button changes its label between Play and Pause. Speed, mute and captions changes are announced through a polite status region. Nothing autoplays, with or without reduced-motion settings. Captions need a WebVTT track; transcripts for longer clips belong next to the player. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using video-player, check it fits: use it when a product walkthrough or short tutorial clip hosted as a file you control; media that needs captions, a visible seek bar and keyboard shortcuts in the site's own style; a recording embedded in docs or a changelog entry where autoplay would be rude. Avoid it when live streams, drm or adaptive streaming need a dedicated player library.; a decorative looping background clip needs no controls; use a plain video element.; audio-only content such as a podcast is better served by a native audio element.. Alternatives: @haze/aspect-ratio, @haze/story-viewer.

## Example requests that should lead here
- Embed a two-minute onboarding video with English captions and a poster image
- Show a changelog demo clip that never autoplays and has a speed control

## Source

```astro
---
import { Captions, Maximize, Minimize, Pause, Play, Volume2, VolumeX } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface Props {
  /** Unique on the page. Becomes the id of the <video>; the other ids derive from it. */
  id: string;
  src?: string;
  poster?: string;
  /** Accessible name of the player region. */
  title?: string;
  /** Pass null to render without a captions track. */
  captions?: { src: string; srclang: string; label: string } | null;
  /** Tailwind aspect-ratio class for the picture area. */
  aspect?: string;
  class?: string;
}

const {
  id,
  src = "/media/video-player/demo.mp4",
  poster,
  title = "Product walkthrough clip",
  captions = { src: "/media/video-player/demo.vtt", srclang: "en", label: "English" },
  aspect = "aspect-video",
  class: className,
} = Astro.props;

const iconButton =
  "group inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-lg border border-transparent text-muted-foreground transition-[background-color,color,scale] duration-150 ease-snappy hover:bg-accent hover:text-foreground aria-pressed:bg-muted aria-pressed:text-foreground active:scale-[0.97] active:duration-75 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring [&_svg]:size-4 [&_svg]:shrink-0";
const rangeStyle = cn(
  "h-8 min-w-0 cursor-pointer appearance-none rounded-md bg-transparent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring disabled:cursor-not-allowed disabled:opacity-50",
  "[&::-webkit-slider-runnable-track]:h-1.5 [&::-webkit-slider-runnable-track]:rounded-full [&::-webkit-slider-runnable-track]:bg-input",
  "[&::-webkit-slider-thumb]:-mt-1.25 [&::-webkit-slider-thumb]:size-4 [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:border-0 [&::-webkit-slider-thumb]:bg-foreground [&::-webkit-slider-thumb]:shadow-key",
  "[&::-moz-range-track]:h-1.5 [&::-moz-range-track]:rounded-full [&::-moz-range-track]:bg-input",
  "[&::-moz-range-thumb]:size-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:border-0 [&::-moz-range-thumb]:bg-foreground [&::-moz-range-thumb]:shadow-key",
  "forced-colors:appearance-auto",
);
---

<div
  data-haze-video-player
  role="region"
  aria-label={title}
  class={cn(
    "group/vp relative w-full min-w-0 overflow-hidden rounded-xl border border-frame bg-card [&:fullscreen]:flex [&:fullscreen]:flex-col [&:fullscreen]:rounded-none [&:fullscreen]:border-0",
    className,
  )}
>
  <div class={cn("relative bg-background [:fullscreen_&]:aspect-auto [:fullscreen_&]:min-h-0 [:fullscreen_&]:flex-1", aspect)}>
    <video
      id={id}
      src={src}
      poster={poster}
      controls
      preload="metadata"
      playsinline
      class="size-full object-contain"
    >
      {captions && <track kind="captions" src={captions.src} srclang={captions.srclang} label={captions.label} />}
      <p class="p-4 text-[0.8125rem]/5 text-muted-foreground">Your browser cannot play this video. <a href={src} class="rounded-sm text-foreground underline underline-offset-4 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring">Download it instead</a>.</p>
    </video>
    <button
      type="button"
      data-vp-big
      hidden
      aria-label="Play video"
      class="absolute inset-0 m-auto inline-flex size-14 cursor-pointer items-center justify-center rounded-full border border-frame bg-background/60 text-foreground transition-[background-color,scale] duration-150 ease-snappy hover:bg-background/80 active:scale-[0.97] active:duration-75 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
    >
      <Play aria-hidden="true" class="size-6 translate-x-px" />
    </button>
  </div>
  <div data-vp-bar hidden class="grid gap-0.5 border-t border-border bg-background/40 px-2 py-1.5">
    <div class="flex items-center gap-2">
      <span data-vp-current class="w-10 shrink-0 text-right text-xs/5 tabular-nums text-muted-foreground">0:00</span>
      <input data-vp-seek type="range" min="0" max="0" step="0.1" value="0" aria-label="Seek" aria-valuetext="0:00 of 0:00" class={cn("flex-1", rangeStyle)} />
      <span data-vp-duration class="w-10 shrink-0 text-xs/5 tabular-nums text-muted-foreground">0:00</span>
    </div>
    <div class="flex flex-wrap items-center gap-1">
      <button type="button" data-vp-play aria-label="Play" class={iconButton}>
        <Pause aria-hidden="true" class="hidden group-data-[playing]/vp:block" />
        <Play aria-hidden="true" class="group-data-[playing]/vp:hidden" />
      </button>
      <button type="button" data-vp-mute aria-label="Mute" aria-pressed="false" class={iconButton}>
        <Volume2 aria-hidden="true" class="group-aria-pressed:hidden" />
        <VolumeX aria-hidden="true" class="hidden group-aria-pressed:block" />
      </button>
      <input data-vp-volume type="range" min="0" max="1" step="0.05" value="1" aria-label="Volume" class={cn("w-16 shrink-0 sm:w-20", rangeStyle)} />
      <div class="ml-auto flex items-center gap-1">
        <button
          type="button"
          data-vp-rate
          aria-label="Playback speed 1×"
          class="inline-flex h-8 min-w-10 shrink-0 cursor-pointer items-center justify-center rounded-lg border border-transparent px-2 text-xs/5 font-medium tabular-nums text-muted-foreground transition-[background-color,color,scale] duration-150 ease-snappy hover:bg-accent hover:text-foreground active:scale-[0.97] active:duration-75 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
        >1×</button>
        {
          captions && (
            <button type="button" data-vp-captions aria-label="Captions" aria-pressed="false" class={iconButton}>
              <Captions aria-hidden="true" />
            </button>
          )
        }
        <button type="button" data-vp-fullscreen hidden aria-label="Fullscreen" aria-pressed="false" class={iconButton}>
          <Maximize aria-hidden="true" class="group-aria-pressed:hidden" />
          <Minimize aria-hidden="true" class="hidden group-aria-pressed:block" />
        </button>
      </div>
    </div>
  </div>
  <p data-vp-status role="status" class="sr-only"></p>
</div>

<script>
  const RATES = [1, 1.25, 1.5, 2];
  const root = document.documentElement;

  function clock(seconds: number): string {
    if (!Number.isFinite(seconds) || seconds < 0) seconds = 0;
    const total = Math.floor(seconds);
    const h = Math.floor(total / 3600);
    const m = Math.floor((total % 3600) / 60);
    const s = String(total % 60).padStart(2, "0");
    return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${s}` : `${m}:${s}`;
  }

  function fullscreenElement(): Element | null {
    return document.fullscreenElement ?? (document as unknown as { webkitFullscreenElement?: Element }).webkitFullscreenElement ?? null;
  }

  function setup(player: HTMLElement) {
    player.setAttribute("data-enhanced", "");
    const video = player.querySelector<HTMLVideoElement>("video");
    const bar = player.querySelector<HTMLElement>("[data-vp-bar]");
    const big = player.querySelector<HTMLButtonElement>("[data-vp-big]");
    const play = player.querySelector<HTMLButtonElement>("[data-vp-play]");
    const seek = player.querySelector<HTMLInputElement>("[data-vp-seek]");
    const current = player.querySelector<HTMLElement>("[data-vp-current]");
    const duration = player.querySelector<HTMLElement>("[data-vp-duration]");
    const mute = player.querySelector<HTMLButtonElement>("[data-vp-mute]");
    const volume = player.querySelector<HTMLInputElement>("[data-vp-volume]");
    const rate = player.querySelector<HTMLButtonElement>("[data-vp-rate]");
    const captionsButton = player.querySelector<HTMLButtonElement>("[data-vp-captions]");
    const fullscreen = player.querySelector<HTMLButtonElement>("[data-vp-fullscreen]");
    const status = player.querySelector<HTMLElement>("[data-vp-status]");
    if (!video || !bar || !big || !play || !seek || !current || !duration || !mute || !volume || !rate) return;

    const announce = (text: string) => { if (status) status.textContent = text; };
    const track = video.textTracks[0] as TextTrack | undefined;
    let scrubbing = false;

    const toggle = () => {
      if (video.paused || video.ended) video.play().catch(() => {});
      else video.pause();
    };
    const total = () => (Number.isFinite(video.duration) ? video.duration : 0);

    const setSeekText = () => {
      const text = `${clock(video.currentTime)} of ${clock(total())}`;
      if (seek.getAttribute("aria-valuetext") !== text) seek.setAttribute("aria-valuetext", text);
    };
    // Whole seconds only: the text changes once a second, not on every timeupdate.
    const showTime = () => {
      current.textContent = clock(video.currentTime);
      if (!scrubbing) seek.value = String(video.currentTime);
      setSeekText();
    };
    const hideBig = () => {
      if (document.activeElement === big) play.focus();
      big.hidden = true;
    };
    const showDuration = () => {
      seek.max = String(total());
      duration.textContent = clock(total());
      showTime();
    };
    const showPlaying = () => {
      const playing = !video.paused && !video.ended;
      player.toggleAttribute("data-playing", playing);
      play.setAttribute("aria-label", playing ? "Pause" : "Play");
    };
    const showVolume = () => {
      const silent = video.muted || video.volume === 0;
      mute.setAttribute("aria-pressed", String(silent));
      volume.value = String(video.muted ? 0 : video.volume);
      volume.setAttribute("aria-valuetext", video.muted ? "Muted" : `${Math.round(video.volume * 100)}%`);
    };
    const showRate = () => {
      const label = `${video.playbackRate}×`;
      rate.textContent = label;
      rate.setAttribute("aria-label", `Playback speed ${label}`);
    };

    video.removeAttribute("controls");
    bar.hidden = false;
    big.hidden = video.played.length > 0 || video.currentTime > 0;
    video.tabIndex = -1;
    if (fullscreen && ("requestFullscreen" in player || "webkitRequestFullscreen" in player || "webkitEnterFullscreen" in video)) {
      fullscreen.hidden = false;
    }
    if (captionsButton && track) {
      if (track.mode === "disabled") track.mode = "hidden";
      captionsButton.setAttribute("aria-pressed", String(track.mode === "showing"));
    } else if (captionsButton) {
      captionsButton.hidden = true;
    }

    play.addEventListener("click", toggle);
    big.addEventListener("click", () => { toggle(); });
    video.addEventListener("click", toggle);
    video.addEventListener("play", () => { hideBig(); showPlaying(); });
    video.addEventListener("ratechange", showRate);
    video.addEventListener("pause", showPlaying);
    video.addEventListener("ended", showPlaying);
    video.addEventListener("timeupdate", showTime);
    video.addEventListener("seeked", showTime);
    video.addEventListener("loadedmetadata", showDuration);
    video.addEventListener("durationchange", showDuration);
    video.addEventListener("volumechange", showVolume);

    seek.addEventListener("pointerdown", () => { scrubbing = true; });
    const endScrub = () => { scrubbing = false; showTime(); };
    seek.addEventListener("pointerup", endScrub);
    seek.addEventListener("pointercancel", endScrub);
    seek.addEventListener("change", endScrub);
    seek.addEventListener("blur", endScrub);
    seek.addEventListener("input", () => {
      video.currentTime = Number(seek.value);
      current.textContent = clock(video.currentTime);
      setSeekText();
    });
    seek.addEventListener("keydown", (event) => {
      if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
      event.preventDefault();
      const step = event.key === "ArrowRight" ? 5 : -5;
      video.currentTime = Math.min(total(), Math.max(0, video.currentTime + step));
      showTime();
    });

    mute.addEventListener("click", () => {
      video.muted = !video.muted;
      if (!video.muted && video.volume === 0) video.volume = 0.5;
      announce(video.muted ? "Muted" : "Sound on");
    });
    volume.addEventListener("input", () => {
      video.volume = Number(volume.value);
      video.muted = video.volume === 0;
    });

    rate.addEventListener("click", () => {
      const next = RATES[(RATES.indexOf(video.playbackRate) + 1) % RATES.length] ?? 1;
      video.playbackRate = next;
      showRate();
      announce(`Speed ${next}×`);
    });

    captionsButton?.addEventListener("click", () => {
      if (!track) return;
      track.mode = track.mode === "showing" ? "hidden" : "showing";
      captionsButton.setAttribute("aria-pressed", String(track.mode === "showing"));
      announce(track.mode === "showing" ? "Captions on" : "Captions off");
    });

    fullscreen?.addEventListener("click", () => {
      if (fullscreenElement() === player) {
        (document.exitFullscreen ?? (document as unknown as { webkitExitFullscreen?: () => void }).webkitExitFullscreen)?.call(document);
      } else if ("requestFullscreen" in player || "webkitRequestFullscreen" in player) {
        (player.requestFullscreen ?? (player as unknown as { webkitRequestFullscreen?: () => void }).webkitRequestFullscreen)?.call(player);
      } else {
        // iOS Safari only fullscreens the video element itself.
        (video as unknown as { webkitEnterFullscreen?: () => void }).webkitEnterFullscreen?.();
      }
    });

    // Space and K toggle playback from anywhere in the player except on a control that uses the key itself.
    player.addEventListener("keydown", (event) => {
      if (event.key !== " " && event.key !== "k" && event.key !== "K") return;
      if ((event.target as Element).closest("button, select, a")) return;
      event.preventDefault();
      toggle();
    });

    showDuration();
    showPlaying();
    showVolume();
    showRate();
  }

  const init = () => {
    document.querySelectorAll<HTMLElement>("[data-haze-video-player]:not([data-enhanced])").forEach(setup);
  };
  init();
  if (!root.hasAttribute("data-haze-video-player-listener")) {
    root.setAttribute("data-haze-video-player-listener", "");
    document.addEventListener("astro:page-load", init);
    const syncFullscreen = () => {
      document.querySelectorAll<HTMLElement>("[data-haze-video-player][data-enhanced]").forEach((player) => {
        player.querySelector("[data-vp-fullscreen]")?.setAttribute("aria-pressed", String(fullscreenElement() === player));
      });
    };
    document.addEventListener("fullscreenchange", syncFullscreen);
    document.addEventListener("webkitfullscreenchange", syncFullscreen);
  }
</script>
```
