Video for Astro
Play video files and YouTube URLs with shared controls. Use the same component for background video.
Installation
bunx --bun shadcn@latest add @gnostic/videonpx shadcn@latest add @gnostic/videopnpm dlx shadcn@latest add @gnostic/videoComponent classes: Default Gnostic.
Complete the Installation guide first. Then copy the component files below.
Install component packages
bun add @data-slot/core @data-slot/sliderCopy the files
src/components/ui/video/index.ts
export { default as Video } from './video.astro'
export { default as VideoToggle } from './video-toggle.astro'
export { default as VideoControls } from './video-controls.astro'
export type { VideoProps, VideoToggleProps } from './types.ts'
export { createVideo } from './video-controller.ts'
export type { VideoController } from './video-controller.ts'
src/components/ui/video/types.ts
/** Shared options for native video files and YouTube URLs. */
export interface VideoProps {
/**
* Show a play overlay until playback starts. The play-overlay slot enables it
* unless this prop is false.
* @default false
*/
playOverlay?: boolean
/** Classes for the video or iframe, such as object-cover or object-position. */
mediaClass?: string
/**
* Pause outside the viewport or in a hidden tab. A manual pause remains in effect.
* @default false
*/
pauseWhenHidden?: boolean
/**
* Hide decorative media from assistive technology. Does not change playback.
* @default false
*/
decorative?: boolean
}
/** Optional play/pause button for a Video without a full control bar. */
export interface VideoToggleProps {
/** ID of the Video to control. Omit when the button is inside the Video overlay slot. */
for?: string
/** Label and default text when paused. @default "Play" */
playLabel?: string
/** Label and default text when playing. @default "Pause" */
pauseLabel?: string
}
src/components/ui/video/video-adapter.ts
/** Internal playback contract shared by native video and YouTube. */
export interface VideoState {
paused: boolean
ended: boolean
waiting: boolean
currentTime: number
duration: number
muted: boolean
volume: number
}
export type VideoEvent =
| 'update'
| 'play'
| 'pause'
| 'ended'
| 'blocked'
| 'error'
export interface VideoAdapter {
read(): VideoState
play(): Promise<void> | void
pause(): void
seek(seconds: number): void
mute(muted: boolean): void
volume(value: number): void
destroy(): void
}
export type VideoNotify = (event: VideoEvent) => void
src/components/ui/video/video-controller.ts
import {
clearRootBinding,
ensureId,
getRootBinding,
getRoots,
hasRootBinding,
setRootBinding,
} from '@data-slot/core'
import { createSlider } from '@data-slot/slider'
import { nativeVideo } from './video-native.ts'
import { youtubeVideo } from './video-youtube.ts'
import type { VideoAdapter, VideoEvent } from './video-adapter.ts'
export interface VideoController {
destroy(): void
}
export function createVideo(root: HTMLElement): VideoController {
const existing = getRootBinding<VideoController>(root, '@gnostic/video')
if (existing) return existing
const events = new AbortController()
const cleanup = setupVideo(root, events.signal)
const controller: VideoController = {
destroy() {
if (events.signal.aborted) return
events.abort()
cleanup?.()
clearRootBinding(root, '@gnostic/video', controller)
},
}
return setRootBinding(root, '@gnostic/video', controller)
}
export function create(scope: ParentNode = document): VideoController[] {
return getRoots<HTMLElement>(scope, 'video')
.filter((root) => !hasRootBinding(root, '@gnostic/video'))
.map((root) => createVideo(root))
}
export function formatVideoTime(value: number) {
const seconds = Math.max(0, Math.floor(Number.isFinite(value) ? value : 0))
const hours = Math.floor(seconds / 3600)
const minutes = Math.floor((seconds % 3600) / 60)
return `${hours ? `${hours}:${String(minutes).padStart(2, '0')}` : minutes}:${String(seconds % 60).padStart(2, '0')}`
}
/** Own controls and playback for one player. */
function setupVideo(root: HTMLElement, signal: AbortSignal) {
const owned = <T extends HTMLElement>(selector: string) =>
[...root.querySelectorAll<T>(selector)].filter(
(element) => element.closest('[data-slot="video"]') === root,
)
const media = owned<HTMLVideoElement | HTMLIFrameElement>(
'[data-slot="video-media"]',
)[0]
if (!media) return
const id = ensureId(root, 'video')
const native = media instanceof HTMLVideoElement ? media : undefined
const controls = owned<HTMLElement>('[data-slot="video-controls"]')[0]
const buttons = [
...owned<HTMLButtonElement>('[data-video-action]').filter(
(button) =>
!button.dataset.videoFor || button.dataset.videoFor === id,
),
...[
...document.querySelectorAll<HTMLButtonElement>('[data-video-for]'),
].filter(
(button) =>
button.dataset.videoFor === id && !root.contains(button),
),
]
const restoreControls = buttons.map((button) => {
const previous = button.getAttribute('aria-controls')
ensureId(button, 'video-trigger')
button.setAttribute('aria-controls', id)
return () => {
if (previous === null) button.removeAttribute('aria-controls')
else button.setAttribute('aria-controls', previous)
}
})
const reduced = matchMedia('(prefers-reduced-motion: reduce)')
const playOverlays = buttons.filter(
(button) => button.dataset.videoAction === 'start',
)
let started = root.dataset.started === 'true'
const pauseWhenHidden = root.hasAttribute('data-pause-when-hidden')
let visible =
!pauseWhenHidden || typeof IntersectionObserver === 'undefined'
const canPlay = () => !pauseWhenHidden || (visible && !document.hidden)
let adapter: VideoAdapter | undefined
let wantsPlayback = root.dataset.autoplay === 'true' && !reduced.matches
let pendingPlay = 0
let request = 0
let syncing = false
let failed = false
const error = owned<HTMLElement>('[data-video-error]')[0]
const timers = owned<HTMLElement>('[data-video-time]')
const sliders = owned<HTMLElement>(
'[data-video-seek], [data-video-volume]',
).map((element) => {
const slider = createSlider(element)
const thumb = element.querySelector<HTMLElement>(
'[data-slot="slider-thumb"]',
)!
const seek = element.hasAttribute('data-video-seek')
thumb.setAttribute('aria-label', seek ? 'Playback position' : 'Volume')
element.addEventListener(
'slider:change',
(event) => {
if (syncing || !adapter || failed) return
const value = (event as CustomEvent<{ value: number }>).detail
.value
if (!Number.isFinite(value)) return
const state = adapter.read()
if (seek) {
if (Number.isFinite(state.duration) && state.duration > 0)
adapter.seek((state.duration * value) / 100)
} else {
adapter.volume(value / 100)
adapter.mute(value === 0)
}
update()
},
{ signal },
)
return { element, slider, thumb, seek }
})
const captionTracks = () =>
native
? [...native.textTracks].filter((track) =>
['captions', 'subtitles'].includes(track.kind),
)
: []
const update = () => {
if (signal.aborted || !adapter || failed) return
const state = adapter.read()
const paused = state.paused || state.ended
if (playOverlays.length && !started && !paused && !state.waiting) {
started = true
if (
playOverlays.some((button) => button === document.activeElement)
) {
const toggle = buttons.find(
(button) =>
button.dataset.videoAction === 'play' && !button.hidden,
)
if (toggle) toggle.focus({ preventScroll: true })
else {
root.setAttribute('tabindex', '-1')
root.focus({ preventScroll: true })
}
}
root.dataset.started = 'true'
}
const muted = state.muted || state.volume === 0
const duration =
Number.isFinite(state.duration) && state.duration > 0
? state.duration
: 0
root.dataset.state = state.ended
? 'ended'
: state.waiting
? 'loading'
: paused
? 'paused'
: 'playing'
for (const button of buttons) {
switch (button.dataset.videoAction) {
case 'play':
button.setAttribute(
'aria-label',
(paused
? button.dataset.playLabel
: button.dataset.pauseLabel) ??
(paused ? 'Play' : 'Pause'),
)
for (const part of button.querySelectorAll<HTMLElement>(
'[data-video-play]',
))
part.hidden = !paused
for (const part of button.querySelectorAll<HTMLElement>(
'[data-video-pause]',
))
part.hidden = paused
break
case 'mute':
button.setAttribute('aria-label', muted ? 'Unmute' : 'Mute')
for (const part of button.querySelectorAll<HTMLElement>(
'[data-video-audible]',
))
part.hidden = muted
for (const part of button.querySelectorAll<HTMLElement>(
'[data-video-muted]',
))
part.hidden = !muted
break
case 'fullscreen':
button.hidden = !document.fullscreenEnabled
button.setAttribute(
'aria-label',
document.fullscreenElement === root
? 'Exit fullscreen'
: 'Enter fullscreen',
)
break
case 'captions':
button.hidden = !captionTracks().length
button.setAttribute(
'aria-pressed',
String(
captionTracks().some(
(track) => track.mode === 'showing',
),
),
)
break
}
}
for (const timer of timers)
timer.textContent = `${formatVideoTime(state.currentTime)} / ${formatVideoTime(duration)}`
syncing = true
try {
for (const { element, slider, thumb, seek } of sliders) {
element.inert = seek && !duration
thumb.setAttribute('aria-disabled', String(seek && !duration))
if (!element.hasAttribute('data-dragging'))
slider.setValue(
seek
? duration
? (state.currentTime / duration) * 100
: 0
: muted
? 0
: state.volume * 100,
)
thumb.setAttribute(
'aria-valuetext',
seek
? `${formatVideoTime(state.currentTime)} of ${formatVideoTime(duration)}`
: `${Math.round(muted ? 0 : state.volume * 100)}%`,
)
}
} finally {
syncing = false
}
}
const suspend = () => {
request++
adapter?.pause()
update()
}
const pause = () => {
wantsPlayback = false
suspend()
}
const play = async () => {
if (!adapter || signal.aborted || failed) return
wantsPlayback = true
if (!canPlay()) return
const active = adapter
const ticket = ++request
if (error) error.hidden = true
pendingPlay++
try {
await active.play()
if (signal.aborted || !wantsPlayback || !canPlay()) active.pause()
} catch {
if (ticket === request) wantsPlayback = false
} finally {
pendingPlay--
}
update()
}
const notify = (event: VideoEvent) => {
if (signal.aborted) return
if (event === 'error') {
failed = true
wantsPlayback = false
root.dataset.state = 'error'
if (error) {
error.textContent = 'The video could not load.'
error.hidden = false
}
if (controls) controls.hidden = true
for (const button of buttons) button.hidden = true
if (native) native.controls = root.dataset.controls === 'true'
return
}
if (event === 'play') {
// A pending play can finish after a visibility or motion change.
if (!canPlay() || (pendingPlay > 0 && !wantsPlayback)) {
adapter?.pause()
return
}
wantsPlayback = true
}
if (
(event === 'pause' && canPlay()) ||
event === 'ended' ||
event === 'blocked'
)
wantsPlayback = false
update()
}
for (const button of buttons) {
button.addEventListener(
'click',
() => {
if (!adapter || failed) return
const state = adapter.read()
switch (button.dataset.videoAction) {
case 'start':
if (state.paused && !wantsPlayback) void play()
break
case 'play':
if (wantsPlayback || !state.paused) pause()
else void play()
break
case 'mute':
if (state.volume === 0) adapter.volume(1)
adapter.mute(!(state.muted || state.volume === 0))
update()
break
case 'fullscreen': {
const action =
document.fullscreenElement === root
? document.exitFullscreen()
: root.requestFullscreen()
void action.catch(() => {})
break
}
case 'captions': {
const tracks = captionTracks()
const showing = tracks.findIndex(
(track) => track.mode === 'showing',
)
tracks.forEach((track, index) => {
track.mode =
index === showing + 1 ? 'showing' : 'disabled'
})
update()
}
}
},
{ signal },
)
}
const syncVisibility = () => {
if (signal.aborted) return
if (!canPlay()) suspend()
else if (wantsPlayback) void play()
}
const observer =
pauseWhenHidden && typeof IntersectionObserver !== 'undefined'
? new IntersectionObserver(([entry]) => {
visible = Boolean(entry?.isIntersecting)
syncVisibility()
})
: undefined
observer?.observe(root)
if (pauseWhenHidden)
document.addEventListener('visibilitychange', syncVisibility, {
signal,
})
document.addEventListener('fullscreenchange', update, { signal })
reduced.addEventListener(
'change',
() => {
if (reduced.matches) pause()
},
{ signal },
)
native?.textTracks.addEventListener('addtrack', update, { signal })
native?.textTracks.addEventListener('change', update, { signal })
const ready = (value: VideoAdapter) => {
if (signal.aborted) {
value.destroy()
return
}
adapter = value
if (native) native.controls = false
if (controls) controls.hidden = false
for (const button of buttons) button.hidden = false
update()
if (wantsPlayback) void play()
}
if (native) {
native.muted = root.dataset.muted === 'true'
ready(nativeVideo(native, signal, notify))
} else {
void youtubeVideo(media as HTMLIFrameElement, root, signal, notify)
.then(ready)
.catch(() => {
if (signal.aborted) return
// The iframe retains its own controls when the API is unavailable.
root.dataset.state = 'unavailable'
})
}
return () => {
wantsPlayback = false
request++
observer?.disconnect()
adapter?.destroy()
for (const { slider } of sliders) slider.destroy()
for (const button of buttons) button.hidden = true
for (const restore of restoreControls) restore()
if (controls) controls.hidden = true
if (native) native.controls = root.dataset.controls === 'true'
delete root.dataset.state
}
}
src/components/ui/video/video-controls.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import { Button } from "../button/index.ts"
import { Slider } from "../slider/index.ts"
import VideoToggle from "./video-toggle.astro"
import PlayIcon from "@lucide/astro/icons/play"
import PauseIcon from "@lucide/astro/icons/pause"
import Volume2Icon from "@lucide/astro/icons/volume-2"
import VolumeXIcon from "@lucide/astro/icons/volume-x"
import MaximizeIcon from "@lucide/astro/icons/maximize"
import CaptionsIcon from "@lucide/astro/icons/captions"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
<div
{...props}
data-slot="video-controls"
class={cn(
"flex flex-col gap-2 border-t border-border bg-background p-3 text-foreground [[hidden]]:hidden",
className,
)}
hidden
>
<Slider data-video-seek defaultValue={0} min={0} max={100} step={0.1} />
<div class="flex flex-wrap items-center gap-2">
<VideoToggle variant="ghost" size="icon-sm">
<PlayIcon slot="play" class="size-4" aria-hidden="true" />
<PauseIcon slot="pause" class="size-4" aria-hidden="true" />
</VideoToggle>
<Button
variant="ghost"
size="icon-sm"
data-video-action="mute"
aria-label="Mute"
>
<span data-video-audible class="[[hidden]]:hidden">
<Volume2Icon class="size-4" aria-hidden="true" />
</span>
<span data-video-muted hidden class="[[hidden]]:hidden">
<VolumeXIcon class="size-4" aria-hidden="true" />
</span>
</Button>
<div class="w-20">
<Slider
data-video-volume
class="[&_[data-slot=slider-control][data-orientation=horizontal]]:min-w-0"
defaultValue={100}
min={0}
max={100}
step={1}
/>
</div>
<span data-video-time class="text-xs tabular-nums text-muted-foreground">
0:00 / 0:00
</span>
<div class="ml-auto flex items-center gap-1">
<Button
variant="ghost"
size="icon-sm"
data-video-action="captions"
aria-label="Captions"
aria-pressed="false"
class="[[hidden]]:hidden"
hidden
>
<CaptionsIcon aria-hidden="true" />
</Button>
<Button
variant="ghost"
size="icon-sm"
data-video-action="fullscreen"
aria-label="Enter fullscreen"
class="[[hidden]]:hidden"
hidden
>
<MaximizeIcon aria-hidden="true" />
</Button>
</div>
</div>
</div>
src/components/ui/video/video-native.ts
import type { VideoAdapter, VideoNotify } from './video-adapter.ts'
export function nativeVideo(
video: HTMLVideoElement,
signal: AbortSignal,
notify: VideoNotify,
): VideoAdapter {
let waiting = false
for (const event of ['play', 'pause', 'ended'] as const)
video.addEventListener(event, () => notify(event), { signal })
for (const event of [
'loadedmetadata',
'durationchange',
'timeupdate',
'volumechange',
'seeked',
'canplay',
'playing',
'waiting',
])
video.addEventListener(
event,
() => {
if (event === 'waiting') waiting = true
if (['canplay', 'playing', 'seeked'].includes(event))
waiting = false
notify('update')
},
{ signal },
)
video.addEventListener('error', () => notify('error'), { signal })
return {
read: () => ({
paused: video.paused,
ended: video.ended,
waiting,
currentTime: video.currentTime,
duration: video.duration,
muted: video.muted,
volume: video.volume,
}),
play: () => {
if (!video.getAttribute('src') && video.dataset.src)
video.src = video.dataset.src
return video.play()
},
pause: () => video.pause(),
seek: (seconds) => {
video.currentTime = seconds
},
mute: (value) => {
video.muted = value
},
volume: (value) => {
video.volume = value
},
destroy: () => {
video.pause()
},
}
}
src/components/ui/video/video-source.ts
export type VideoSource =
| { provider: 'native'; src: string }
| { provider: 'youtube'; id: string; start: number; portrait: boolean }
/** Detect known YouTube hosts. File extensions are not required for native media. */
export function resolveVideoSource(src: string): VideoSource {
if (!src?.trim()) throw new TypeError('Video requires a source.')
let url: URL
try {
url = new URL(src, 'https://video.invalid')
} catch {
throw new TypeError('Video requires a valid media URL.')
}
if (!['https:', 'http:', 'blob:', 'data:'].includes(url.protocol))
throw new TypeError('Unsupported video URL protocol.')
const host = url.hostname.replace(/^(www\.|m\.)/, '')
if (!['youtube.com', 'youtube-nocookie.com', 'youtu.be'].includes(host))
return { provider: 'native', src }
const parts = url.pathname.split('/').filter(Boolean)
const id =
host === 'youtu.be'
? parts[0]
: parts[0] === 'watch'
? url.searchParams.get('v')
: ['embed', 'shorts', 'live'].includes(parts[0] ?? '')
? parts[1]
: undefined
if (!id || !/^[\w-]{11}$/.test(id))
throw new TypeError(
'Video requires a YouTube video URL with a valid video ID.',
)
const time =
url.searchParams.get('start') ?? url.searchParams.get('t') ?? ''
const match = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/.exec(time)
const start = /^\d+$/.test(time)
? Number(time)
: match
? Number(match[1] ?? 0) * 3600 +
Number(match[2] ?? 0) * 60 +
Number(match[3] ?? 0)
: 0
return { provider: 'youtube', id, start, portrait: parts[0] === 'shorts' }
}
/** Native controls remain available if JavaScript or the API cannot load. */
export function youtubeEmbedUrl(
source: Extract<VideoSource, { provider: 'youtube' }>,
controls: boolean,
) {
const url = new URL(`https://www.youtube-nocookie.com/embed/${source.id}`)
url.searchParams.set('enablejsapi', '1')
url.searchParams.set('playsinline', '1')
url.searchParams.set('controls', controls ? '1' : '0')
if (source.start) url.searchParams.set('start', String(source.start))
return url.href
}
src/components/ui/video/video-toggle.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import { Button } from "../button/index.ts"
import type { ButtonProps } from "../button/types.ts"
import type { VideoToggleProps } from "./types.ts"
type Props = HTMLAttributes<"button"> &
Omit<ButtonProps, "as"> &
VideoToggleProps
const {
class: className,
for: target,
playLabel = "Play",
pauseLabel = "Pause",
...props
} = Astro.props
---
<Button
{...props}
as="button"
type="button"
data-video-action="play"
data-video-for={target}
data-play-label={playLabel}
data-pause-label={pauseLabel}
aria-label={playLabel}
class={cn("[[hidden]]:hidden", className)}
hidden
>
<span data-video-play class="[[hidden]]:hidden">
<slot name="play">{playLabel}</slot>
</span>
<span data-video-pause hidden class="[[hidden]]:hidden">
<slot name="pause">{pauseLabel}</slot>
</span>
</Button>
src/components/ui/video/video-youtube.ts
import type { VideoAdapter, VideoNotify } from './video-adapter.ts'
interface YoutubePlayer {
playVideo(): void
pauseVideo(): void
seekTo(seconds: number, allowSeekAhead: boolean): void
mute(): void
unMute(): void
isMuted(): boolean
setVolume(value: number): void
getVolume(): number
getCurrentTime(): number
getDuration(): number
getPlayerState(): number
destroy(): void
}
interface YoutubeAPI {
Player: new (
frame: HTMLIFrameElement,
options: {
events: {
onReady(): void
onStateChange(event: { data: number }): void
onError(): void
onAutoplayBlocked(): void
}
},
) => YoutubePlayer
}
type YoutubeWindow = Window & {
YT?: YoutubeAPI
onYouTubeIframeAPIReady?: () => void
}
let apiPromise: Promise<YoutubeAPI> | undefined
/** Share one API request across players, without replacing an existing ready callback. */
export function loadYoutubeAPI(): Promise<YoutubeAPI> {
const scope = window as YoutubeWindow
if (scope.YT?.Player) return Promise.resolve(scope.YT)
if (apiPromise) return apiPromise
apiPromise = new Promise<YoutubeAPI>((resolve, reject) => {
const previous = scope.onYouTubeIframeAPIReady
const script = document.createElement('script')
let timeout: ReturnType<typeof setTimeout>
const cleanup = () => {
clearTimeout(timeout)
if (scope.onYouTubeIframeAPIReady === ready) {
if (previous) scope.onYouTubeIframeAPIReady = previous
else delete scope.onYouTubeIframeAPIReady
}
script.onerror = null
}
const fail = () => {
cleanup()
script.remove()
reject(new Error('The YouTube API could not load.'))
}
const ready = () => {
try {
previous?.()
} finally {
if (scope.YT?.Player) {
cleanup()
resolve(scope.YT)
} else fail()
}
}
scope.onYouTubeIframeAPIReady = ready
script.src = 'https://www.youtube.com/iframe_api'
script.async = true
script.onerror = fail
timeout = setTimeout(fail, 15000)
document.head.append(script)
}).catch((error) => {
apiPromise = undefined
throw error
})
return apiPromise
}
/** Bind an existing iframe and restore its native controls if setup fails. */
export async function youtubeVideo(
frame: HTMLIFrameElement,
root: HTMLElement,
signal: AbortSignal,
notify: VideoNotify,
): Promise<VideoAdapter> {
const api = await loadYoutubeAPI()
signal.throwIfAborted()
const fallback = frame.cloneNode(true) as HTMLIFrameElement
const parent = frame.parentElement!
const url = new URL(frame.src)
url.searchParams.set('origin', window.location.origin)
url.searchParams.set('controls', '0')
url.searchParams.set(
'playsinline',
root.dataset.playsinline === 'false' ? '0' : '1',
)
if (root.dataset.loop === 'true') {
url.searchParams.set('loop', '1')
url.searchParams.set('playlist', url.pathname.split('/').pop()!)
}
frame.src = url.href
let player: YoutubePlayer | undefined
let stopped = false
let ready = false
let polling: ReturnType<typeof setInterval> | undefined
let timeout: ReturnType<typeof setTimeout> | undefined
const destroy = () => {
if (stopped) return
stopped = true
clearInterval(polling)
clearTimeout(timeout)
player?.destroy()
frame.remove()
parent.prepend(fallback)
}
return new Promise<VideoAdapter>((resolve, reject) => {
const abort = () => {
destroy()
reject(signal.reason)
}
signal.addEventListener('abort', abort, { once: true })
const fail = () => {
if (stopped) return
notify('error')
destroy()
signal.removeEventListener('abort', abort)
reject(new Error('The YouTube player could not load.'))
}
timeout = setTimeout(fail, 15000)
try {
player = new api.Player(frame, {
events: {
onReady: () => {
if (stopped || signal.aborted || !player) return
ready = true
clearTimeout(timeout)
root.dataset.muted === 'true'
? player.mute()
: player.unMute()
polling = setInterval(() => notify('update'), 250)
resolve({
read: () => {
const state = player!.getPlayerState()
return {
paused: ![1, 3].includes(state),
ended: state === 0,
waiting: state === 3,
currentTime: player!.getCurrentTime(),
duration: player!.getDuration(),
muted: player!.isMuted(),
volume: player!.getVolume() / 100,
}
},
play: () => player!.playVideo(),
pause: () => player!.pauseVideo(),
seek: (seconds) => player!.seekTo(seconds, true),
mute: (value) => {
value ? player!.mute() : player!.unMute()
},
volume: (value) => player!.setVolume(value * 100),
destroy: () => {
signal.removeEventListener('abort', abort)
destroy()
},
})
},
onStateChange: ({ data }) => {
if (!stopped && ready)
notify(
data === 1
? 'play'
: data === 2
? 'pause'
: data === 0
? 'ended'
: 'update',
)
},
onError: fail,
onAutoplayBlocked: () => {
if (!stopped) notify('blocked')
},
},
})
} catch {
fail()
}
})
}
src/components/ui/video/video.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import CirclePlayIcon from "@lucide/astro/icons/circle-play"
import { Button } from "../button/index.ts"
import VideoControls from "./video-controls.astro"
import { resolveVideoSource, youtubeEmbedUrl } from "./video-source.ts"
import type { VideoProps } from "./types.ts"
import { IconFrame } from "../icon"
import { PlayIcon } from "@lucide/astro"
/** Native media attributes pass to the video. Class, style, and ID belong to the player. */
type Props = Omit<HTMLAttributes<"video">, "src"> &
VideoProps & {
src: string
controls?: boolean
autoplay?: boolean
muted?: boolean
loop?: boolean
playsinline?: boolean
}
const {
class: className,
style,
id,
src,
mediaClass,
title = "Video",
controls = true,
autoplay = false,
muted = false,
loop = false,
playsinline = true,
preload = "metadata",
poster,
playOverlay = Astro.slots.has("play-overlay"),
pauseWhenHidden = false,
decorative = false,
...props
} = Astro.props
const source = resolveVideoSource(src)
const portrait = source.provider === "youtube" && source.portrait
---
<div
id={id}
style={style}
data-slot="video"
data-provider={source.provider}
data-autoplay={String(autoplay)}
data-muted={String(muted)}
data-loop={String(loop)}
data-playsinline={String(playsinline)}
data-controls={String(controls)}
data-started={playOverlay ? "false" : undefined}
data-pause-when-hidden={pauseWhenHidden || undefined}
class={cn(
"bg-muted w-full rounded-lg border relative block overflow-hidden [&:fullscreen]:flex [&:fullscreen]:flex-col [&:fullscreen]:rounded-none [&:fullscreen>[data-slot=video-frame]]:min-h-0 [&:fullscreen>[data-slot=video-frame]]:flex-1 @container/video",
playOverlay && "group/video",
!controls && "border-0 rounded-none bg-transparent",
portrait && "max-w-xs",
className,
)}
>
<div
data-slot="video-frame"
class={cn(
"relative",
controls ? (portrait ? "aspect-9/16" : "aspect-video") : "size-full",
)}
>
{source.provider === "youtube" ? (
<iframe
data-slot="video-media"
src={youtubeEmbedUrl(source, controls)}
title={title}
aria-hidden={decorative ? "true" : undefined}
tabindex={decorative ? -1 : undefined}
allow="autoplay; encrypted-media; fullscreen; picture-in-picture"
allowfullscreen
referrerpolicy="strict-origin-when-cross-origin"
class={cn("block size-full", mediaClass)}
/>
) : (
<video
{...props}
data-slot="video-media"
src={controls ? src : undefined}
data-src={src}
poster={poster}
controls={controls}
muted={muted}
loop={loop}
playsinline={playsinline}
preload={controls ? preload : "none"}
aria-label={props["aria-label"] ?? title}
aria-hidden={decorative ? "true" : props["aria-hidden"]}
tabindex={decorative ? -1 : props.tabindex}
class={cn(
"block size-full",
controls ? "object-contain" : "object-cover",
mediaClass,
)}
>
<slot />
</video>
)}
{playOverlay && (
<Button
as="button"
variant="ghost"
data-video-action="start"
aria-label={`Play ${title}`}
class="absolute inset-0 size-full rounded-none bg-black/30 p-0 text-white hover:bg-black/40 focus-visible:ring-inset sm:h-full group-data-[started=true]/video:hidden [[hidden]]:hidden"
hidden
>
<slot name="play-overlay">
<IconFrame variant="glass" class="size-16 rounded-full">
<PlayIcon class="size-8" aria-hidden="true" />
</IconFrame>
</slot>
</Button>
)}
</div>
<slot name="overlay" />
{controls && <VideoControls />}
<p
data-video-error
role="status"
class="absolute inset-x-0 top-0 bg-background p-3 text-sm text-foreground [[hidden]]:hidden"
hidden
></p>
</div>
<script>
import { create } from "./video-controller.ts"
const controllers: ReturnType<typeof create> = []
const initialize = () => controllers.push(...create())
initialize()
document.addEventListener("astro:page-load", initialize)
document.addEventListener("astro:before-swap", () => {
for (const controller of controllers) controller.destroy()
controllers.length = 0
})
</script>
Usage
Video detects YouTube watch, share, Shorts, live, and embed URLs. Other sources use a native video element, including local files and media URLs without a file extension.
---
import { Video } from "@/components/ui/video"
---
<Video src="/demo.mp4" poster="/demo.webp" title="Product demonstration" />
<Video src="https://www.youtube.com/watch?v=M7lc1UVf-VE" title="YouTube demonstration" />
Controls are enabled by default. The player uses Button and Slider for play/pause, mute, volume, playback position, and fullscreen. Both sources use the same controls. YouTube loads its IFrame Player API only when a YouTube player is present.
Poster play overlay
Set playOverlay to show a dark layer and a circle play icon over the media. The overlay starts playback. It disappears after playback starts and stays hidden on pause or completion. If playback is blocked, the overlay stays available for another attempt.
<Video src="/demo.mp4" poster="/demo.webp" playOverlay />
Use the play-overlay slot to replace the icon with your own text or artwork. The slot enables the overlay unless playOverlay={false} is set. Video supplies the button and its accessible label from title; do not put a button or link inside this slot.
<Video src="/demo.mp4" poster="/demo.webp" title="Product demonstration">
<span slot="play-overlay" class="rounded-full border px-6 py-3">
Play demonstration
</span>
</Video>
The overlay also works with YouTube and controls={false}. It appears when the player is ready. The root uses data-started="true" after first playback; CSS hides the overlay from that state. The separate overlay slot remains available for persistent content.
YouTube URLs
YouTube Shorts use a portrait frame. Start times in start or t are preserved. The player uses the youtube-nocookie.com embed host. YouTube still makes external requests and controls its own branding, overlays, and media availability.
Background playback
Set controls={false} to remove the control bar. Set autoplay, muted, and loop separately. Set decorative only when the video adds no information. Use the overlay slot for content or a separate play/pause button.
Autoplay respects reduced motion. Native background files load when playback is requested. Supply a poster for a static fallback. pauseWhenHidden pauses the player outside the viewport or in a hidden tab. It resumes only if playback was requested before the player became hidden. A manual pause remains in effect.
YouTube background playback uses the same options, but YouTube can still show its own overlays. poster applies to native files only.
Separate play/pause button
Place VideoToggle in the overlay slot, or set its for prop to the Video ID. It accepts Button variants and sizes. Named play and pause slots replace the button content.
The controller creates missing player and trigger IDs and sets aria-controls.
It preserves IDs you supply. A toggle inside Video needs no for prop. A detached
toggle needs a matching, unique Video ID. No preview-specific ID changes are required.
Captions
Pass native <track> elements through the default slot. A captions button appears when native caption or subtitle tracks are available. Repeated clicks select each track, then turn captions off. Choose YouTube videos with accurate captions; YouTube manages its caption settings, including its c keyboard shortcut when the iframe has focus.
<Video src="/demo.mp4" title="Product demonstration" crossorigin="anonymous">
<track kind="captions" src="/demo.en.vtt" srclang="en" label="English" default />
</Video>
Keyboard and fallback behavior
Buttons use normal keyboard activation. Sliders support arrow keys, Home, End, and Page Up/Down. The playback slider reports the current time and duration. Browser controls remain available until custom controls are ready. If the YouTube API cannot load, the iframe keeps its own controls.
API Reference
Migration from BackgroundVideo
Replace BackgroundVideo and BackgroundVideoMedia with one Video component. Replace BackgroundVideoToggle with VideoToggle. Set controls={false}, autoplay, muted, and loop explicitly for background playback. Use mediaClass for media positioning and the overlay slot for content above the video.
Native video attributes include src, poster, controls, autoplay, muted, loop, playsinline, preload, and crossorigin. controls and playsinline default to true; autoplay, mute, and loop default to false. Playback options also apply to YouTube where supported. Other native media attributes apply to native files only. class, style, and id apply to the player root. title labels the media. The root uses the selected preset.
playOverlay?boolean
Show a play overlay until playback starts. The play-overlay slot enables it unless this prop is false.
booleanfalsemediaClass?string
Classes for the video or iframe, such as object-cover or object-position.
stringpauseWhenHidden?boolean
Pause outside the viewport or in a hidden tab. A manual pause remains in effect.
booleanfalsedecorative?boolean
Hide decorative media from assistive technology. Does not change playback.
booleanfalsefor?string
ID of the Video to control. Omit when the button is inside the Video overlay slot.
stringplayLabel?string
Label and default text when paused.
string"Play"pauseLabel?string
Label and default text when playing.
string"Pause"Read the installed source for the complete component.
The player uses an HTML root and a factory. The component initializes on script
load and astro:page-load, then stops playback and destroys its controller before
an Astro page swap. For direct DOM changes, import createVideo from the component
index and call controller.destroy() before removing the player.