Video player
A video with its own controls: play, scrub, volume, speed, captions and fullscreen, all reachable from the keyboard, over a picture that clears when you stop touching it.
Goal
A player for a product tour, a lesson or a recorded talk where the browser's own controls do not match the page. The media is one video element; everything around it, the controls, the status and the keyboard, is the recipe's, and none of it needs a player library.
Primitives
- MediaController owns the playback state: the status, the position, the buffered ranges, whether it is waiting for data, blocked by the autoplay policy or in error, and the volume, the mute and the rate. It also seeks, either at once (
skip,seek) or after the reader has paused on the scrub bar (scrub), and it retries a failed load. The recipe never listens to a media event and never stores whether the video plays. - CaptionsController owns the captions: it adds the track from the cue data, shows and hides it, and keeps the cues above the controls. The recipe passes the video, the controls element to stay above and one English track, and keeps the button's
aria-pressedfrom the state it reports. - formatMediaTime writes the clock, and tolerates the
NaNduration the element reports before its metadata arrives. - cycleValue steps the speed button through 1x, 1.25x, 1.5x, 2x and 0.5x.
rui-slideris the scrub bar and the volume, and the buttons carry the Radiant button classes (rui-button,rui-button--ghost,rui-button--square), so the player follows the selected theme. The component form renders them with theRuiSliderandRuiButtonhelpers; the other forms write the slider's light-DOM contract by hand: a root, a track with its fill and onerole="slider"thumb, with the position seeded in the track's custom properties. The buffered ranges are adata-bufferedlayer inside the scrub track, behind the fill.
Left to the recipe: the keyboard shortcuts, hiding the controls, fullscreen, the states the stage shows (buffering, error with Retry, blocked autoplay), the live region and the accessible names, and loading the clip through a Blob.
Example
Press Play or click the video, drag the scrub bar, change the volume, cycle the speed and turn the captions on. Focus the player and use the keyboard: Space or K plays and pauses, J and L skip 10 seconds, the left and right arrows 5 seconds, the up and down arrows change the volume, M mutes, C toggles the captions, F toggles fullscreen, the digits 0 to 9 jump to that tenth of the video and Home and End go to the ends. While it plays, the controls hide after two and a half seconds without a pointer or key and return on any movement; double-click the video to enter fullscreen. The clip is a twelve second animation made for this page, with a running timecode so a seek is easy to check. It has a sound track of its own. It is played from memory, so the lighter layer behind the thumb, the buffered range, covers the whole clip as soon as it has loaded.
Pick an authoring pattern below; they all behave the same, and the one you pick is remembered on the other recipes.
The same behavior as a RadiantElement. The markup is authored inside <video-player-element> and the element finds its parts with @query; there is nothing to mount, clean up or run again.
Could not load the video
import { RadiantElement, bindTo, customElement, onEvent, query, state } from '@ecopages/radiant';
import { createCaptionsController, createMediaController, type MediaState } from '@ecopages/radiant-ui/controllers';
import '@ecopages/radiant-ui/slider';
import type { RuiSliderChangeDetail, RuiSliderElement } from '@ecopages/radiant-ui/slider';
import { cycleValue, formatMediaTime } from '@ecopages/radiant-ui/helpers';
import {
Announcer,
CAPTIONS,
HIDE_CONTROLS_MS,
RATES,
bufferedSegments,
seekFromKey,
seekValueText,
shortcutFor,
stageState,
type Shortcut,
type StageState,
} from './video-player.data';
import { fetchSource, releaseSource } from './video-player.loader';
/**
* @remarks
* What the page shows that is a plain copy of the media state (the stage state, whether the controls are hidden, the
* pressed buttons, the clock, the status, the speed, the error panel) is a `@state` field that `@bindTo` writes onto
* the markup; the buffered bar and the slider values are written here because they are not a copy
* of one value.
*
* `createMediaController(this, ...)` takes the element as its host and attaches and destroys with it, so the element
* listens to no media event. The timer and the thumb observer are stopped by a callback
* registered once in the constructor, because one registered in `onConnected()` would be added again on every
* reconnect, and `onConnected()` starts the load again when the element is moved. Each pointer listener is
* delegated on the host, and `pointerleave`, which does not bubble, is delegated in the capture phase.
*/
@customElement('video-player-element')
export class VideoPlayerElement extends RadiantElement {
@query({ selector: '[data-stage]' }) private stage!: HTMLElement;
@query({ selector: '[data-video]' }) private video!: HTMLVideoElement;
@query({ selector: '[data-controls]' }) private controls!: HTMLElement;
@query({ selector: '[data-seek]' }) private seek!: RuiSliderElement;
@query({ selector: '[data-seek] [role="slider"]' }) private seekThumb!: HTMLElement;
@query({ selector: '[data-volume-input]' }) private volume!: RuiSliderElement;
@query({ selector: '[data-buffered]' }) private buffered!: HTMLElement;
@query({ selector: '[data-fullscreen]' }) private fullscreen!: HTMLButtonElement;
@state
@bindTo({ selector: '[data-stage]', attr: 'data-state' })
stageState: StageState = 'idle';
@state
@bindTo({ selector: '[data-stage]', bool: 'data-controls-hidden' })
controlsHidden = false;
@state
@bindTo({ selector: '[data-playback]', attr: 'aria-pressed', map: (value) => String(value) })
playing = false;
@state
@bindTo({ selector: '[data-mute]', attr: 'aria-pressed', map: (value) => String(value) })
muted = false;
@state
@bindTo({ selector: '[data-captions]', attr: 'aria-pressed', map: (value) => String(value) })
captionsOn = false;
@state
@bindTo({ selector: '[data-fullscreen]', attr: 'aria-pressed', map: (value) => String(value) })
fullscreenOn = false;
@state
@bindTo([
{ selector: '[data-rate]', text: true, map: (rate) => `${rate}x` },
{ selector: '[data-rate]', attr: 'aria-label', map: (rate) => `Speed ${rate}x` },
])
rate = 1;
@state
@bindTo({ selector: '[data-elapsed]', text: true })
elapsed = '0:00';
@state
@bindTo({ selector: '[data-duration]', text: true })
total = '0:00';
@state
@bindTo({ selector: '[data-status]', text: true })
status = '';
@state
@bindTo({ selector: '[data-seek]', bool: 'disabled', invert: true })
seekable = false;
@state
@bindTo({ selector: '[data-error]', bool: 'hidden', invert: true })
failed = false;
private hideTimer: ReturnType<typeof setTimeout> | undefined;
private pointer = 'mouse';
private bufferedKey = '';
private valueText = '';
private readonly announcer = new Announcer();
private readonly valueTextObserver = new MutationObserver(() => this.keepValueText());
private readonly captions = createCaptionsController(this, {
getMedia: () => this.video,
getAvoid: () => this.controls,
tracks: [{ language: 'en', label: 'English', cues: CAPTIONS }],
onState: (state) => {
this.captionsOn = state.enabled;
},
});
private readonly media = createMediaController(this, {
getMedia: () => this.video,
resolveSource: fetchSource,
releaseSource,
clearSourceOnDestroy: true,
onState: (state) => this.renderState(state),
onProgress: (state) => this.renderProgress(state),
});
constructor() {
super();
this.registerCleanupCallback(() => {
clearTimeout(this.hideTimer);
this.valueTextObserver.disconnect();
});
}
override onConnected(): void {
this.valueTextObserver.observe(this.seekThumb, { attributes: true, attributeFilter: ['aria-valuetext'] });
this.fullscreen.hidden = !document.fullscreenEnabled;
this.captions.disable();
this.announcer.reset();
void this.media.load(this.video.dataset.src!);
}
/**
* Writes the clock, the seek thumb and the buffered bar.
*
* @remarks
* The slider repaints in a later update with its own `aria-valuetext`, a bare number of seconds, so the text is
* kept by the observer as well as written here.
*/
private renderProgress(state: MediaState): void {
if (Number.isFinite(state.duration) && this.seek.max !== state.duration) this.seek.max = state.duration;
this.seek.value = [state.position];
this.valueText = seekValueText(state.position, state.duration);
this.keepValueText();
this.elapsed = formatMediaTime(state.position);
this.total = formatMediaTime(state.duration);
const segments = bufferedSegments(state.bufferedRanges, state.duration);
const key = JSON.stringify(segments);
if (key !== this.bufferedKey) {
this.bufferedKey = key;
this.buffered.replaceChildren(
...segments.map(({ start, size }) => {
const segment = document.createElement('i');
segment.style.setProperty('--start', String(start));
segment.style.setProperty('--size', String(size));
return segment;
}),
);
}
}
private keepValueText(): void {
if (this.seekThumb.getAttribute('aria-valuetext') !== this.valueText) {
this.seekThumb.setAttribute('aria-valuetext', this.valueText);
}
}
private renderState(state: MediaState): void {
const shown = stageState(state);
const message = this.announcer.next(state);
this.stageState = shown;
this.playing = state.status === 'playing';
this.muted = state.muted;
this.volume.value = [state.muted ? 0 : state.volume];
this.rate = state.rate;
this.seekable = state.seekable;
this.failed = shown === 'error';
if (message !== '') this.status = message;
this.renderProgress(state);
this.wake();
}
/**
* Shows the controls and, while the video plays, hides them again after `HIDE_CONTROLS_MS` of quiet. They stay
* while the pointer is over them or a control has keyboard focus, so a reader who is aiming at one never loses it.
*/
private wake(): void {
clearTimeout(this.hideTimer);
this.controlsHidden = false;
if (this.stageState !== 'playing') return;
this.hideTimer = setTimeout(() => {
if (this.controls.matches(':hover') || this.controls.querySelector(':focus-visible')) return this.wake();
this.controlsHidden = true;
}, HIDE_CONTROLS_MS);
}
private toggleCaptions(): void {
this.captions.toggle();
this.status = this.captionsOn ? 'Captions on' : 'Captions off';
}
/**
* Both calls reject when the browser refuses (no user gesture, a sandboxed frame), and the player has nothing to
* show for it: the button only follows `fullscreenchange`.
*/
private toggleFullscreen(): void {
const request =
document.fullscreenElement === this.stage ? document.exitFullscreen() : this.stage.requestFullscreen();
request.catch(() => undefined);
}
private run(shortcut: Shortcut): void {
const state = this.media.getState();
switch (shortcut.type) {
case 'toggle':
return void this.media.toggle();
case 'skip':
return this.media.skip(shortcut.seconds);
case 'volume': {
const next = Math.round((state.volume + shortcut.delta) * 100) / 100;
if (shortcut.delta > 0 && state.muted) this.media.setMuted(false);
this.media.setVolume(next);
this.status = `Volume ${Math.round(this.media.getState().volume * 100)}%`;
return;
}
case 'mute':
return this.media.toggleMuted();
case 'captions':
return this.toggleCaptions();
case 'fullscreen':
return this.toggleFullscreen();
case 'jump':
return this.media.seek(state.duration * shortcut.fraction);
case 'start':
return this.media.seek(0);
case 'end':
return this.media.seek(state.duration);
}
}
@onEvent({ selector: '[data-stage]', type: 'keydown' })
shortcut(event: Event): void {
this.wake();
const shortcut = shortcutFor(event as KeyboardEvent);
if (!shortcut) return;
event.preventDefault();
this.run(shortcut);
}
/**
* A touch on the video is a tap that shows or hides the controls, which `tapVideo` decides, so it is not
* activity here.
*/
@onEvent({ selector: '[data-stage]', type: 'pointermove' })
@onEvent({ selector: '[data-stage]', type: 'pointerdown' })
@onEvent({ selector: '[data-stage]', type: 'pointerleave', options: { capture: true } })
activity(event: Event): void {
const { target, pointerType } = event as PointerEvent;
if (target !== this.video || pointerType !== 'touch') this.wake();
}
@onEvent({ selector: '[data-video]', type: 'pointerdown' })
rememberPointer(event: Event): void {
this.pointer = (event as PointerEvent).pointerType;
}
@onEvent({ selector: '[data-video]', type: 'click' })
tapVideo(): void {
if (this.pointer === 'touch' && this.stageState === 'playing') {
if (this.controlsHidden) this.wake();
else this.controlsHidden = true;
} else void this.media.toggle();
}
@onEvent({ selector: '[data-video]', type: 'dblclick' })
@onEvent({ selector: '[data-fullscreen]', type: 'click' })
enterFullscreen(): void {
this.toggleFullscreen();
}
@onEvent({ selector: '[data-big-play]', type: 'click' })
@onEvent({ selector: '[data-playback]', type: 'click' })
togglePlayback(): void {
void this.media.toggle();
}
@onEvent({ selector: '[data-mute]', type: 'click' })
toggleMute(): void {
this.media.toggleMuted();
}
@onEvent({ selector: '[data-rate]', type: 'click' })
cycleRate(): void {
this.media.setRate(Number(cycleValue(RATES, String(this.media.getState().rate))));
this.status = `Speed ${this.media.getState().rate}x`;
}
@onEvent({ selector: '[data-captions]', type: 'click' })
pressCaptions(): void {
this.toggleCaptions();
}
@onEvent({ selector: '[data-retry]', type: 'click' })
retry(): void {
void this.media.retry();
}
@onEvent({ document: true, type: 'fullscreenchange' })
followFullscreen(): void {
this.fullscreenOn = document.fullscreenElement === this.stage;
}
/** The slider works in seconds and reports `rui-change` only for the reader, never for a position written to it. */
@onEvent({ selector: '[data-seek]', type: 'rui-change' })
scrub(event: Event): void {
this.media.scrub((event as CustomEvent<RuiSliderChangeDetail>).detail.value[0]);
}
/**
* Delegated in the capture phase, which runs before the slider's own key handler and lets this stop it for the
* keys the player moves by whole seconds, so the slider's 0.01 s step never applies to an arrow key. Home and
* End are left to the slider.
*/
@onEvent({ selector: '[data-seek]', type: 'keydown', options: { capture: true } })
scrubWithKey(event: Event): void {
const key = event as KeyboardEvent;
const seconds = seekFromKey(key.key);
if (seconds === undefined) return;
key.preventDefault();
key.stopPropagation();
this.wake();
this.media.skip(seconds);
}
@onEvent({ selector: '[data-volume-input]', type: 'rui-change' })
setVolume(event: Event): void {
const level = (event as CustomEvent<RuiSliderChangeDetail>).detail.value[0];
this.media.setVolume(level);
if (level > 0) this.media.setMuted(false);
}
}import type { MediaState } from '@ecopages/radiant-ui/controllers';
import { formatMediaTime } from '@ecopages/radiant-ui/helpers';
/** The sample clip and its poster, made by `scripts/generate-video-player-assets.mjs`. */
export const VIDEO = {
src: '/assets/video/radiant-reel.webm',
poster: '/assets/video/radiant-reel.jpg',
} as const;
/** The English captions of the clip, one for each of its five scenes, in seconds. */
export const CAPTIONS: readonly { start: number; end: number; text: string }[] = [
{ start: 0.2, end: 2.3, text: 'Scene one: a slow start' },
{ start: 2.6, end: 4.7, text: 'Scene two: the shapes arrive' },
{ start: 5, end: 7.1, text: 'Scene three: everything turns' },
{ start: 7.4, end: 9.5, text: 'Scene four: the light moves on' },
{ start: 9.8, end: 11.9, text: 'Scene five: and it settles' },
];
/**
* The playback rates the speed button cycles through, as the strings `cycleValue` works on, and the value the
* button shows with an `x`.
*/
export const RATES: readonly string[] = ['1', '1.25', '1.5', '2', '0.5'];
/** Seconds the arrow keys move the playback by, on the seek thumb and on the player. */
export const SEEK_STEP = 5;
/** Seconds `J`, `L`, Page Up and Page Down move the playback by. */
export const LONG_SEEK_STEP = 10;
/** The fraction of the full volume the arrow keys change it by. */
export const VOLUME_STEP = 0.1;
/** Milliseconds without a pointer or key event after which the controls hide while the video plays. */
export const HIDE_CONTROLS_MS = 2500;
/** What the stage shows: `data-state` on `[data-stage]` carries one of these and the stylesheet draws from it. */
export type StageState = 'idle' | 'buffering' | 'playing' | 'paused' | 'error';
/** What a shortcut asks the player to do. */
export type Shortcut =
| { type: 'toggle' }
| { type: 'skip'; seconds: number }
| { type: 'volume'; delta: number }
| { type: 'mute' }
| { type: 'captions' }
| { type: 'fullscreen' }
| { type: 'jump'; fraction: number }
| { type: 'start' }
| { type: 'end' };
const SHORTCUTS = new Map<string, Shortcut>([
[' ', { type: 'toggle' }],
['k', { type: 'toggle' }],
['j', { type: 'skip', seconds: -LONG_SEEK_STEP }],
['l', { type: 'skip', seconds: LONG_SEEK_STEP }],
['ArrowLeft', { type: 'skip', seconds: -SEEK_STEP }],
['ArrowRight', { type: 'skip', seconds: SEEK_STEP }],
['ArrowUp', { type: 'volume', delta: VOLUME_STEP }],
['ArrowDown', { type: 'volume', delta: -VOLUME_STEP }],
['m', { type: 'mute' }],
['c', { type: 'captions' }],
['f', { type: 'fullscreen' }],
['Home', { type: 'start' }],
['End', { type: 'end' }],
...Array.from({ length: 10 }, (_, digit): [string, Shortcut] => [
String(digit),
{ type: 'jump', fraction: digit / 10 },
]),
]);
const SLIDER_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'PageUp', 'PageDown']);
/**
* The shortcut a key event asks for, or `undefined` when the player must leave it alone.
*
* @remarks
* A key that carries Ctrl, Alt or Meta belongs to the browser. A button owns Space and Enter, which activate it. A
* slider thumb owns the arrows, Home, End and the page keys, which move it; the letters and digits still reach the
* player. The target is the element the key was pressed on, which a `keydown` listener on the stage always has.
*/
export function shortcutFor(
event: Pick<KeyboardEvent, 'key' | 'ctrlKey' | 'altKey' | 'metaKey' | 'target'>,
): Shortcut | undefined {
if (event.ctrlKey || event.altKey || event.metaKey) return undefined;
const target = event.target as Element;
if (target.closest('button') && (event.key === ' ' || event.key === 'Enter')) return undefined;
if (target.closest('[role="slider"]') && SLIDER_KEYS.has(event.key)) return undefined;
return SHORTCUTS.get(event.key.length === 1 ? event.key.toLowerCase() : event.key);
}
const SEEK_KEYS = new Map([
['ArrowRight', SEEK_STEP],
['ArrowUp', SEEK_STEP],
['ArrowLeft', -SEEK_STEP],
['ArrowDown', -SEEK_STEP],
['PageUp', LONG_SEEK_STEP],
['PageDown', -LONG_SEEK_STEP],
]);
/**
* Seconds a key moves the seek slider by, or `undefined` for any other key.
*
* @remarks
* The slider works in seconds with a step of 0.01, fine enough that the per-frame position write is not rounded and
* the thumb glides. A step that fine would make an arrow key inaudible, so the player handles these keys and the
* slider keeps Home and End.
*/
export function seekFromKey(key: string): number | undefined {
return SEEK_KEYS.get(key);
}
/** The state of the stage for a snapshot of the media element. */
export function stageState(state: Pick<MediaState, 'status' | 'waiting' | 'error'>): StageState {
if (state.error) return 'error';
if (state.waiting || state.status === 'loading') return 'buffering';
if (state.status === 'idle') return 'idle';
return state.status === 'playing' ? 'playing' : 'paused';
}
/** The text a snapshot is worth in the polite live region, `''` while there is nothing to say. */
export function statusMessage(state: Pick<MediaState, 'status' | 'waiting' | 'error' | 'blocked'>): string {
if (state.blocked) return 'Playback was blocked, press Play to start';
switch (stageState(state)) {
case 'error':
return 'Could not load the video';
case 'buffering':
return 'Buffering';
case 'playing':
return 'Playing';
case 'paused':
return state.status === 'ended' ? 'Ended' : 'Paused';
default:
return '';
}
}
/**
* Decides what the polite live region says.
*
* @remarks
* The player says nothing while the clip loads on its own: "Buffering" and "Paused" at page load, or after the
* player was moved, are noise to a reader who has done nothing yet. It starts to report once the clip has played,
* and a failure ("Could not load", "Playback was blocked") is always reported, because it answers an action or
* leaves the player unusable. A message is said once until it changes.
*/
export class Announcer {
private spoken = '';
private started = false;
/** Forgets what was said and silences the player again, for a clip that loads from the start. */
reset(): void {
this.spoken = '';
this.started = false;
}
/** The message to say for this snapshot, or `''` when there is nothing new to say. */
next(state: Pick<MediaState, 'status' | 'waiting' | 'error' | 'blocked'>): string {
if (state.status === 'playing') this.started = true;
const message = this.started || state.error || state.blocked ? statusMessage(state) : '';
if (message === this.spoken) return '';
this.spoken = message;
return message;
}
}
/** The `aria-valuetext` of the seek thumb, such as `1:15 of 4:00`. */
export function seekValueText(position: number, duration: number): string {
return `${formatMediaTime(position)} of ${formatMediaTime(duration)}`;
}
/** One buffered range as the percentages the stylesheet draws it with. */
export type BufferedSegment = { start: number; size: number };
/** The buffered ranges as percentages of the duration, empty until the duration is known. */
export function bufferedSegments(ranges: readonly (readonly [number, number])[], duration: number): BufferedSegment[] {
if (!Number.isFinite(duration) || duration <= 0) return [];
return ranges.map(([from, to]) => ({
start: (from / duration) * 100,
size: ((Math.min(to, duration) - from) / duration) * 100,
}));
}const inFlight = new Map<string, Promise<Blob>>();
function download(url: string): Promise<Blob> {
let pending = inFlight.get(url);
if (!pending) {
pending = fetchBlob(url).finally(() => inFlight.delete(url));
inFlight.set(url, pending);
}
return pending;
}
async function fetchBlob(url: string): Promise<Blob> {
const response = await fetch(url);
if (!response.ok) throw new Error(`${response.status} ${response.statusText} for ${url}`);
return response.blob();
}
/**
* Fetches a video into a `Blob` and returns an object URL, for `MediaController`'s `resolveSource`.
*
* @remarks
* A media element can only seek in a file whose server answers range requests, and many development and preview
* servers (this site's among them) do not: the element then reports nothing seekable and every seek snaps back to
* the start. The sample clip is about a megabyte, so it is fetched whole and played from memory, which always
* seeks. For long media serve the file with range support and pass its URL to `load()` without a `resolveSource`.
* A failed request rejects, which puts the controller in its `error` state; `retry()` calls this again.
*
* Requests for a url that is still downloading share one download, and each caller gets an object URL of its own.
* The page swaps the authoring pattern of a recipe by mounting the new form as soon as the old one is on the page,
* which would otherwise fetch the clip twice, and a shared object URL would be revoked under the form that is left
* running when the other releases it. A finished download is not kept, so a retry or a player that is moved asks the
* server again.
*/
export async function fetchSource(url: string): Promise<string> {
return URL.createObjectURL(await download(url));
}
/** Frees an object URL `fetchSource` made; `MediaController` calls it as `releaseSource` once the element has let go of it. */
export function releaseSource(url: string): void {
URL.revokeObjectURL(url);
}<video-player-element>
<div
data-stage
data-state="idle"
role="group"
aria-label="Video player"
aria-describedby="video-player-element-help"
tabindex="0"
>
<video
data-video
data-src="/assets/video/radiant-reel.webm"
poster="/assets/video/radiant-reel.jpg"
preload="metadata"
playsinline
></video>
<button
type="button"
class="rui-button rui-button--filled rui-button--lg rui-button--square"
data-big-play
aria-hidden="true"
tabindex="-1"
>
<svg viewBox="0 0 24 24" width="28" height="28" aria-hidden="true" focusable="false">
<path d="M8 5v14l11-7z" fill="currentColor" />
</svg>
</button>
<span data-spinner aria-hidden="true"></span>
<div data-error hidden>
<p data-error-message>Could not load the video</p>
<button type="button" class="rui-button rui-button--filled rui-button--sm" data-retry>Retry</button>
</div>
<div data-controls>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-playback
aria-label="Play"
aria-pressed="false"
>
<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="play">
<path d="M8 5v14l11-7z" fill="currentColor" /></svg
><svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="pause">
<path d="M6 5h4v14H6zM14 5h4v14h-4z" fill="currentColor" />
</svg>
</button>
<div data-scrub>
<span data-elapsed>0:00</span>
<rui-slider data-seek step="0.01" label="Seek" min="0" max="1" value="0" disabled>
<div class="rui-slider rui-slider--single" data-ref="root">
<div class="rui-slider__range">
<div
class="rui-slider__range-track"
data-ref="rangeTrack"
style="--rui-slider-fill-start: 0%; --rui-slider-fill-size: 0%; --rui-slider-value: 0%"
>
<div data-buffered aria-hidden="true"></div>
<div class="rui-slider__range-fill" data-ref="rangeFill"></div>
<button
type="button"
class="rui-slider__thumb"
data-ref="singleThumb"
data-thumb="value"
role="slider"
aria-label="Seek"
></button>
</div>
</div>
</div>
</rui-slider>
<span data-duration>0:00</span>
</div>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-mute
aria-label="Mute"
aria-pressed="false"
>
<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="volume">
<path d="M4 9v6h4l5 4V5L8 9z" fill="currentColor" />
<path
d="M16 9a4 4 0 0 1 0 6"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/></svg
><svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="muted">
<path d="M4 9v6h4l5 4V5L8 9z" fill="currentColor" />
<path
d="M16.5 9.5l5 5M21.5 9.5l-5 5"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</button>
<div data-volume>
<rui-slider data-volume-input step="0.05" label="Volume" min="0" max="1" value="1">
<div class="rui-slider rui-slider--single" data-ref="root">
<div class="rui-slider__range">
<div
class="rui-slider__range-track"
data-ref="rangeTrack"
style="
--rui-slider-fill-start: 0%;
--rui-slider-fill-size: 100%;
--rui-slider-value: 100%;
"
>
<div class="rui-slider__range-fill" data-ref="rangeFill"></div>
<button
type="button"
class="rui-slider__thumb"
data-ref="singleThumb"
data-thumb="value"
role="slider"
aria-label="Volume"
></button>
</div>
</div>
</div>
</rui-slider>
</div>
<button type="button" class="rui-button rui-button--ghost rui-button--md" data-rate aria-label="Speed 1x">
1x
</button>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-captions
aria-label="Captions"
aria-pressed="false"
>
<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false">
<rect
x="3"
y="5"
width="18"
height="14"
rx="2"
fill="none"
stroke="currentColor"
stroke-width="2"
/>
<path
d="M10.5 10.5a2 2 0 1 0 0 3M17 10.5a2 2 0 1 0 0 3"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</button>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-fullscreen
aria-label="Fullscreen"
aria-pressed="false"
>
<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="enter">
<path
d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/></svg
><svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="exit">
<path
d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</button>
</div>
<p data-status aria-live="polite"></p>
</div>
<span data-help hidden id="video-player-element-help"
>Space or K plays and pauses, J and L skip 10 seconds, the arrows seek 5 seconds or change the volume, M mutes,
C toggles captions, F toggles fullscreen, 0 to 9 jump through the video, Home and End go to its start and
end</span
>
</video-player-element>.primitive-example:is(
[data-example='video-player'],
:has(> video-player-element, > [data-controller='video-player'], > video-player-app)
) {
display: block;
width: min(100%, 44rem);
& :where([data-stage]) {
position: relative;
overflow: hidden;
box-sizing: border-box;
aspect-ratio: 16 / 9;
border-radius: var(--radius-container);
background: #000;
color: #fff;
box-shadow: var(--shadow-overlay);
container-type: inline-size;
user-select: none;
}
& :where([data-stage]:focus-visible) {
outline: 2px solid var(--focus-ring);
outline-offset: 2px;
}
& :where([data-stage]:fullscreen) {
aspect-ratio: auto;
inline-size: 100%;
block-size: 100%;
border-radius: 0;
}
& :where([data-stage]:fullscreen:focus-visible) {
outline-offset: -4px;
}
/* The ring is drawn over the picture, so it is white, which stands out from the dark bar and the error panel. */
& :where([data-controls], [data-error]) {
--focus-ring: #fff;
}
& :where([data-stage][data-controls-hidden][data-state='playing']) {
cursor: none;
}
& :where([data-video]) {
display: block;
inline-size: 100%;
block-size: 100%;
object-fit: contain;
cursor: pointer;
}
& :where([data-big-play]) {
position: absolute;
inset: 50% auto auto 50%;
translate: -50% -50%;
inline-size: calc(var(--size-control-lg) * 1.75);
block-size: calc(var(--size-control-lg) * 1.75);
border-radius: var(--radius-full);
box-shadow: var(--shadow-overlay);
opacity: 0;
pointer-events: none;
transition-property: opacity, scale;
transition-duration: var(--duration-normal);
transition-timing-function: var(--ease-out-strong);
scale: 0.9;
}
& :where([data-stage]:is([data-state='paused'], [data-state='idle']) [data-big-play]) {
opacity: 1;
pointer-events: auto;
scale: 1;
}
& :where([data-stage][data-state='idle'] [data-big-play]) {
opacity: 0.6;
}
& :where([data-spinner]) {
position: absolute;
inset: 50% auto auto 50%;
translate: -50% -50%;
box-sizing: border-box;
inline-size: calc(var(--size-control-lg) * 1.1);
block-size: calc(var(--size-control-lg) * 1.1);
border: 3px solid rgb(255 255 255 / 0.3);
border-block-start-color: #fff;
border-radius: var(--radius-full);
opacity: 0;
pointer-events: none;
transition: opacity var(--duration-normal) var(--ease-out-strong);
}
& :where([data-stage][data-state='buffering'] [data-spinner]) {
opacity: 1;
animation: video-player-spin 0.9s linear infinite;
}
& :where([data-error]:not([hidden])) {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: var(--space-4);
padding: var(--space-4);
background: color-mix(in srgb, #000 78%, transparent);
text-align: center;
}
& :where([data-error-message]) {
margin: 0;
}
& :where([data-video])::cue {
background: rgb(0 0 0 / 0.72);
color: #fff;
font-size: 1rem;
}
& :where([data-controls]) {
position: absolute;
inset: auto 0 0;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1) var(--space-2);
padding: var(--space-8) var(--space-3) var(--space-2);
background: linear-gradient(to top, rgb(0 0 0 / 0.78), rgb(0 0 0 / 0));
transition-property: opacity, translate;
transition-duration: var(--duration-normal);
transition-timing-function: var(--ease-out-strong);
}
& :where([data-stage][data-controls-hidden][data-state='playing'] [data-controls]) {
opacity: 0;
translate: 0 var(--space-2);
pointer-events: none;
}
& :where([data-controls] .rui-button--ghost) {
color: #fff;
}
@media (hover: hover) {
& :where([data-controls] .rui-button--ghost:hover:not(:disabled)) {
background: rgb(255 255 255 / 0.18);
}
}
& :where([data-controls] .rui-button--ghost:active:not(:disabled)) {
background: rgb(255 255 255 / 0.28);
}
/* The macOS themes draw a pressed button with a ring, which the inset bar replaces. */
& :where([data-controls] .rui-button--ghost[aria-pressed='true']) {
background: rgb(255 255 255 / 0.2);
color: #fff;
box-shadow: inset 0 -2px 0 var(--primary);
--tw-ring-shadow: 0 0 #0000;
}
& :where([data-rate]) {
min-inline-size: 3.25rem;
font-variant-numeric: tabular-nums;
}
& [data-playback] [data-icon='pause'],
& [data-playback][aria-pressed='true'] [data-icon='play'],
& [data-mute] [data-icon='muted'],
& [data-mute][aria-pressed='true'] [data-icon='volume'],
& [data-fullscreen] [data-icon='exit'],
& [data-fullscreen][aria-pressed='true'] [data-icon='enter'] {
display: none;
}
& [data-playback][aria-pressed='true'] [data-icon='pause'],
& [data-mute][aria-pressed='true'] [data-icon='muted'],
& [data-fullscreen][aria-pressed='true'] [data-icon='exit'] {
display: block;
}
& :where([data-fullscreen][hidden]) {
display: none;
}
& :where([data-scrub]) {
display: flex;
flex: 1 1 14rem;
align-items: center;
gap: var(--space-3);
min-inline-size: 0;
}
& :where([data-elapsed], [data-duration]) {
min-inline-size: 2.5ch;
font-size: 0.75rem;
font-variant-numeric: tabular-nums;
opacity: 0.85;
}
& :where([data-volume]) {
display: flex;
flex: 0 0 5.5rem;
align-items: center;
}
& :where([data-scrub] rui-slider, [data-volume] rui-slider),
& :where([data-scrub], [data-volume]) .rui-slider {
--rui-slider-track-length: 100%;
--rui-slider-track-color: rgb(255 255 255 / 0.28);
--rui-slider-fill-color: #fff;
--rui-slider-thumb-size: 0.875rem;
--rui-slider-thumb-background: #fff;
--rui-slider-thumb-border-color: #fff;
}
& :where([data-scrub] rui-slider, [data-volume] rui-slider) {
flex: 1;
min-inline-size: 0;
margin-inline: calc(var(--rui-slider-thumb-size) / 2);
}
& :where([data-scrub] .rui-slider__range-track) {
overflow: visible;
}
& .rui-slider__header {
display: none;
}
& :where([data-buffered]) {
position: absolute;
inset-block: 0;
inset-inline: 0;
border-radius: var(--rui-slider-track-radius, var(--radius-control));
overflow: hidden;
pointer-events: none;
}
& :where([data-buffered] i) {
position: absolute;
inset-block: 0;
inset-inline-start: calc(var(--start) * 1%);
inline-size: calc(var(--size) * 1%);
background: rgb(255 255 255 / 0.4);
}
& :where([data-status]) {
position: absolute;
inline-size: 1px;
block-size: 1px;
margin: 0;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
@container (max-width: 30rem) {
& :where([data-volume]) {
display: none;
}
}
@media (prefers-reduced-motion: reduce) {
& :where([data-controls], [data-big-play], [data-spinner]) {
transition: none;
}
& :where([data-stage][data-state='buffering'] [data-spinner]) {
animation: none;
}
}
}
@keyframes video-player-spin {
to {
rotate: 360deg;
}
}The element is the plain function's logic on a class. @query finds the parts, and @onEvent delegates the clicks, the keys, the pointer activity and the two sliders' rui-change events from the element, so no listener is added or removed by hand and none outlives the element. The seek key handler is delegated in the capture phase, which runs before the slider's own handler and lets it stop the arrow keys the player moves by whole seconds. fullscreenchange is a document-level @onEvent. pointerleave does not bubble, so its delegated listener runs in the capture phase.
The playback is createMediaController(this, ...), which attaches when the element connects and is destroyed when it leaves, pausing the video, clearing its source and releasing the object URL. Moving the element to another parent destroys and attaches it in the same turn; the controller waits a microtask before it lets go, so the source survives the move, and onConnected loads the clip again, which leaves the player paused at the start.
What the plain form writes with textContent and setAttribute, the element keeps in @state fields that @bindTo copies onto the markup: the stage's data-state, the status and clock text, the speed label, the aria-pressed of the four toggles, the error panel and whether the seek bar is enabled. data-controls-hidden is a field too, bound to the stage. The hide timer, the MutationObserver that keeps the seek thumb's aria-valuetext, the position written to the sliders, and the buffered bar stay hand written, because no field follows them. The timer and the thumb observer are stopped by a callback registered once in the constructor with registerCleanupCallback, because one registered in onConnected would be added again on every move. createCaptionsController(this, ...) attaches and is destroyed with the element, and onConnected calls disable(), because the controller keeps its selection through a move.
The same behavior as a RadiantElement. The markup is authored inside <video-player-element> and the element finds its parts with @query; there is nothing to mount, clean up or run again.
Could not load the video
import { RadiantElement, bindTo, customElement, onEvent, query, state } from '@ecopages/radiant';
import { createCaptionsController, createMediaController, type MediaState } from '@ecopages/radiant-ui/controllers';
import '@ecopages/radiant-ui/slider';
import type { RuiSliderChangeDetail, RuiSliderElement } from '@ecopages/radiant-ui/slider';
import { cycleValue, formatMediaTime } from '@ecopages/radiant-ui/helpers';
import {
Announcer,
CAPTIONS,
HIDE_CONTROLS_MS,
RATES,
bufferedSegments,
seekFromKey,
seekValueText,
shortcutFor,
stageState,
type Shortcut,
type StageState,
} from './video-player.data';
import { fetchSource, releaseSource } from './video-player.loader';
/**
* @remarks
* What the page shows that is a plain copy of the media state (the stage state, whether the controls are hidden, the
* pressed buttons, the clock, the status, the speed, the error panel) is a `@state` field that `@bindTo` writes onto
* the markup; the buffered bar and the slider values are written here because they are not a copy
* of one value.
*
* `createMediaController(this, ...)` takes the element as its host and attaches and destroys with it, so the element
* listens to no media event. The timer and the thumb observer are stopped by a callback
* registered once in the constructor, because one registered in `onConnected()` would be added again on every
* reconnect, and `onConnected()` starts the load again when the element is moved. Each pointer listener is
* delegated on the host, and `pointerleave`, which does not bubble, is delegated in the capture phase.
*/
@customElement('video-player-element')
export class VideoPlayerElement extends RadiantElement {
@query({ selector: '[data-stage]' }) private stage!: HTMLElement;
@query({ selector: '[data-video]' }) private video!: HTMLVideoElement;
@query({ selector: '[data-controls]' }) private controls!: HTMLElement;
@query({ selector: '[data-seek]' }) private seek!: RuiSliderElement;
@query({ selector: '[data-seek] [role="slider"]' }) private seekThumb!: HTMLElement;
@query({ selector: '[data-volume-input]' }) private volume!: RuiSliderElement;
@query({ selector: '[data-buffered]' }) private buffered!: HTMLElement;
@query({ selector: '[data-fullscreen]' }) private fullscreen!: HTMLButtonElement;
@state
@bindTo({ selector: '[data-stage]', attr: 'data-state' })
stageState: StageState = 'idle';
@state
@bindTo({ selector: '[data-stage]', bool: 'data-controls-hidden' })
controlsHidden = false;
@state
@bindTo({ selector: '[data-playback]', attr: 'aria-pressed', map: (value) => String(value) })
playing = false;
@state
@bindTo({ selector: '[data-mute]', attr: 'aria-pressed', map: (value) => String(value) })
muted = false;
@state
@bindTo({ selector: '[data-captions]', attr: 'aria-pressed', map: (value) => String(value) })
captionsOn = false;
@state
@bindTo({ selector: '[data-fullscreen]', attr: 'aria-pressed', map: (value) => String(value) })
fullscreenOn = false;
@state
@bindTo([
{ selector: '[data-rate]', text: true, map: (rate) => `${rate}x` },
{ selector: '[data-rate]', attr: 'aria-label', map: (rate) => `Speed ${rate}x` },
])
rate = 1;
@state
@bindTo({ selector: '[data-elapsed]', text: true })
elapsed = '0:00';
@state
@bindTo({ selector: '[data-duration]', text: true })
total = '0:00';
@state
@bindTo({ selector: '[data-status]', text: true })
status = '';
@state
@bindTo({ selector: '[data-seek]', bool: 'disabled', invert: true })
seekable = false;
@state
@bindTo({ selector: '[data-error]', bool: 'hidden', invert: true })
failed = false;
private hideTimer: ReturnType<typeof setTimeout> | undefined;
private pointer = 'mouse';
private bufferedKey = '';
private valueText = '';
private readonly announcer = new Announcer();
private readonly valueTextObserver = new MutationObserver(() => this.keepValueText());
private readonly captions = createCaptionsController(this, {
getMedia: () => this.video,
getAvoid: () => this.controls,
tracks: [{ language: 'en', label: 'English', cues: CAPTIONS }],
onState: (state) => {
this.captionsOn = state.enabled;
},
});
private readonly media = createMediaController(this, {
getMedia: () => this.video,
resolveSource: fetchSource,
releaseSource,
clearSourceOnDestroy: true,
onState: (state) => this.renderState(state),
onProgress: (state) => this.renderProgress(state),
});
constructor() {
super();
this.registerCleanupCallback(() => {
clearTimeout(this.hideTimer);
this.valueTextObserver.disconnect();
});
}
override onConnected(): void {
this.valueTextObserver.observe(this.seekThumb, { attributes: true, attributeFilter: ['aria-valuetext'] });
this.fullscreen.hidden = !document.fullscreenEnabled;
this.captions.disable();
this.announcer.reset();
void this.media.load(this.video.dataset.src!);
}
/**
* Writes the clock, the seek thumb and the buffered bar.
*
* @remarks
* The slider repaints in a later update with its own `aria-valuetext`, a bare number of seconds, so the text is
* kept by the observer as well as written here.
*/
private renderProgress(state: MediaState): void {
if (Number.isFinite(state.duration) && this.seek.max !== state.duration) this.seek.max = state.duration;
this.seek.value = [state.position];
this.valueText = seekValueText(state.position, state.duration);
this.keepValueText();
this.elapsed = formatMediaTime(state.position);
this.total = formatMediaTime(state.duration);
const segments = bufferedSegments(state.bufferedRanges, state.duration);
const key = JSON.stringify(segments);
if (key !== this.bufferedKey) {
this.bufferedKey = key;
this.buffered.replaceChildren(
...segments.map(({ start, size }) => {
const segment = document.createElement('i');
segment.style.setProperty('--start', String(start));
segment.style.setProperty('--size', String(size));
return segment;
}),
);
}
}
private keepValueText(): void {
if (this.seekThumb.getAttribute('aria-valuetext') !== this.valueText) {
this.seekThumb.setAttribute('aria-valuetext', this.valueText);
}
}
private renderState(state: MediaState): void {
const shown = stageState(state);
const message = this.announcer.next(state);
this.stageState = shown;
this.playing = state.status === 'playing';
this.muted = state.muted;
this.volume.value = [state.muted ? 0 : state.volume];
this.rate = state.rate;
this.seekable = state.seekable;
this.failed = shown === 'error';
if (message !== '') this.status = message;
this.renderProgress(state);
this.wake();
}
/**
* Shows the controls and, while the video plays, hides them again after `HIDE_CONTROLS_MS` of quiet. They stay
* while the pointer is over them or a control has keyboard focus, so a reader who is aiming at one never loses it.
*/
private wake(): void {
clearTimeout(this.hideTimer);
this.controlsHidden = false;
if (this.stageState !== 'playing') return;
this.hideTimer = setTimeout(() => {
if (this.controls.matches(':hover') || this.controls.querySelector(':focus-visible')) return this.wake();
this.controlsHidden = true;
}, HIDE_CONTROLS_MS);
}
private toggleCaptions(): void {
this.captions.toggle();
this.status = this.captionsOn ? 'Captions on' : 'Captions off';
}
/**
* Both calls reject when the browser refuses (no user gesture, a sandboxed frame), and the player has nothing to
* show for it: the button only follows `fullscreenchange`.
*/
private toggleFullscreen(): void {
const request =
document.fullscreenElement === this.stage ? document.exitFullscreen() : this.stage.requestFullscreen();
request.catch(() => undefined);
}
private run(shortcut: Shortcut): void {
const state = this.media.getState();
switch (shortcut.type) {
case 'toggle':
return void this.media.toggle();
case 'skip':
return this.media.skip(shortcut.seconds);
case 'volume': {
const next = Math.round((state.volume + shortcut.delta) * 100) / 100;
if (shortcut.delta > 0 && state.muted) this.media.setMuted(false);
this.media.setVolume(next);
this.status = `Volume ${Math.round(this.media.getState().volume * 100)}%`;
return;
}
case 'mute':
return this.media.toggleMuted();
case 'captions':
return this.toggleCaptions();
case 'fullscreen':
return this.toggleFullscreen();
case 'jump':
return this.media.seek(state.duration * shortcut.fraction);
case 'start':
return this.media.seek(0);
case 'end':
return this.media.seek(state.duration);
}
}
@onEvent({ selector: '[data-stage]', type: 'keydown' })
shortcut(event: Event): void {
this.wake();
const shortcut = shortcutFor(event as KeyboardEvent);
if (!shortcut) return;
event.preventDefault();
this.run(shortcut);
}
/**
* A touch on the video is a tap that shows or hides the controls, which `tapVideo` decides, so it is not
* activity here.
*/
@onEvent({ selector: '[data-stage]', type: 'pointermove' })
@onEvent({ selector: '[data-stage]', type: 'pointerdown' })
@onEvent({ selector: '[data-stage]', type: 'pointerleave', options: { capture: true } })
activity(event: Event): void {
const { target, pointerType } = event as PointerEvent;
if (target !== this.video || pointerType !== 'touch') this.wake();
}
@onEvent({ selector: '[data-video]', type: 'pointerdown' })
rememberPointer(event: Event): void {
this.pointer = (event as PointerEvent).pointerType;
}
@onEvent({ selector: '[data-video]', type: 'click' })
tapVideo(): void {
if (this.pointer === 'touch' && this.stageState === 'playing') {
if (this.controlsHidden) this.wake();
else this.controlsHidden = true;
} else void this.media.toggle();
}
@onEvent({ selector: '[data-video]', type: 'dblclick' })
@onEvent({ selector: '[data-fullscreen]', type: 'click' })
enterFullscreen(): void {
this.toggleFullscreen();
}
@onEvent({ selector: '[data-big-play]', type: 'click' })
@onEvent({ selector: '[data-playback]', type: 'click' })
togglePlayback(): void {
void this.media.toggle();
}
@onEvent({ selector: '[data-mute]', type: 'click' })
toggleMute(): void {
this.media.toggleMuted();
}
@onEvent({ selector: '[data-rate]', type: 'click' })
cycleRate(): void {
this.media.setRate(Number(cycleValue(RATES, String(this.media.getState().rate))));
this.status = `Speed ${this.media.getState().rate}x`;
}
@onEvent({ selector: '[data-captions]', type: 'click' })
pressCaptions(): void {
this.toggleCaptions();
}
@onEvent({ selector: '[data-retry]', type: 'click' })
retry(): void {
void this.media.retry();
}
@onEvent({ document: true, type: 'fullscreenchange' })
followFullscreen(): void {
this.fullscreenOn = document.fullscreenElement === this.stage;
}
/** The slider works in seconds and reports `rui-change` only for the reader, never for a position written to it. */
@onEvent({ selector: '[data-seek]', type: 'rui-change' })
scrub(event: Event): void {
this.media.scrub((event as CustomEvent<RuiSliderChangeDetail>).detail.value[0]);
}
/**
* Delegated in the capture phase, which runs before the slider's own key handler and lets this stop it for the
* keys the player moves by whole seconds, so the slider's 0.01 s step never applies to an arrow key. Home and
* End are left to the slider.
*/
@onEvent({ selector: '[data-seek]', type: 'keydown', options: { capture: true } })
scrubWithKey(event: Event): void {
const key = event as KeyboardEvent;
const seconds = seekFromKey(key.key);
if (seconds === undefined) return;
key.preventDefault();
key.stopPropagation();
this.wake();
this.media.skip(seconds);
}
@onEvent({ selector: '[data-volume-input]', type: 'rui-change' })
setVolume(event: Event): void {
const level = (event as CustomEvent<RuiSliderChangeDetail>).detail.value[0];
this.media.setVolume(level);
if (level > 0) this.media.setMuted(false);
}
}import type { MediaState } from '@ecopages/radiant-ui/controllers';
import { formatMediaTime } from '@ecopages/radiant-ui/helpers';
/** The sample clip and its poster, made by `scripts/generate-video-player-assets.mjs`. */
export const VIDEO = {
src: '/assets/video/radiant-reel.webm',
poster: '/assets/video/radiant-reel.jpg',
} as const;
/** The English captions of the clip, one for each of its five scenes, in seconds. */
export const CAPTIONS: readonly { start: number; end: number; text: string }[] = [
{ start: 0.2, end: 2.3, text: 'Scene one: a slow start' },
{ start: 2.6, end: 4.7, text: 'Scene two: the shapes arrive' },
{ start: 5, end: 7.1, text: 'Scene three: everything turns' },
{ start: 7.4, end: 9.5, text: 'Scene four: the light moves on' },
{ start: 9.8, end: 11.9, text: 'Scene five: and it settles' },
];
/**
* The playback rates the speed button cycles through, as the strings `cycleValue` works on, and the value the
* button shows with an `x`.
*/
export const RATES: readonly string[] = ['1', '1.25', '1.5', '2', '0.5'];
/** Seconds the arrow keys move the playback by, on the seek thumb and on the player. */
export const SEEK_STEP = 5;
/** Seconds `J`, `L`, Page Up and Page Down move the playback by. */
export const LONG_SEEK_STEP = 10;
/** The fraction of the full volume the arrow keys change it by. */
export const VOLUME_STEP = 0.1;
/** Milliseconds without a pointer or key event after which the controls hide while the video plays. */
export const HIDE_CONTROLS_MS = 2500;
/** What the stage shows: `data-state` on `[data-stage]` carries one of these and the stylesheet draws from it. */
export type StageState = 'idle' | 'buffering' | 'playing' | 'paused' | 'error';
/** What a shortcut asks the player to do. */
export type Shortcut =
| { type: 'toggle' }
| { type: 'skip'; seconds: number }
| { type: 'volume'; delta: number }
| { type: 'mute' }
| { type: 'captions' }
| { type: 'fullscreen' }
| { type: 'jump'; fraction: number }
| { type: 'start' }
| { type: 'end' };
const SHORTCUTS = new Map<string, Shortcut>([
[' ', { type: 'toggle' }],
['k', { type: 'toggle' }],
['j', { type: 'skip', seconds: -LONG_SEEK_STEP }],
['l', { type: 'skip', seconds: LONG_SEEK_STEP }],
['ArrowLeft', { type: 'skip', seconds: -SEEK_STEP }],
['ArrowRight', { type: 'skip', seconds: SEEK_STEP }],
['ArrowUp', { type: 'volume', delta: VOLUME_STEP }],
['ArrowDown', { type: 'volume', delta: -VOLUME_STEP }],
['m', { type: 'mute' }],
['c', { type: 'captions' }],
['f', { type: 'fullscreen' }],
['Home', { type: 'start' }],
['End', { type: 'end' }],
...Array.from({ length: 10 }, (_, digit): [string, Shortcut] => [
String(digit),
{ type: 'jump', fraction: digit / 10 },
]),
]);
const SLIDER_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'PageUp', 'PageDown']);
/**
* The shortcut a key event asks for, or `undefined` when the player must leave it alone.
*
* @remarks
* A key that carries Ctrl, Alt or Meta belongs to the browser. A button owns Space and Enter, which activate it. A
* slider thumb owns the arrows, Home, End and the page keys, which move it; the letters and digits still reach the
* player. The target is the element the key was pressed on, which a `keydown` listener on the stage always has.
*/
export function shortcutFor(
event: Pick<KeyboardEvent, 'key' | 'ctrlKey' | 'altKey' | 'metaKey' | 'target'>,
): Shortcut | undefined {
if (event.ctrlKey || event.altKey || event.metaKey) return undefined;
const target = event.target as Element;
if (target.closest('button') && (event.key === ' ' || event.key === 'Enter')) return undefined;
if (target.closest('[role="slider"]') && SLIDER_KEYS.has(event.key)) return undefined;
return SHORTCUTS.get(event.key.length === 1 ? event.key.toLowerCase() : event.key);
}
const SEEK_KEYS = new Map([
['ArrowRight', SEEK_STEP],
['ArrowUp', SEEK_STEP],
['ArrowLeft', -SEEK_STEP],
['ArrowDown', -SEEK_STEP],
['PageUp', LONG_SEEK_STEP],
['PageDown', -LONG_SEEK_STEP],
]);
/**
* Seconds a key moves the seek slider by, or `undefined` for any other key.
*
* @remarks
* The slider works in seconds with a step of 0.01, fine enough that the per-frame position write is not rounded and
* the thumb glides. A step that fine would make an arrow key inaudible, so the player handles these keys and the
* slider keeps Home and End.
*/
export function seekFromKey(key: string): number | undefined {
return SEEK_KEYS.get(key);
}
/** The state of the stage for a snapshot of the media element. */
export function stageState(state: Pick<MediaState, 'status' | 'waiting' | 'error'>): StageState {
if (state.error) return 'error';
if (state.waiting || state.status === 'loading') return 'buffering';
if (state.status === 'idle') return 'idle';
return state.status === 'playing' ? 'playing' : 'paused';
}
/** The text a snapshot is worth in the polite live region, `''` while there is nothing to say. */
export function statusMessage(state: Pick<MediaState, 'status' | 'waiting' | 'error' | 'blocked'>): string {
if (state.blocked) return 'Playback was blocked, press Play to start';
switch (stageState(state)) {
case 'error':
return 'Could not load the video';
case 'buffering':
return 'Buffering';
case 'playing':
return 'Playing';
case 'paused':
return state.status === 'ended' ? 'Ended' : 'Paused';
default:
return '';
}
}
/**
* Decides what the polite live region says.
*
* @remarks
* The player says nothing while the clip loads on its own: "Buffering" and "Paused" at page load, or after the
* player was moved, are noise to a reader who has done nothing yet. It starts to report once the clip has played,
* and a failure ("Could not load", "Playback was blocked") is always reported, because it answers an action or
* leaves the player unusable. A message is said once until it changes.
*/
export class Announcer {
private spoken = '';
private started = false;
/** Forgets what was said and silences the player again, for a clip that loads from the start. */
reset(): void {
this.spoken = '';
this.started = false;
}
/** The message to say for this snapshot, or `''` when there is nothing new to say. */
next(state: Pick<MediaState, 'status' | 'waiting' | 'error' | 'blocked'>): string {
if (state.status === 'playing') this.started = true;
const message = this.started || state.error || state.blocked ? statusMessage(state) : '';
if (message === this.spoken) return '';
this.spoken = message;
return message;
}
}
/** The `aria-valuetext` of the seek thumb, such as `1:15 of 4:00`. */
export function seekValueText(position: number, duration: number): string {
return `${formatMediaTime(position)} of ${formatMediaTime(duration)}`;
}
/** One buffered range as the percentages the stylesheet draws it with. */
export type BufferedSegment = { start: number; size: number };
/** The buffered ranges as percentages of the duration, empty until the duration is known. */
export function bufferedSegments(ranges: readonly (readonly [number, number])[], duration: number): BufferedSegment[] {
if (!Number.isFinite(duration) || duration <= 0) return [];
return ranges.map(([from, to]) => ({
start: (from / duration) * 100,
size: ((Math.min(to, duration) - from) / duration) * 100,
}));
}const inFlight = new Map<string, Promise<Blob>>();
function download(url: string): Promise<Blob> {
let pending = inFlight.get(url);
if (!pending) {
pending = fetchBlob(url).finally(() => inFlight.delete(url));
inFlight.set(url, pending);
}
return pending;
}
async function fetchBlob(url: string): Promise<Blob> {
const response = await fetch(url);
if (!response.ok) throw new Error(`${response.status} ${response.statusText} for ${url}`);
return response.blob();
}
/**
* Fetches a video into a `Blob` and returns an object URL, for `MediaController`'s `resolveSource`.
*
* @remarks
* A media element can only seek in a file whose server answers range requests, and many development and preview
* servers (this site's among them) do not: the element then reports nothing seekable and every seek snaps back to
* the start. The sample clip is about a megabyte, so it is fetched whole and played from memory, which always
* seeks. For long media serve the file with range support and pass its URL to `load()` without a `resolveSource`.
* A failed request rejects, which puts the controller in its `error` state; `retry()` calls this again.
*
* Requests for a url that is still downloading share one download, and each caller gets an object URL of its own.
* The page swaps the authoring pattern of a recipe by mounting the new form as soon as the old one is on the page,
* which would otherwise fetch the clip twice, and a shared object URL would be revoked under the form that is left
* running when the other releases it. A finished download is not kept, so a retry or a player that is moved asks the
* server again.
*/
export async function fetchSource(url: string): Promise<string> {
return URL.createObjectURL(await download(url));
}
/** Frees an object URL `fetchSource` made; `MediaController` calls it as `releaseSource` once the element has let go of it. */
export function releaseSource(url: string): void {
URL.revokeObjectURL(url);
}<video-player-element>
<div
data-stage
data-state="idle"
role="group"
aria-label="Video player"
aria-describedby="video-player-element-help"
tabindex="0"
>
<video
data-video
data-src="/assets/video/radiant-reel.webm"
poster="/assets/video/radiant-reel.jpg"
preload="metadata"
playsinline
></video>
<button
type="button"
class="rui-button rui-button--filled rui-button--lg rui-button--square"
data-big-play
aria-hidden="true"
tabindex="-1"
>
<svg viewBox="0 0 24 24" width="28" height="28" aria-hidden="true" focusable="false">
<path d="M8 5v14l11-7z" fill="currentColor" />
</svg>
</button>
<span data-spinner aria-hidden="true"></span>
<div data-error hidden>
<p data-error-message>Could not load the video</p>
<button type="button" class="rui-button rui-button--filled rui-button--sm" data-retry>Retry</button>
</div>
<div data-controls>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-playback
aria-label="Play"
aria-pressed="false"
>
<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="play">
<path d="M8 5v14l11-7z" fill="currentColor" /></svg
><svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="pause">
<path d="M6 5h4v14H6zM14 5h4v14h-4z" fill="currentColor" />
</svg>
</button>
<div data-scrub>
<span data-elapsed>0:00</span>
<rui-slider data-seek step="0.01" label="Seek" min="0" max="1" value="0" disabled>
<div class="rui-slider rui-slider--single" data-ref="root">
<div class="rui-slider__range">
<div
class="rui-slider__range-track"
data-ref="rangeTrack"
style="--rui-slider-fill-start: 0%; --rui-slider-fill-size: 0%; --rui-slider-value: 0%"
>
<div data-buffered aria-hidden="true"></div>
<div class="rui-slider__range-fill" data-ref="rangeFill"></div>
<button
type="button"
class="rui-slider__thumb"
data-ref="singleThumb"
data-thumb="value"
role="slider"
aria-label="Seek"
></button>
</div>
</div>
</div>
</rui-slider>
<span data-duration>0:00</span>
</div>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-mute
aria-label="Mute"
aria-pressed="false"
>
<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="volume">
<path d="M4 9v6h4l5 4V5L8 9z" fill="currentColor" />
<path
d="M16 9a4 4 0 0 1 0 6"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/></svg
><svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="muted">
<path d="M4 9v6h4l5 4V5L8 9z" fill="currentColor" />
<path
d="M16.5 9.5l5 5M21.5 9.5l-5 5"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</button>
<div data-volume>
<rui-slider data-volume-input step="0.05" label="Volume" min="0" max="1" value="1">
<div class="rui-slider rui-slider--single" data-ref="root">
<div class="rui-slider__range">
<div
class="rui-slider__range-track"
data-ref="rangeTrack"
style="
--rui-slider-fill-start: 0%;
--rui-slider-fill-size: 100%;
--rui-slider-value: 100%;
"
>
<div class="rui-slider__range-fill" data-ref="rangeFill"></div>
<button
type="button"
class="rui-slider__thumb"
data-ref="singleThumb"
data-thumb="value"
role="slider"
aria-label="Volume"
></button>
</div>
</div>
</div>
</rui-slider>
</div>
<button type="button" class="rui-button rui-button--ghost rui-button--md" data-rate aria-label="Speed 1x">
1x
</button>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-captions
aria-label="Captions"
aria-pressed="false"
>
<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false">
<rect
x="3"
y="5"
width="18"
height="14"
rx="2"
fill="none"
stroke="currentColor"
stroke-width="2"
/>
<path
d="M10.5 10.5a2 2 0 1 0 0 3M17 10.5a2 2 0 1 0 0 3"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</button>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-fullscreen
aria-label="Fullscreen"
aria-pressed="false"
>
<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="enter">
<path
d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/></svg
><svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="exit">
<path
d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</button>
</div>
<p data-status aria-live="polite"></p>
</div>
<span data-help hidden id="video-player-element-help"
>Space or K plays and pauses, J and L skip 10 seconds, the arrows seek 5 seconds or change the volume, M mutes,
C toggles captions, F toggles fullscreen, 0 to 9 jump through the video, Home and End go to its start and
end</span
>
</video-player-element>.primitive-example:is(
[data-example='video-player'],
:has(> video-player-element, > [data-controller='video-player'], > video-player-app)
) {
display: block;
width: min(100%, 44rem);
& :where([data-stage]) {
position: relative;
overflow: hidden;
box-sizing: border-box;
aspect-ratio: 16 / 9;
border-radius: var(--radius-container);
background: #000;
color: #fff;
box-shadow: var(--shadow-overlay);
container-type: inline-size;
user-select: none;
}
& :where([data-stage]:focus-visible) {
outline: 2px solid var(--focus-ring);
outline-offset: 2px;
}
& :where([data-stage]:fullscreen) {
aspect-ratio: auto;
inline-size: 100%;
block-size: 100%;
border-radius: 0;
}
& :where([data-stage]:fullscreen:focus-visible) {
outline-offset: -4px;
}
/* The ring is drawn over the picture, so it is white, which stands out from the dark bar and the error panel. */
& :where([data-controls], [data-error]) {
--focus-ring: #fff;
}
& :where([data-stage][data-controls-hidden][data-state='playing']) {
cursor: none;
}
& :where([data-video]) {
display: block;
inline-size: 100%;
block-size: 100%;
object-fit: contain;
cursor: pointer;
}
& :where([data-big-play]) {
position: absolute;
inset: 50% auto auto 50%;
translate: -50% -50%;
inline-size: calc(var(--size-control-lg) * 1.75);
block-size: calc(var(--size-control-lg) * 1.75);
border-radius: var(--radius-full);
box-shadow: var(--shadow-overlay);
opacity: 0;
pointer-events: none;
transition-property: opacity, scale;
transition-duration: var(--duration-normal);
transition-timing-function: var(--ease-out-strong);
scale: 0.9;
}
& :where([data-stage]:is([data-state='paused'], [data-state='idle']) [data-big-play]) {
opacity: 1;
pointer-events: auto;
scale: 1;
}
& :where([data-stage][data-state='idle'] [data-big-play]) {
opacity: 0.6;
}
& :where([data-spinner]) {
position: absolute;
inset: 50% auto auto 50%;
translate: -50% -50%;
box-sizing: border-box;
inline-size: calc(var(--size-control-lg) * 1.1);
block-size: calc(var(--size-control-lg) * 1.1);
border: 3px solid rgb(255 255 255 / 0.3);
border-block-start-color: #fff;
border-radius: var(--radius-full);
opacity: 0;
pointer-events: none;
transition: opacity var(--duration-normal) var(--ease-out-strong);
}
& :where([data-stage][data-state='buffering'] [data-spinner]) {
opacity: 1;
animation: video-player-spin 0.9s linear infinite;
}
& :where([data-error]:not([hidden])) {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: var(--space-4);
padding: var(--space-4);
background: color-mix(in srgb, #000 78%, transparent);
text-align: center;
}
& :where([data-error-message]) {
margin: 0;
}
& :where([data-video])::cue {
background: rgb(0 0 0 / 0.72);
color: #fff;
font-size: 1rem;
}
& :where([data-controls]) {
position: absolute;
inset: auto 0 0;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1) var(--space-2);
padding: var(--space-8) var(--space-3) var(--space-2);
background: linear-gradient(to top, rgb(0 0 0 / 0.78), rgb(0 0 0 / 0));
transition-property: opacity, translate;
transition-duration: var(--duration-normal);
transition-timing-function: var(--ease-out-strong);
}
& :where([data-stage][data-controls-hidden][data-state='playing'] [data-controls]) {
opacity: 0;
translate: 0 var(--space-2);
pointer-events: none;
}
& :where([data-controls] .rui-button--ghost) {
color: #fff;
}
@media (hover: hover) {
& :where([data-controls] .rui-button--ghost:hover:not(:disabled)) {
background: rgb(255 255 255 / 0.18);
}
}
& :where([data-controls] .rui-button--ghost:active:not(:disabled)) {
background: rgb(255 255 255 / 0.28);
}
/* The macOS themes draw a pressed button with a ring, which the inset bar replaces. */
& :where([data-controls] .rui-button--ghost[aria-pressed='true']) {
background: rgb(255 255 255 / 0.2);
color: #fff;
box-shadow: inset 0 -2px 0 var(--primary);
--tw-ring-shadow: 0 0 #0000;
}
& :where([data-rate]) {
min-inline-size: 3.25rem;
font-variant-numeric: tabular-nums;
}
& [data-playback] [data-icon='pause'],
& [data-playback][aria-pressed='true'] [data-icon='play'],
& [data-mute] [data-icon='muted'],
& [data-mute][aria-pressed='true'] [data-icon='volume'],
& [data-fullscreen] [data-icon='exit'],
& [data-fullscreen][aria-pressed='true'] [data-icon='enter'] {
display: none;
}
& [data-playback][aria-pressed='true'] [data-icon='pause'],
& [data-mute][aria-pressed='true'] [data-icon='muted'],
& [data-fullscreen][aria-pressed='true'] [data-icon='exit'] {
display: block;
}
& :where([data-fullscreen][hidden]) {
display: none;
}
& :where([data-scrub]) {
display: flex;
flex: 1 1 14rem;
align-items: center;
gap: var(--space-3);
min-inline-size: 0;
}
& :where([data-elapsed], [data-duration]) {
min-inline-size: 2.5ch;
font-size: 0.75rem;
font-variant-numeric: tabular-nums;
opacity: 0.85;
}
& :where([data-volume]) {
display: flex;
flex: 0 0 5.5rem;
align-items: center;
}
& :where([data-scrub] rui-slider, [data-volume] rui-slider),
& :where([data-scrub], [data-volume]) .rui-slider {
--rui-slider-track-length: 100%;
--rui-slider-track-color: rgb(255 255 255 / 0.28);
--rui-slider-fill-color: #fff;
--rui-slider-thumb-size: 0.875rem;
--rui-slider-thumb-background: #fff;
--rui-slider-thumb-border-color: #fff;
}
& :where([data-scrub] rui-slider, [data-volume] rui-slider) {
flex: 1;
min-inline-size: 0;
margin-inline: calc(var(--rui-slider-thumb-size) / 2);
}
& :where([data-scrub] .rui-slider__range-track) {
overflow: visible;
}
& .rui-slider__header {
display: none;
}
& :where([data-buffered]) {
position: absolute;
inset-block: 0;
inset-inline: 0;
border-radius: var(--rui-slider-track-radius, var(--radius-control));
overflow: hidden;
pointer-events: none;
}
& :where([data-buffered] i) {
position: absolute;
inset-block: 0;
inset-inline-start: calc(var(--start) * 1%);
inline-size: calc(var(--size) * 1%);
background: rgb(255 255 255 / 0.4);
}
& :where([data-status]) {
position: absolute;
inline-size: 1px;
block-size: 1px;
margin: 0;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
@container (max-width: 30rem) {
& :where([data-volume]) {
display: none;
}
}
@media (prefers-reduced-motion: reduce) {
& :where([data-controls], [data-big-play], [data-spinner]) {
transition: none;
}
& :where([data-stage][data-state='buffering'] [data-spinner]) {
animation: none;
}
}
}
@keyframes video-player-spin {
to {
rotate: 360deg;
}
}The element is the plain function's logic on a class. @query finds the parts, and @onEvent delegates the clicks, the keys, the pointer activity and the two sliders' rui-change events from the element, so no listener is added or removed by hand and none outlives the element. The seek key handler is delegated in the capture phase, which runs before the slider's own handler and lets it stop the arrow keys the player moves by whole seconds. fullscreenchange is a document-level @onEvent. pointerleave does not bubble, so its delegated listener runs in the capture phase.
The playback is createMediaController(this, ...), which attaches when the element connects and is destroyed when it leaves, pausing the video, clearing its source and releasing the object URL. Moving the element to another parent destroys and attaches it in the same turn; the controller waits a microtask before it lets go, so the source survives the move, and onConnected loads the clip again, which leaves the player paused at the start.
What the plain form writes with textContent and setAttribute, the element keeps in @state fields that @bindTo copies onto the markup: the stage's data-state, the status and clock text, the speed label, the aria-pressed of the four toggles, the error panel and whether the seek bar is enabled. data-controls-hidden is a field too, bound to the stage. The hide timer, the MutationObserver that keeps the seek thumb's aria-valuetext, the position written to the sliders, and the buffered bar stay hand written, because no field follows them. The timer and the thumb observer are stopped by a callback registered once in the constructor with registerCleanupCallback, because one registered in onConnected would be added again on every move. createCaptionsController(this, ...) attaches and is destroyed with the element, and onConnected calls disable(), because the controller keeps its selection through a move.
The same behavior as a single RadiantElement that owns its markup: render() draws the stage, the controls and the status, and what changes them is @state.
import { RadiantElement, customElement, onEvent, query, state } from '@ecopages/radiant';
import { createCaptionsController, createMediaController, type MediaState } from '@ecopages/radiant-ui/controllers';
import { RuiButton } from '@ecopages/radiant-ui/button';
import { cycleValue, formatMediaTime } from '@ecopages/radiant-ui/helpers';
import { RuiSlider } from '@ecopages/radiant-ui/slider';
import type { RuiSliderChangeDetail, RuiSliderElement } from '@ecopages/radiant-ui/slider';
import {
Announcer,
CAPTIONS,
HIDE_CONTROLS_MS,
RATES,
VIDEO,
bufferedSegments,
seekFromKey,
seekValueText,
shortcutFor,
stageState,
type Shortcut,
type StageState,
} from './video-player.data';
import { fetchSource, releaseSource } from './video-player.loader';
const HELP =
'Space or K plays and pauses, J and L skip 10 seconds, the arrows seek 5 seconds or change the volume, M mutes, C toggles captions, F toggles fullscreen, 0 to 9 jump through the video, Home and End go to its start and end';
/**
* @remarks
* What changes the markup is `@state`: the stage state, the pressed buttons, the speed and whether the seek bar is
* enabled. Whether the controls are hidden and whether it is full screen are fields that are also written to the DOM
* at once, because a touch tap or a `fullscreenchange` must show in the same turn. What changes every frame never
* goes through `render()`: the clock and the status are bound with `this.$`, and the seek position, the volume, the thumb's `aria-valuetext` and the
* buffered bar are written to the DOM by hand, from `onProgress`.
*
* Playback is a `MediaController` created with the element as its host, so the `video` element has no media
* listener. The buffered layer is the one node `RuiSlider` has no region for: it is added to the seek track after
* each render that lacks it.
*/
@customElement('video-player-app')
export class VideoPlayerApp extends RadiantElement<{ status: string; elapsed: string; total: string }> {
@state stage: StageState = 'idle';
@state playing = false;
@state muted = false;
@state ready = false;
@state captionsOn = false;
@state fullscreenAvailable = false;
@state rate = 1;
@state status = '';
@state elapsed = '0:00';
@state total = '0:00';
@query({ selector: '[data-stage]' }) private stageNode!: HTMLElement;
@query({ selector: '[data-video]' }) private video!: HTMLVideoElement;
@query({ selector: '[data-controls]' }) private controls!: HTMLElement;
@query({ selector: '[data-seek]' }) private seek!: RuiSliderElement;
@query({ selector: '[data-fullscreen]' }) private fullscreenButton!: HTMLElement;
@query({ selector: '[data-volume-input]' }) private volume!: RuiSliderElement;
private controlsHidden = false;
private fullscreen = false;
private hideTimer: ReturnType<typeof setTimeout> | undefined;
private pointer = 'mouse';
private position = 0;
private seekMax = 1;
private level = 1;
private bufferedKey = '';
private valueText = '';
private readonly announcer = new Announcer();
private thumb: HTMLElement | null = null;
private readonly thumbObserver = new MutationObserver(() => this.keepValueText());
private readonly captions = createCaptionsController(this, {
getMedia: () => this.video,
getAvoid: () => this.controls,
tracks: [{ language: 'en', label: 'English', cues: CAPTIONS }],
onState: (state) => {
this.captionsOn = state.enabled;
},
});
private readonly media = createMediaController(this, {
getMedia: () => this.video,
resolveSource: fetchSource,
releaseSource,
clearSourceOnDestroy: true,
onState: (state) => this.renderState(state),
onProgress: (state) => this.renderProgress(state),
});
constructor() {
super();
this.registerCleanupCallback(() => {
clearTimeout(this.hideTimer);
this.thumbObserver.disconnect();
this.thumb = null;
});
}
/**
* Starts the player paused on the clip, each time the element connects.
*
* @remarks
* It runs after the render, so the `video` element exists. The controllers attached when the element
* connected, before the first render, when there was no media yet, so the media controller attaches again here and
* the captions controller refreshes. The cleanup is
* registered once in the constructor, because one registered here would be added again on every reconnect.
*/
override onConnected(): void {
this.captions.refresh();
this.captions.disable();
this.fullscreenAvailable = document.fullscreenEnabled;
this.announcer.reset();
this.media.attach();
void this.media.load(this.video.dataset.src!);
}
/**
* @remarks
* A document-level `@onEvent` is removed with the element. The button's `aria-pressed` is written here at once,
* and `render()` reads the same field, so a render caused by another change does not undo it.
*/
@onEvent({ document: true, type: 'fullscreenchange' })
followFullscreen(): void {
this.fullscreen = document.fullscreenElement === this.stageNode;
this.fullscreenButton.setAttribute('aria-pressed', String(this.fullscreen));
}
/**
* Adds the buffered layer to the seek track and watches the seek thumb after each render.
*
* @remarks
* The slider repaints in a later update with its own `aria-valuetext`, a bare number of seconds, so the observer
* puts the player's text back. A render that replaced the track would drop the layer, which is added again here.
*/
protected override updated(): void {
const track = this.seek.querySelector<HTMLElement>('[data-ref="rangeTrack"]')!;
if (!track.querySelector('[data-buffered]')) {
const layer = document.createElement('div');
layer.setAttribute('data-buffered', '');
layer.setAttribute('aria-hidden', 'true');
track.prepend(layer);
this.bufferedKey = '';
}
const thumb = this.seek.querySelector<HTMLElement>('[role="slider"]')!;
if (thumb !== this.thumb) {
this.thumbObserver.disconnect();
this.thumb = thumb;
this.thumbObserver.observe(thumb, { attributes: true, attributeFilter: ['aria-valuetext'] });
}
}
private renderState(state: MediaState): void {
const shown = stageState(state);
const message = this.announcer.next(state);
this.stage = shown;
this.playing = state.status === 'playing';
this.muted = state.muted;
this.rate = state.rate;
this.ready = state.seekable;
this.level = state.muted ? 0 : state.volume;
this.volume.value = [this.level];
if (message !== '') this.status = message;
this.renderProgress(state);
this.wake();
}
/** The controller reports the pending scrub target as the position, so the thumb and the clock never jump back. */
private renderProgress(state: MediaState): void {
if (Number.isFinite(state.duration) && this.seekMax !== state.duration) {
this.seekMax = state.duration;
this.seek.max = state.duration;
}
this.position = state.position;
this.seek.value = [state.position];
this.valueText = seekValueText(state.position, state.duration);
this.keepValueText();
this.elapsed = formatMediaTime(state.position);
this.total = formatMediaTime(state.duration);
const segments = bufferedSegments(state.bufferedRanges, state.duration);
const key = JSON.stringify(segments);
const layer = this.seek.querySelector('[data-buffered]');
if (layer && key !== this.bufferedKey) {
this.bufferedKey = key;
layer.replaceChildren(
...segments.map(({ start, size }) => {
const segment = document.createElement('i');
segment.style.setProperty('--start', String(start));
segment.style.setProperty('--size', String(size));
return segment;
}),
);
}
}
private keepValueText(): void {
const thumb = this.thumb;
if (thumb && this.valueText !== '' && thumb.getAttribute('aria-valuetext') !== this.valueText) {
thumb.setAttribute('aria-valuetext', this.valueText);
}
}
/**
* Shows the controls and, while the video plays, hides them again after `HIDE_CONTROLS_MS` of quiet. They stay
* while the pointer is over them or a control has keyboard focus, so a reader who is aiming at one never loses it.
*/
private wake(): void {
clearTimeout(this.hideTimer);
this.hideControls(false);
if (this.stage !== 'playing') return;
this.hideTimer = setTimeout(() => {
if (this.controls.matches(':hover') || this.controls.querySelector(':focus-visible')) return this.wake();
this.hideControls(true);
}, HIDE_CONTROLS_MS);
}
/**
* Writes `data-controls-hidden` at once and keeps it in a field that `render()` reads, instead of `@state`.
*
* @remarks
* A render is deferred, and a touch tap or a pointer move must show the result in the same turn. The field keeps
* a render caused by another change from undoing it.
*/
private hideControls(hidden: boolean): void {
this.controlsHidden = hidden;
this.stageNode.toggleAttribute('data-controls-hidden', hidden);
}
private toggleCaptions(): void {
this.captions.toggle();
this.status = this.captionsOn ? 'Captions on' : 'Captions off';
}
/**
* Both calls reject when the browser refuses (no user gesture, a sandboxed frame), and the player has nothing to
* show for it: the button only follows `fullscreenchange`.
*/
private toggleFullscreen(): void {
const request =
document.fullscreenElement === this.stageNode
? document.exitFullscreen()
: this.stageNode.requestFullscreen();
request.catch(() => undefined);
}
private run(shortcut: Shortcut): void {
const state = this.media.getState();
switch (shortcut.type) {
case 'toggle':
return void this.media.toggle();
case 'skip':
return this.media.skip(shortcut.seconds);
case 'volume': {
const next = Math.round((state.volume + shortcut.delta) * 100) / 100;
if (shortcut.delta > 0 && state.muted) this.media.setMuted(false);
this.media.setVolume(next);
this.status = `Volume ${Math.round(this.media.getState().volume * 100)}%`;
return;
}
case 'mute':
return this.media.toggleMuted();
case 'captions':
return this.toggleCaptions();
case 'fullscreen':
return this.toggleFullscreen();
case 'jump':
return this.media.seek(state.duration * shortcut.fraction);
case 'start':
return this.media.seek(0);
case 'end':
return this.media.seek(state.duration);
}
}
private onKey(event: KeyboardEvent): void {
this.wake();
const shortcut = shortcutFor(event);
if (!shortcut) return;
event.preventDefault();
this.run(shortcut);
}
/**
* A touch on the video is a tap that shows or hides the controls, which the click handler decides, so it is not
* activity here.
*/
private onActivity(event: PointerEvent): void {
if (event.target !== this.video || event.pointerType !== 'touch') this.wake();
}
private onVideoClick(): void {
if (this.pointer === 'touch' && this.stage === 'playing') {
if (this.controlsHidden) this.wake();
else this.hideControls(true);
} else void this.media.toggle();
}
private cycleRate(): void {
this.media.setRate(Number(cycleValue(RATES, String(this.media.getState().rate))));
this.status = `Speed ${this.media.getState().rate}x`;
}
/** The slider works in seconds and reports `rui-change` only for the reader, never for the position written to it. */
private onSeek(event: Event): void {
this.media.scrub((event as CustomEvent<RuiSliderChangeDetail>).detail.value[0]);
}
private onVolume(event: Event): void {
const level = (event as CustomEvent<RuiSliderChangeDetail>).detail.value[0];
this.media.setVolume(level);
if (level > 0) this.media.setMuted(false);
}
/**
* @remarks
* The one handler that is not a JSX `on:*` attribute: it is delegated in the capture phase, which runs before the
* slider's own key handler and lets this stop it for the keys the player moves by whole seconds, so the slider's
* 0.01 s step never applies to an arrow key.
*/
@onEvent({ selector: '[data-seek]', type: 'keydown', options: { capture: true } })
onSeekKey(event: KeyboardEvent): void {
const seconds = seekFromKey(event.key);
if (seconds === undefined) return;
event.preventDefault();
event.stopPropagation();
this.wake();
this.media.skip(seconds);
}
override render() {
return (
<>
<div
data-stage
data-state={this.stage}
data-controls-hidden={this.controlsHidden ? '' : undefined}
role="group"
aria-label="Video player"
aria-describedby="video-player-app-help"
tabindex="0"
on:keydown={(event: KeyboardEvent) => this.onKey(event)}
on:pointermove={(event: PointerEvent) => this.onActivity(event)}
on:pointerdown={(event: PointerEvent) => this.onActivity(event)}
on:pointerleave={(event: PointerEvent) => this.onActivity(event)}
>
<video
data-video
data-src={VIDEO.src}
poster={VIDEO.poster}
preload="metadata"
playsinline
on:pointerdown={(event: PointerEvent) => (this.pointer = event.pointerType)}
on:click={() => this.onVideoClick()}
on:dblclick={() => this.toggleFullscreen()}
></video>
<RuiButton
size="lg"
square
data-big-play
aria-hidden="true"
tabindex="-1"
on:click={() => void this.media.toggle()}
>
<svg viewBox="0 0 24 24" width="28" height="28" aria-hidden="true" focusable="false">
<path d="M8 5v14l11-7z" fill="currentColor" />
</svg>
</RuiButton>
<span data-spinner aria-hidden="true"></span>
<div data-error hidden={this.stage !== 'error'}>
<p data-error-message>Could not load the video</p>
<RuiButton size="sm" data-retry on:click={() => void this.media.retry()}>
Retry
</RuiButton>
</div>
<div data-controls>
<RuiButton
variant="ghost"
square
data-playback
aria-label="Play"
pressed={this.playing}
on:click={() => void this.media.toggle()}
>
<svg
viewBox="0 0 24 24"
width="18"
height="18"
aria-hidden="true"
focusable="false"
data-icon="play"
>
<path d="M8 5v14l11-7z" fill="currentColor" />
</svg>
<svg
viewBox="0 0 24 24"
width="18"
height="18"
aria-hidden="true"
focusable="false"
data-icon="pause"
>
<path d="M6 5h4v14H6zM14 5h4v14h-4z" fill="currentColor" />
</svg>
</RuiButton>
<div data-scrub>
<span data-elapsed>{this.$.elapsed}</span>
<RuiSlider
data-seek
label="Seek"
min={0}
max={this.seekMax}
step={0.01}
value={this.position}
disabled={!this.ready}
on:rui-change={(event: Event) => this.onSeek(event)}
/>
<span data-duration>{this.$.total}</span>
</div>
<RuiButton
variant="ghost"
square
data-mute
aria-label="Mute"
pressed={this.muted}
on:click={() => this.media.toggleMuted()}
>
<svg
viewBox="0 0 24 24"
width="18"
height="18"
aria-hidden="true"
focusable="false"
data-icon="volume"
>
<path d="M4 9v6h4l5 4V5L8 9z" fill="currentColor" />
<path
d="M16 9a4 4 0 0 1 0 6"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
<svg
viewBox="0 0 24 24"
width="18"
height="18"
aria-hidden="true"
focusable="false"
data-icon="muted"
>
<path d="M4 9v6h4l5 4V5L8 9z" fill="currentColor" />
<path
d="M16.5 9.5l5 5M21.5 9.5l-5 5"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</RuiButton>
<div data-volume>
<RuiSlider
data-volume-input
label="Volume"
min={0}
max={1}
step={0.05}
value={this.level}
on:rui-change={(event: Event) => this.onVolume(event)}
/>
</div>
<RuiButton
variant="ghost"
data-rate
aria-label={`Speed ${this.rate}x`}
on:click={() => this.cycleRate()}
>
{`${this.rate}x`}
</RuiButton>
<RuiButton
variant="ghost"
square
data-captions
aria-label="Captions"
pressed={this.captionsOn}
on:click={() => this.toggleCaptions()}
>
<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false">
<rect
x="3"
y="5"
width="18"
height="14"
rx="2"
fill="none"
stroke="currentColor"
stroke-width="2"
/>
<path
d="M10.5 10.5a2 2 0 1 0 0 3M17 10.5a2 2 0 1 0 0 3"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</RuiButton>
<RuiButton
variant="ghost"
square
data-fullscreen
aria-label="Fullscreen"
hidden={!this.fullscreenAvailable}
pressed={this.fullscreen}
on:click={() => this.toggleFullscreen()}
>
<svg
viewBox="0 0 24 24"
width="18"
height="18"
aria-hidden="true"
focusable="false"
data-icon="enter"
>
<path
d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
<svg
viewBox="0 0 24 24"
width="18"
height="18"
aria-hidden="true"
focusable="false"
data-icon="exit"
>
<path
d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</RuiButton>
</div>
<p data-status aria-live="polite">
{this.$.status}
</p>
</div>
<span data-help hidden id="video-player-app-help">
{HELP}
</span>
</>
);
}
}import type { MediaState } from '@ecopages/radiant-ui/controllers';
import { formatMediaTime } from '@ecopages/radiant-ui/helpers';
/** The sample clip and its poster, made by `scripts/generate-video-player-assets.mjs`. */
export const VIDEO = {
src: '/assets/video/radiant-reel.webm',
poster: '/assets/video/radiant-reel.jpg',
} as const;
/** The English captions of the clip, one for each of its five scenes, in seconds. */
export const CAPTIONS: readonly { start: number; end: number; text: string }[] = [
{ start: 0.2, end: 2.3, text: 'Scene one: a slow start' },
{ start: 2.6, end: 4.7, text: 'Scene two: the shapes arrive' },
{ start: 5, end: 7.1, text: 'Scene three: everything turns' },
{ start: 7.4, end: 9.5, text: 'Scene four: the light moves on' },
{ start: 9.8, end: 11.9, text: 'Scene five: and it settles' },
];
/**
* The playback rates the speed button cycles through, as the strings `cycleValue` works on, and the value the
* button shows with an `x`.
*/
export const RATES: readonly string[] = ['1', '1.25', '1.5', '2', '0.5'];
/** Seconds the arrow keys move the playback by, on the seek thumb and on the player. */
export const SEEK_STEP = 5;
/** Seconds `J`, `L`, Page Up and Page Down move the playback by. */
export const LONG_SEEK_STEP = 10;
/** The fraction of the full volume the arrow keys change it by. */
export const VOLUME_STEP = 0.1;
/** Milliseconds without a pointer or key event after which the controls hide while the video plays. */
export const HIDE_CONTROLS_MS = 2500;
/** What the stage shows: `data-state` on `[data-stage]` carries one of these and the stylesheet draws from it. */
export type StageState = 'idle' | 'buffering' | 'playing' | 'paused' | 'error';
/** What a shortcut asks the player to do. */
export type Shortcut =
| { type: 'toggle' }
| { type: 'skip'; seconds: number }
| { type: 'volume'; delta: number }
| { type: 'mute' }
| { type: 'captions' }
| { type: 'fullscreen' }
| { type: 'jump'; fraction: number }
| { type: 'start' }
| { type: 'end' };
const SHORTCUTS = new Map<string, Shortcut>([
[' ', { type: 'toggle' }],
['k', { type: 'toggle' }],
['j', { type: 'skip', seconds: -LONG_SEEK_STEP }],
['l', { type: 'skip', seconds: LONG_SEEK_STEP }],
['ArrowLeft', { type: 'skip', seconds: -SEEK_STEP }],
['ArrowRight', { type: 'skip', seconds: SEEK_STEP }],
['ArrowUp', { type: 'volume', delta: VOLUME_STEP }],
['ArrowDown', { type: 'volume', delta: -VOLUME_STEP }],
['m', { type: 'mute' }],
['c', { type: 'captions' }],
['f', { type: 'fullscreen' }],
['Home', { type: 'start' }],
['End', { type: 'end' }],
...Array.from({ length: 10 }, (_, digit): [string, Shortcut] => [
String(digit),
{ type: 'jump', fraction: digit / 10 },
]),
]);
const SLIDER_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'PageUp', 'PageDown']);
/**
* The shortcut a key event asks for, or `undefined` when the player must leave it alone.
*
* @remarks
* A key that carries Ctrl, Alt or Meta belongs to the browser. A button owns Space and Enter, which activate it. A
* slider thumb owns the arrows, Home, End and the page keys, which move it; the letters and digits still reach the
* player. The target is the element the key was pressed on, which a `keydown` listener on the stage always has.
*/
export function shortcutFor(
event: Pick<KeyboardEvent, 'key' | 'ctrlKey' | 'altKey' | 'metaKey' | 'target'>,
): Shortcut | undefined {
if (event.ctrlKey || event.altKey || event.metaKey) return undefined;
const target = event.target as Element;
if (target.closest('button') && (event.key === ' ' || event.key === 'Enter')) return undefined;
if (target.closest('[role="slider"]') && SLIDER_KEYS.has(event.key)) return undefined;
return SHORTCUTS.get(event.key.length === 1 ? event.key.toLowerCase() : event.key);
}
const SEEK_KEYS = new Map([
['ArrowRight', SEEK_STEP],
['ArrowUp', SEEK_STEP],
['ArrowLeft', -SEEK_STEP],
['ArrowDown', -SEEK_STEP],
['PageUp', LONG_SEEK_STEP],
['PageDown', -LONG_SEEK_STEP],
]);
/**
* Seconds a key moves the seek slider by, or `undefined` for any other key.
*
* @remarks
* The slider works in seconds with a step of 0.01, fine enough that the per-frame position write is not rounded and
* the thumb glides. A step that fine would make an arrow key inaudible, so the player handles these keys and the
* slider keeps Home and End.
*/
export function seekFromKey(key: string): number | undefined {
return SEEK_KEYS.get(key);
}
/** The state of the stage for a snapshot of the media element. */
export function stageState(state: Pick<MediaState, 'status' | 'waiting' | 'error'>): StageState {
if (state.error) return 'error';
if (state.waiting || state.status === 'loading') return 'buffering';
if (state.status === 'idle') return 'idle';
return state.status === 'playing' ? 'playing' : 'paused';
}
/** The text a snapshot is worth in the polite live region, `''` while there is nothing to say. */
export function statusMessage(state: Pick<MediaState, 'status' | 'waiting' | 'error' | 'blocked'>): string {
if (state.blocked) return 'Playback was blocked, press Play to start';
switch (stageState(state)) {
case 'error':
return 'Could not load the video';
case 'buffering':
return 'Buffering';
case 'playing':
return 'Playing';
case 'paused':
return state.status === 'ended' ? 'Ended' : 'Paused';
default:
return '';
}
}
/**
* Decides what the polite live region says.
*
* @remarks
* The player says nothing while the clip loads on its own: "Buffering" and "Paused" at page load, or after the
* player was moved, are noise to a reader who has done nothing yet. It starts to report once the clip has played,
* and a failure ("Could not load", "Playback was blocked") is always reported, because it answers an action or
* leaves the player unusable. A message is said once until it changes.
*/
export class Announcer {
private spoken = '';
private started = false;
/** Forgets what was said and silences the player again, for a clip that loads from the start. */
reset(): void {
this.spoken = '';
this.started = false;
}
/** The message to say for this snapshot, or `''` when there is nothing new to say. */
next(state: Pick<MediaState, 'status' | 'waiting' | 'error' | 'blocked'>): string {
if (state.status === 'playing') this.started = true;
const message = this.started || state.error || state.blocked ? statusMessage(state) : '';
if (message === this.spoken) return '';
this.spoken = message;
return message;
}
}
/** The `aria-valuetext` of the seek thumb, such as `1:15 of 4:00`. */
export function seekValueText(position: number, duration: number): string {
return `${formatMediaTime(position)} of ${formatMediaTime(duration)}`;
}
/** One buffered range as the percentages the stylesheet draws it with. */
export type BufferedSegment = { start: number; size: number };
/** The buffered ranges as percentages of the duration, empty until the duration is known. */
export function bufferedSegments(ranges: readonly (readonly [number, number])[], duration: number): BufferedSegment[] {
if (!Number.isFinite(duration) || duration <= 0) return [];
return ranges.map(([from, to]) => ({
start: (from / duration) * 100,
size: ((Math.min(to, duration) - from) / duration) * 100,
}));
}const inFlight = new Map<string, Promise<Blob>>();
function download(url: string): Promise<Blob> {
let pending = inFlight.get(url);
if (!pending) {
pending = fetchBlob(url).finally(() => inFlight.delete(url));
inFlight.set(url, pending);
}
return pending;
}
async function fetchBlob(url: string): Promise<Blob> {
const response = await fetch(url);
if (!response.ok) throw new Error(`${response.status} ${response.statusText} for ${url}`);
return response.blob();
}
/**
* Fetches a video into a `Blob` and returns an object URL, for `MediaController`'s `resolveSource`.
*
* @remarks
* A media element can only seek in a file whose server answers range requests, and many development and preview
* servers (this site's among them) do not: the element then reports nothing seekable and every seek snaps back to
* the start. The sample clip is about a megabyte, so it is fetched whole and played from memory, which always
* seeks. For long media serve the file with range support and pass its URL to `load()` without a `resolveSource`.
* A failed request rejects, which puts the controller in its `error` state; `retry()` calls this again.
*
* Requests for a url that is still downloading share one download, and each caller gets an object URL of its own.
* The page swaps the authoring pattern of a recipe by mounting the new form as soon as the old one is on the page,
* which would otherwise fetch the clip twice, and a shared object URL would be revoked under the form that is left
* running when the other releases it. A finished download is not kept, so a retry or a player that is moved asks the
* server again.
*/
export async function fetchSource(url: string): Promise<string> {
return URL.createObjectURL(await download(url));
}
/** Frees an object URL `fetchSource` made; `MediaController` calls it as `releaseSource` once the element has let go of it. */
export function releaseSource(url: string): void {
URL.revokeObjectURL(url);
}.primitive-example:is(
[data-example='video-player'],
:has(> video-player-element, > [data-controller='video-player'], > video-player-app)
) {
display: block;
width: min(100%, 44rem);
& :where([data-stage]) {
position: relative;
overflow: hidden;
box-sizing: border-box;
aspect-ratio: 16 / 9;
border-radius: var(--radius-container);
background: #000;
color: #fff;
box-shadow: var(--shadow-overlay);
container-type: inline-size;
user-select: none;
}
& :where([data-stage]:focus-visible) {
outline: 2px solid var(--focus-ring);
outline-offset: 2px;
}
& :where([data-stage]:fullscreen) {
aspect-ratio: auto;
inline-size: 100%;
block-size: 100%;
border-radius: 0;
}
& :where([data-stage]:fullscreen:focus-visible) {
outline-offset: -4px;
}
/* The ring is drawn over the picture, so it is white, which stands out from the dark bar and the error panel. */
& :where([data-controls], [data-error]) {
--focus-ring: #fff;
}
& :where([data-stage][data-controls-hidden][data-state='playing']) {
cursor: none;
}
& :where([data-video]) {
display: block;
inline-size: 100%;
block-size: 100%;
object-fit: contain;
cursor: pointer;
}
& :where([data-big-play]) {
position: absolute;
inset: 50% auto auto 50%;
translate: -50% -50%;
inline-size: calc(var(--size-control-lg) * 1.75);
block-size: calc(var(--size-control-lg) * 1.75);
border-radius: var(--radius-full);
box-shadow: var(--shadow-overlay);
opacity: 0;
pointer-events: none;
transition-property: opacity, scale;
transition-duration: var(--duration-normal);
transition-timing-function: var(--ease-out-strong);
scale: 0.9;
}
& :where([data-stage]:is([data-state='paused'], [data-state='idle']) [data-big-play]) {
opacity: 1;
pointer-events: auto;
scale: 1;
}
& :where([data-stage][data-state='idle'] [data-big-play]) {
opacity: 0.6;
}
& :where([data-spinner]) {
position: absolute;
inset: 50% auto auto 50%;
translate: -50% -50%;
box-sizing: border-box;
inline-size: calc(var(--size-control-lg) * 1.1);
block-size: calc(var(--size-control-lg) * 1.1);
border: 3px solid rgb(255 255 255 / 0.3);
border-block-start-color: #fff;
border-radius: var(--radius-full);
opacity: 0;
pointer-events: none;
transition: opacity var(--duration-normal) var(--ease-out-strong);
}
& :where([data-stage][data-state='buffering'] [data-spinner]) {
opacity: 1;
animation: video-player-spin 0.9s linear infinite;
}
& :where([data-error]:not([hidden])) {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: var(--space-4);
padding: var(--space-4);
background: color-mix(in srgb, #000 78%, transparent);
text-align: center;
}
& :where([data-error-message]) {
margin: 0;
}
& :where([data-video])::cue {
background: rgb(0 0 0 / 0.72);
color: #fff;
font-size: 1rem;
}
& :where([data-controls]) {
position: absolute;
inset: auto 0 0;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1) var(--space-2);
padding: var(--space-8) var(--space-3) var(--space-2);
background: linear-gradient(to top, rgb(0 0 0 / 0.78), rgb(0 0 0 / 0));
transition-property: opacity, translate;
transition-duration: var(--duration-normal);
transition-timing-function: var(--ease-out-strong);
}
& :where([data-stage][data-controls-hidden][data-state='playing'] [data-controls]) {
opacity: 0;
translate: 0 var(--space-2);
pointer-events: none;
}
& :where([data-controls] .rui-button--ghost) {
color: #fff;
}
@media (hover: hover) {
& :where([data-controls] .rui-button--ghost:hover:not(:disabled)) {
background: rgb(255 255 255 / 0.18);
}
}
& :where([data-controls] .rui-button--ghost:active:not(:disabled)) {
background: rgb(255 255 255 / 0.28);
}
/* The macOS themes draw a pressed button with a ring, which the inset bar replaces. */
& :where([data-controls] .rui-button--ghost[aria-pressed='true']) {
background: rgb(255 255 255 / 0.2);
color: #fff;
box-shadow: inset 0 -2px 0 var(--primary);
--tw-ring-shadow: 0 0 #0000;
}
& :where([data-rate]) {
min-inline-size: 3.25rem;
font-variant-numeric: tabular-nums;
}
& [data-playback] [data-icon='pause'],
& [data-playback][aria-pressed='true'] [data-icon='play'],
& [data-mute] [data-icon='muted'],
& [data-mute][aria-pressed='true'] [data-icon='volume'],
& [data-fullscreen] [data-icon='exit'],
& [data-fullscreen][aria-pressed='true'] [data-icon='enter'] {
display: none;
}
& [data-playback][aria-pressed='true'] [data-icon='pause'],
& [data-mute][aria-pressed='true'] [data-icon='muted'],
& [data-fullscreen][aria-pressed='true'] [data-icon='exit'] {
display: block;
}
& :where([data-fullscreen][hidden]) {
display: none;
}
& :where([data-scrub]) {
display: flex;
flex: 1 1 14rem;
align-items: center;
gap: var(--space-3);
min-inline-size: 0;
}
& :where([data-elapsed], [data-duration]) {
min-inline-size: 2.5ch;
font-size: 0.75rem;
font-variant-numeric: tabular-nums;
opacity: 0.85;
}
& :where([data-volume]) {
display: flex;
flex: 0 0 5.5rem;
align-items: center;
}
& :where([data-scrub] rui-slider, [data-volume] rui-slider),
& :where([data-scrub], [data-volume]) .rui-slider {
--rui-slider-track-length: 100%;
--rui-slider-track-color: rgb(255 255 255 / 0.28);
--rui-slider-fill-color: #fff;
--rui-slider-thumb-size: 0.875rem;
--rui-slider-thumb-background: #fff;
--rui-slider-thumb-border-color: #fff;
}
& :where([data-scrub] rui-slider, [data-volume] rui-slider) {
flex: 1;
min-inline-size: 0;
margin-inline: calc(var(--rui-slider-thumb-size) / 2);
}
& :where([data-scrub] .rui-slider__range-track) {
overflow: visible;
}
& .rui-slider__header {
display: none;
}
& :where([data-buffered]) {
position: absolute;
inset-block: 0;
inset-inline: 0;
border-radius: var(--rui-slider-track-radius, var(--radius-control));
overflow: hidden;
pointer-events: none;
}
& :where([data-buffered] i) {
position: absolute;
inset-block: 0;
inset-inline-start: calc(var(--start) * 1%);
inline-size: calc(var(--size) * 1%);
background: rgb(255 255 255 / 0.4);
}
& :where([data-status]) {
position: absolute;
inline-size: 1px;
block-size: 1px;
margin: 0;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
@container (max-width: 30rem) {
& :where([data-volume]) {
display: none;
}
}
@media (prefers-reduced-motion: reduce) {
& :where([data-controls], [data-big-play], [data-spinner]) {
transition: none;
}
& :where([data-stage][data-state='buffering'] [data-spinner]) {
animation: none;
}
}
}
@keyframes video-player-spin {
to {
rotate: 360deg;
}
}The sliders are RuiSlider and the buttons RuiButton, composed in JSX, so their markup comes from the helpers and the buttons are controlled: pressed follows @state, and the labels stay fixed. The stage state, the pressed buttons, the speed and whether the seek bar is enabled are @state written from onState; @query finds the video, the stage, the controls and the sliders, and the handlers are JSX on:* attributes, with the media events left to createMediaController(this, ...). The one exception is the seek key handler, a delegated @onEvent in the capture phase, because it has to run before the slider's own.
Nothing that changes every frame goes through render(): the clock and the status are bound with this.$, and onProgress writes the seek position, the volume, the thumb's aria-valuetext and the buffered bar to the DOM by hand, so a playing video never redraws the controls. RuiSlider has no region for the buffered bar, so updated() adds the layer to the seek track and puts it back if a render drops it; the same hook watches the thumb with a MutationObserver. The hide timer and the thumb observer are stopped by a callback registered once in the constructor with registerCleanupCallback, because one registered in onConnected would be added again on every move; createCaptionsController(this, ...) and createMediaController(this, ...) attach before the first render, when the video does not exist and getMedia returns null, so onConnected calls captions.refresh() and media.attach() once the video is drawn; fullscreenchange is a document-level @onEvent, which goes with the element. The fullscreen button is hidden from document.fullscreenEnabled, which onConnected reads into @state, so render() never touches the document. data-controls-hidden and the fullscreen button's aria-pressed are written to the DOM at once and kept in fields that render() reads, because a render is deferred and a touch tap or a fullscreenchange must show in the same turn.
The playback is destroyed with the element, and moving the element to another parent loads the clip again, paused at the start, from onConnected. Compared with the Radiant element above, the markup lives inside the class, so there is nothing to keep in step with the page, but restyling the structure means editing it, and this docs build prerenders the tag empty and the client draws it, so the page shows nothing until the script loads.
The same player as a RadiantController attached to the authored markup, which carries data-controller="video-player" on a plain div.
Could not load the video
import { RadiantController, bindTo, controller, onEvent, query, state } from '@ecopages/radiant';
import { createCaptionsController, createMediaController, type MediaState } from '@ecopages/radiant-ui/controllers';
import '@ecopages/radiant-ui/slider';
import type { RuiSliderChangeDetail, RuiSliderElement } from '@ecopages/radiant-ui/slider';
import { cycleValue, formatMediaTime } from '@ecopages/radiant-ui/helpers';
import {
Announcer,
CAPTIONS,
HIDE_CONTROLS_MS,
RATES,
bufferedSegments,
seekFromKey,
seekValueText,
shortcutFor,
stageState,
type Shortcut,
type StageState,
} from './video-player.data';
import { fetchSource, releaseSource } from './video-player.loader';
/**
* @remarks
* The same player as the element form on a `RadiantController`, attached by the registry to the authored
* `data-controller="video-player"` markup, with `connect()` in place of `onConnected()`. What the page shows that is
* a plain copy of the media state (the stage state, whether the controls are hidden, the pressed buttons, the clock,
* the status, the speed, the error panel) is a `@state` field that `@bindTo` writes onto the markup; the buffered
* bar and the slider values are written here because they are not a copy of one value.
*
* `createMediaController(this, ...)` takes the controller as its host and attaches and destroys with it. The timer,
* and the thumb observer are stopped by a callback registered once in the constructor, because
* one registered in `connect()` would be added again on every reconnect, and `connect()` starts the load again when
* the element is moved. Each pointer listener is delegated on the host, and `pointerleave`, which does not bubble,
* is delegated in the capture phase.
*/
@controller('video-player')
export class VideoPlayerController extends RadiantController {
@query({ selector: '[data-stage]' }) private stage!: HTMLElement;
@query({ selector: '[data-video]' }) private video!: HTMLVideoElement;
@query({ selector: '[data-controls]' }) private controls!: HTMLElement;
@query({ selector: '[data-seek]' }) private seek!: RuiSliderElement;
@query({ selector: '[data-seek] [role="slider"]' }) private seekThumb!: HTMLElement;
@query({ selector: '[data-volume-input]' }) private volume!: RuiSliderElement;
@query({ selector: '[data-buffered]' }) private buffered!: HTMLElement;
@query({ selector: '[data-fullscreen]' }) private fullscreen!: HTMLButtonElement;
@state
@bindTo({ selector: '[data-stage]', attr: 'data-state' })
stageState: StageState = 'idle';
@state
@bindTo({ selector: '[data-stage]', bool: 'data-controls-hidden' })
controlsHidden = false;
@state
@bindTo({ selector: '[data-playback]', attr: 'aria-pressed', map: (value) => String(value) })
playing = false;
@state
@bindTo({ selector: '[data-mute]', attr: 'aria-pressed', map: (value) => String(value) })
muted = false;
@state
@bindTo({ selector: '[data-captions]', attr: 'aria-pressed', map: (value) => String(value) })
captionsOn = false;
@state
@bindTo({ selector: '[data-fullscreen]', attr: 'aria-pressed', map: (value) => String(value) })
fullscreenOn = false;
@state
@bindTo([
{ selector: '[data-rate]', text: true, map: (rate) => `${rate}x` },
{ selector: '[data-rate]', attr: 'aria-label', map: (rate) => `Speed ${rate}x` },
])
rate = 1;
@state
@bindTo({ selector: '[data-elapsed]', text: true })
elapsed = '0:00';
@state
@bindTo({ selector: '[data-duration]', text: true })
total = '0:00';
@state
@bindTo({ selector: '[data-status]', text: true })
status = '';
@state
@bindTo({ selector: '[data-seek]', bool: 'disabled', invert: true })
seekable = false;
@state
@bindTo({ selector: '[data-error]', bool: 'hidden', invert: true })
failed = false;
private hideTimer: ReturnType<typeof setTimeout> | undefined;
private pointer = 'mouse';
private bufferedKey = '';
private valueText = '';
private readonly announcer = new Announcer();
private readonly valueTextObserver = new MutationObserver(() => this.keepValueText());
private readonly captions = createCaptionsController(this, {
getMedia: () => this.video,
getAvoid: () => this.controls,
tracks: [{ language: 'en', label: 'English', cues: CAPTIONS }],
onState: (state) => {
this.captionsOn = state.enabled;
},
});
private readonly media = createMediaController(this, {
getMedia: () => this.video,
resolveSource: fetchSource,
releaseSource,
clearSourceOnDestroy: true,
onState: (state) => this.renderState(state),
onProgress: (state) => this.renderProgress(state),
});
constructor(host: Element) {
super(host);
this.registerCleanupCallback(() => {
clearTimeout(this.hideTimer);
this.valueTextObserver.disconnect();
});
}
override connect(): void {
super.connect();
this.valueTextObserver.observe(this.seekThumb, { attributes: true, attributeFilter: ['aria-valuetext'] });
this.fullscreen.hidden = !document.fullscreenEnabled;
this.captions.disable();
this.announcer.reset();
void this.media.load(this.video.dataset.src!);
}
/**
* Writes the clock, the seek thumb and the buffered bar.
*
* @remarks
* The slider repaints in a later update with its own `aria-valuetext`, a bare number of seconds, so the text is
* kept by the observer as well as written here.
*/
private renderProgress(state: MediaState): void {
if (Number.isFinite(state.duration) && this.seek.max !== state.duration) this.seek.max = state.duration;
this.seek.value = [state.position];
this.valueText = seekValueText(state.position, state.duration);
this.keepValueText();
this.elapsed = formatMediaTime(state.position);
this.total = formatMediaTime(state.duration);
const segments = bufferedSegments(state.bufferedRanges, state.duration);
const key = JSON.stringify(segments);
if (key !== this.bufferedKey) {
this.bufferedKey = key;
this.buffered.replaceChildren(
...segments.map(({ start, size }) => {
const segment = document.createElement('i');
segment.style.setProperty('--start', String(start));
segment.style.setProperty('--size', String(size));
return segment;
}),
);
}
}
private keepValueText(): void {
if (this.seekThumb.getAttribute('aria-valuetext') !== this.valueText) {
this.seekThumb.setAttribute('aria-valuetext', this.valueText);
}
}
private renderState(state: MediaState): void {
const shown = stageState(state);
const message = this.announcer.next(state);
this.stageState = shown;
this.playing = state.status === 'playing';
this.muted = state.muted;
this.volume.value = [state.muted ? 0 : state.volume];
this.rate = state.rate;
this.seekable = state.seekable;
this.failed = shown === 'error';
if (message !== '') this.status = message;
this.renderProgress(state);
this.wake();
}
/**
* Shows the controls and, while the video plays, hides them again after `HIDE_CONTROLS_MS` of quiet. They stay
* while the pointer is over them or a control has keyboard focus, so a reader who is aiming at one never loses it.
*/
private wake(): void {
clearTimeout(this.hideTimer);
this.controlsHidden = false;
if (this.stageState !== 'playing') return;
this.hideTimer = setTimeout(() => {
if (this.controls.matches(':hover') || this.controls.querySelector(':focus-visible')) return this.wake();
this.controlsHidden = true;
}, HIDE_CONTROLS_MS);
}
private toggleCaptions(): void {
this.captions.toggle();
this.status = this.captionsOn ? 'Captions on' : 'Captions off';
}
/**
* Both calls reject when the browser refuses (no user gesture, a sandboxed frame), and the player has nothing to
* show for it: the button only follows `fullscreenchange`.
*/
private toggleFullscreen(): void {
const request =
document.fullscreenElement === this.stage ? document.exitFullscreen() : this.stage.requestFullscreen();
request.catch(() => undefined);
}
private run(shortcut: Shortcut): void {
const state = this.media.getState();
switch (shortcut.type) {
case 'toggle':
return void this.media.toggle();
case 'skip':
return this.media.skip(shortcut.seconds);
case 'volume': {
const next = Math.round((state.volume + shortcut.delta) * 100) / 100;
if (shortcut.delta > 0 && state.muted) this.media.setMuted(false);
this.media.setVolume(next);
this.status = `Volume ${Math.round(this.media.getState().volume * 100)}%`;
return;
}
case 'mute':
return this.media.toggleMuted();
case 'captions':
return this.toggleCaptions();
case 'fullscreen':
return this.toggleFullscreen();
case 'jump':
return this.media.seek(state.duration * shortcut.fraction);
case 'start':
return this.media.seek(0);
case 'end':
return this.media.seek(state.duration);
}
}
@onEvent({ selector: '[data-stage]', type: 'keydown' })
shortcut(event: Event): void {
this.wake();
const shortcut = shortcutFor(event as KeyboardEvent);
if (!shortcut) return;
event.preventDefault();
this.run(shortcut);
}
/**
* A touch on the video is a tap that shows or hides the controls, which `tapVideo` decides, so it is not
* activity here.
*/
@onEvent({ selector: '[data-stage]', type: 'pointermove' })
@onEvent({ selector: '[data-stage]', type: 'pointerdown' })
@onEvent({ selector: '[data-stage]', type: 'pointerleave', options: { capture: true } })
activity(event: Event): void {
const { target, pointerType } = event as PointerEvent;
if (target !== this.video || pointerType !== 'touch') this.wake();
}
@onEvent({ selector: '[data-video]', type: 'pointerdown' })
rememberPointer(event: Event): void {
this.pointer = (event as PointerEvent).pointerType;
}
@onEvent({ selector: '[data-video]', type: 'click' })
tapVideo(): void {
if (this.pointer === 'touch' && this.stageState === 'playing') {
if (this.controlsHidden) this.wake();
else this.controlsHidden = true;
} else void this.media.toggle();
}
@onEvent({ selector: '[data-video]', type: 'dblclick' })
@onEvent({ selector: '[data-fullscreen]', type: 'click' })
enterFullscreen(): void {
this.toggleFullscreen();
}
@onEvent({ selector: '[data-big-play]', type: 'click' })
@onEvent({ selector: '[data-playback]', type: 'click' })
togglePlayback(): void {
void this.media.toggle();
}
@onEvent({ selector: '[data-mute]', type: 'click' })
toggleMute(): void {
this.media.toggleMuted();
}
@onEvent({ selector: '[data-rate]', type: 'click' })
cycleRate(): void {
this.media.setRate(Number(cycleValue(RATES, String(this.media.getState().rate))));
this.status = `Speed ${this.media.getState().rate}x`;
}
@onEvent({ selector: '[data-captions]', type: 'click' })
pressCaptions(): void {
this.toggleCaptions();
}
@onEvent({ selector: '[data-retry]', type: 'click' })
retry(): void {
void this.media.retry();
}
@onEvent({ document: true, type: 'fullscreenchange' })
followFullscreen(): void {
this.fullscreenOn = document.fullscreenElement === this.stage;
}
/** The slider works in seconds and reports `rui-change` only for the reader, never for a position written to it. */
@onEvent({ selector: '[data-seek]', type: 'rui-change' })
scrub(event: Event): void {
this.media.scrub((event as CustomEvent<RuiSliderChangeDetail>).detail.value[0]);
}
/**
* Delegated in the capture phase, which runs before the slider's own key handler and lets this stop it for the
* keys the player moves by whole seconds, so the slider's 0.01 s step never applies to an arrow key. Home and
* End are left to the slider.
*/
@onEvent({ selector: '[data-seek]', type: 'keydown', options: { capture: true } })
scrubWithKey(event: Event): void {
const key = event as KeyboardEvent;
const seconds = seekFromKey(key.key);
if (seconds === undefined) return;
key.preventDefault();
key.stopPropagation();
this.wake();
this.media.skip(seconds);
}
@onEvent({ selector: '[data-volume-input]', type: 'rui-change' })
setVolume(event: Event): void {
const level = (event as CustomEvent<RuiSliderChangeDetail>).detail.value[0];
this.media.setVolume(level);
if (level > 0) this.media.setMuted(false);
}
}import type { MediaState } from '@ecopages/radiant-ui/controllers';
import { formatMediaTime } from '@ecopages/radiant-ui/helpers';
/** The sample clip and its poster, made by `scripts/generate-video-player-assets.mjs`. */
export const VIDEO = {
src: '/assets/video/radiant-reel.webm',
poster: '/assets/video/radiant-reel.jpg',
} as const;
/** The English captions of the clip, one for each of its five scenes, in seconds. */
export const CAPTIONS: readonly { start: number; end: number; text: string }[] = [
{ start: 0.2, end: 2.3, text: 'Scene one: a slow start' },
{ start: 2.6, end: 4.7, text: 'Scene two: the shapes arrive' },
{ start: 5, end: 7.1, text: 'Scene three: everything turns' },
{ start: 7.4, end: 9.5, text: 'Scene four: the light moves on' },
{ start: 9.8, end: 11.9, text: 'Scene five: and it settles' },
];
/**
* The playback rates the speed button cycles through, as the strings `cycleValue` works on, and the value the
* button shows with an `x`.
*/
export const RATES: readonly string[] = ['1', '1.25', '1.5', '2', '0.5'];
/** Seconds the arrow keys move the playback by, on the seek thumb and on the player. */
export const SEEK_STEP = 5;
/** Seconds `J`, `L`, Page Up and Page Down move the playback by. */
export const LONG_SEEK_STEP = 10;
/** The fraction of the full volume the arrow keys change it by. */
export const VOLUME_STEP = 0.1;
/** Milliseconds without a pointer or key event after which the controls hide while the video plays. */
export const HIDE_CONTROLS_MS = 2500;
/** What the stage shows: `data-state` on `[data-stage]` carries one of these and the stylesheet draws from it. */
export type StageState = 'idle' | 'buffering' | 'playing' | 'paused' | 'error';
/** What a shortcut asks the player to do. */
export type Shortcut =
| { type: 'toggle' }
| { type: 'skip'; seconds: number }
| { type: 'volume'; delta: number }
| { type: 'mute' }
| { type: 'captions' }
| { type: 'fullscreen' }
| { type: 'jump'; fraction: number }
| { type: 'start' }
| { type: 'end' };
const SHORTCUTS = new Map<string, Shortcut>([
[' ', { type: 'toggle' }],
['k', { type: 'toggle' }],
['j', { type: 'skip', seconds: -LONG_SEEK_STEP }],
['l', { type: 'skip', seconds: LONG_SEEK_STEP }],
['ArrowLeft', { type: 'skip', seconds: -SEEK_STEP }],
['ArrowRight', { type: 'skip', seconds: SEEK_STEP }],
['ArrowUp', { type: 'volume', delta: VOLUME_STEP }],
['ArrowDown', { type: 'volume', delta: -VOLUME_STEP }],
['m', { type: 'mute' }],
['c', { type: 'captions' }],
['f', { type: 'fullscreen' }],
['Home', { type: 'start' }],
['End', { type: 'end' }],
...Array.from({ length: 10 }, (_, digit): [string, Shortcut] => [
String(digit),
{ type: 'jump', fraction: digit / 10 },
]),
]);
const SLIDER_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'PageUp', 'PageDown']);
/**
* The shortcut a key event asks for, or `undefined` when the player must leave it alone.
*
* @remarks
* A key that carries Ctrl, Alt or Meta belongs to the browser. A button owns Space and Enter, which activate it. A
* slider thumb owns the arrows, Home, End and the page keys, which move it; the letters and digits still reach the
* player. The target is the element the key was pressed on, which a `keydown` listener on the stage always has.
*/
export function shortcutFor(
event: Pick<KeyboardEvent, 'key' | 'ctrlKey' | 'altKey' | 'metaKey' | 'target'>,
): Shortcut | undefined {
if (event.ctrlKey || event.altKey || event.metaKey) return undefined;
const target = event.target as Element;
if (target.closest('button') && (event.key === ' ' || event.key === 'Enter')) return undefined;
if (target.closest('[role="slider"]') && SLIDER_KEYS.has(event.key)) return undefined;
return SHORTCUTS.get(event.key.length === 1 ? event.key.toLowerCase() : event.key);
}
const SEEK_KEYS = new Map([
['ArrowRight', SEEK_STEP],
['ArrowUp', SEEK_STEP],
['ArrowLeft', -SEEK_STEP],
['ArrowDown', -SEEK_STEP],
['PageUp', LONG_SEEK_STEP],
['PageDown', -LONG_SEEK_STEP],
]);
/**
* Seconds a key moves the seek slider by, or `undefined` for any other key.
*
* @remarks
* The slider works in seconds with a step of 0.01, fine enough that the per-frame position write is not rounded and
* the thumb glides. A step that fine would make an arrow key inaudible, so the player handles these keys and the
* slider keeps Home and End.
*/
export function seekFromKey(key: string): number | undefined {
return SEEK_KEYS.get(key);
}
/** The state of the stage for a snapshot of the media element. */
export function stageState(state: Pick<MediaState, 'status' | 'waiting' | 'error'>): StageState {
if (state.error) return 'error';
if (state.waiting || state.status === 'loading') return 'buffering';
if (state.status === 'idle') return 'idle';
return state.status === 'playing' ? 'playing' : 'paused';
}
/** The text a snapshot is worth in the polite live region, `''` while there is nothing to say. */
export function statusMessage(state: Pick<MediaState, 'status' | 'waiting' | 'error' | 'blocked'>): string {
if (state.blocked) return 'Playback was blocked, press Play to start';
switch (stageState(state)) {
case 'error':
return 'Could not load the video';
case 'buffering':
return 'Buffering';
case 'playing':
return 'Playing';
case 'paused':
return state.status === 'ended' ? 'Ended' : 'Paused';
default:
return '';
}
}
/**
* Decides what the polite live region says.
*
* @remarks
* The player says nothing while the clip loads on its own: "Buffering" and "Paused" at page load, or after the
* player was moved, are noise to a reader who has done nothing yet. It starts to report once the clip has played,
* and a failure ("Could not load", "Playback was blocked") is always reported, because it answers an action or
* leaves the player unusable. A message is said once until it changes.
*/
export class Announcer {
private spoken = '';
private started = false;
/** Forgets what was said and silences the player again, for a clip that loads from the start. */
reset(): void {
this.spoken = '';
this.started = false;
}
/** The message to say for this snapshot, or `''` when there is nothing new to say. */
next(state: Pick<MediaState, 'status' | 'waiting' | 'error' | 'blocked'>): string {
if (state.status === 'playing') this.started = true;
const message = this.started || state.error || state.blocked ? statusMessage(state) : '';
if (message === this.spoken) return '';
this.spoken = message;
return message;
}
}
/** The `aria-valuetext` of the seek thumb, such as `1:15 of 4:00`. */
export function seekValueText(position: number, duration: number): string {
return `${formatMediaTime(position)} of ${formatMediaTime(duration)}`;
}
/** One buffered range as the percentages the stylesheet draws it with. */
export type BufferedSegment = { start: number; size: number };
/** The buffered ranges as percentages of the duration, empty until the duration is known. */
export function bufferedSegments(ranges: readonly (readonly [number, number])[], duration: number): BufferedSegment[] {
if (!Number.isFinite(duration) || duration <= 0) return [];
return ranges.map(([from, to]) => ({
start: (from / duration) * 100,
size: ((Math.min(to, duration) - from) / duration) * 100,
}));
}const inFlight = new Map<string, Promise<Blob>>();
function download(url: string): Promise<Blob> {
let pending = inFlight.get(url);
if (!pending) {
pending = fetchBlob(url).finally(() => inFlight.delete(url));
inFlight.set(url, pending);
}
return pending;
}
async function fetchBlob(url: string): Promise<Blob> {
const response = await fetch(url);
if (!response.ok) throw new Error(`${response.status} ${response.statusText} for ${url}`);
return response.blob();
}
/**
* Fetches a video into a `Blob` and returns an object URL, for `MediaController`'s `resolveSource`.
*
* @remarks
* A media element can only seek in a file whose server answers range requests, and many development and preview
* servers (this site's among them) do not: the element then reports nothing seekable and every seek snaps back to
* the start. The sample clip is about a megabyte, so it is fetched whole and played from memory, which always
* seeks. For long media serve the file with range support and pass its URL to `load()` without a `resolveSource`.
* A failed request rejects, which puts the controller in its `error` state; `retry()` calls this again.
*
* Requests for a url that is still downloading share one download, and each caller gets an object URL of its own.
* The page swaps the authoring pattern of a recipe by mounting the new form as soon as the old one is on the page,
* which would otherwise fetch the clip twice, and a shared object URL would be revoked under the form that is left
* running when the other releases it. A finished download is not kept, so a retry or a player that is moved asks the
* server again.
*/
export async function fetchSource(url: string): Promise<string> {
return URL.createObjectURL(await download(url));
}
/** Frees an object URL `fetchSource` made; `MediaController` calls it as `releaseSource` once the element has let go of it. */
export function releaseSource(url: string): void {
URL.revokeObjectURL(url);
}<div data-controller="video-player">
<div
data-stage
data-state="idle"
role="group"
aria-label="Video player"
aria-describedby="video-player-controller-help"
tabindex="0"
>
<video
data-video
data-src="/assets/video/radiant-reel.webm"
poster="/assets/video/radiant-reel.jpg"
preload="metadata"
playsinline
></video>
<button
type="button"
class="rui-button rui-button--filled rui-button--lg rui-button--square"
data-big-play
aria-hidden="true"
tabindex="-1"
>
<svg viewBox="0 0 24 24" width="28" height="28" aria-hidden="true" focusable="false">
<path d="M8 5v14l11-7z" fill="currentColor" />
</svg>
</button>
<span data-spinner aria-hidden="true"></span>
<div data-error hidden>
<p data-error-message>Could not load the video</p>
<button type="button" class="rui-button rui-button--filled rui-button--sm" data-retry>Retry</button>
</div>
<div data-controls>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-playback
aria-label="Play"
aria-pressed="false"
>
<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="play">
<path d="M8 5v14l11-7z" fill="currentColor" /></svg
><svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="pause">
<path d="M6 5h4v14H6zM14 5h4v14h-4z" fill="currentColor" />
</svg>
</button>
<div data-scrub>
<span data-elapsed>0:00</span>
<rui-slider data-seek step="0.01" label="Seek" min="0" max="1" value="0" disabled>
<div class="rui-slider rui-slider--single" data-ref="root">
<div class="rui-slider__range">
<div
class="rui-slider__range-track"
data-ref="rangeTrack"
style="--rui-slider-fill-start: 0%; --rui-slider-fill-size: 0%; --rui-slider-value: 0%"
>
<div data-buffered aria-hidden="true"></div>
<div class="rui-slider__range-fill" data-ref="rangeFill"></div>
<button
type="button"
class="rui-slider__thumb"
data-ref="singleThumb"
data-thumb="value"
role="slider"
aria-label="Seek"
></button>
</div>
</div>
</div>
</rui-slider>
<span data-duration>0:00</span>
</div>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-mute
aria-label="Mute"
aria-pressed="false"
>
<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="volume">
<path d="M4 9v6h4l5 4V5L8 9z" fill="currentColor" />
<path
d="M16 9a4 4 0 0 1 0 6"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/></svg
><svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="muted">
<path d="M4 9v6h4l5 4V5L8 9z" fill="currentColor" />
<path
d="M16.5 9.5l5 5M21.5 9.5l-5 5"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</button>
<div data-volume>
<rui-slider data-volume-input step="0.05" label="Volume" min="0" max="1" value="1">
<div class="rui-slider rui-slider--single" data-ref="root">
<div class="rui-slider__range">
<div
class="rui-slider__range-track"
data-ref="rangeTrack"
style="
--rui-slider-fill-start: 0%;
--rui-slider-fill-size: 100%;
--rui-slider-value: 100%;
"
>
<div class="rui-slider__range-fill" data-ref="rangeFill"></div>
<button
type="button"
class="rui-slider__thumb"
data-ref="singleThumb"
data-thumb="value"
role="slider"
aria-label="Volume"
></button>
</div>
</div>
</div>
</rui-slider>
</div>
<button type="button" class="rui-button rui-button--ghost rui-button--md" data-rate aria-label="Speed 1x">
1x
</button>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-captions
aria-label="Captions"
aria-pressed="false"
>
<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false">
<rect
x="3"
y="5"
width="18"
height="14"
rx="2"
fill="none"
stroke="currentColor"
stroke-width="2"
/>
<path
d="M10.5 10.5a2 2 0 1 0 0 3M17 10.5a2 2 0 1 0 0 3"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</button>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-fullscreen
aria-label="Fullscreen"
aria-pressed="false"
>
<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="enter">
<path
d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/></svg
><svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="exit">
<path
d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</button>
</div>
<p data-status aria-live="polite"></p>
</div>
<span data-help hidden id="video-player-controller-help"
>Space or K plays and pauses, J and L skip 10 seconds, the arrows seek 5 seconds or change the volume, M mutes,
C toggles captions, F toggles fullscreen, 0 to 9 jump through the video, Home and End go to its start and
end</span
>
</div>.primitive-example:is(
[data-example='video-player'],
:has(> video-player-element, > [data-controller='video-player'], > video-player-app)
) {
display: block;
width: min(100%, 44rem);
& :where([data-stage]) {
position: relative;
overflow: hidden;
box-sizing: border-box;
aspect-ratio: 16 / 9;
border-radius: var(--radius-container);
background: #000;
color: #fff;
box-shadow: var(--shadow-overlay);
container-type: inline-size;
user-select: none;
}
& :where([data-stage]:focus-visible) {
outline: 2px solid var(--focus-ring);
outline-offset: 2px;
}
& :where([data-stage]:fullscreen) {
aspect-ratio: auto;
inline-size: 100%;
block-size: 100%;
border-radius: 0;
}
& :where([data-stage]:fullscreen:focus-visible) {
outline-offset: -4px;
}
/* The ring is drawn over the picture, so it is white, which stands out from the dark bar and the error panel. */
& :where([data-controls], [data-error]) {
--focus-ring: #fff;
}
& :where([data-stage][data-controls-hidden][data-state='playing']) {
cursor: none;
}
& :where([data-video]) {
display: block;
inline-size: 100%;
block-size: 100%;
object-fit: contain;
cursor: pointer;
}
& :where([data-big-play]) {
position: absolute;
inset: 50% auto auto 50%;
translate: -50% -50%;
inline-size: calc(var(--size-control-lg) * 1.75);
block-size: calc(var(--size-control-lg) * 1.75);
border-radius: var(--radius-full);
box-shadow: var(--shadow-overlay);
opacity: 0;
pointer-events: none;
transition-property: opacity, scale;
transition-duration: var(--duration-normal);
transition-timing-function: var(--ease-out-strong);
scale: 0.9;
}
& :where([data-stage]:is([data-state='paused'], [data-state='idle']) [data-big-play]) {
opacity: 1;
pointer-events: auto;
scale: 1;
}
& :where([data-stage][data-state='idle'] [data-big-play]) {
opacity: 0.6;
}
& :where([data-spinner]) {
position: absolute;
inset: 50% auto auto 50%;
translate: -50% -50%;
box-sizing: border-box;
inline-size: calc(var(--size-control-lg) * 1.1);
block-size: calc(var(--size-control-lg) * 1.1);
border: 3px solid rgb(255 255 255 / 0.3);
border-block-start-color: #fff;
border-radius: var(--radius-full);
opacity: 0;
pointer-events: none;
transition: opacity var(--duration-normal) var(--ease-out-strong);
}
& :where([data-stage][data-state='buffering'] [data-spinner]) {
opacity: 1;
animation: video-player-spin 0.9s linear infinite;
}
& :where([data-error]:not([hidden])) {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: var(--space-4);
padding: var(--space-4);
background: color-mix(in srgb, #000 78%, transparent);
text-align: center;
}
& :where([data-error-message]) {
margin: 0;
}
& :where([data-video])::cue {
background: rgb(0 0 0 / 0.72);
color: #fff;
font-size: 1rem;
}
& :where([data-controls]) {
position: absolute;
inset: auto 0 0;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1) var(--space-2);
padding: var(--space-8) var(--space-3) var(--space-2);
background: linear-gradient(to top, rgb(0 0 0 / 0.78), rgb(0 0 0 / 0));
transition-property: opacity, translate;
transition-duration: var(--duration-normal);
transition-timing-function: var(--ease-out-strong);
}
& :where([data-stage][data-controls-hidden][data-state='playing'] [data-controls]) {
opacity: 0;
translate: 0 var(--space-2);
pointer-events: none;
}
& :where([data-controls] .rui-button--ghost) {
color: #fff;
}
@media (hover: hover) {
& :where([data-controls] .rui-button--ghost:hover:not(:disabled)) {
background: rgb(255 255 255 / 0.18);
}
}
& :where([data-controls] .rui-button--ghost:active:not(:disabled)) {
background: rgb(255 255 255 / 0.28);
}
/* The macOS themes draw a pressed button with a ring, which the inset bar replaces. */
& :where([data-controls] .rui-button--ghost[aria-pressed='true']) {
background: rgb(255 255 255 / 0.2);
color: #fff;
box-shadow: inset 0 -2px 0 var(--primary);
--tw-ring-shadow: 0 0 #0000;
}
& :where([data-rate]) {
min-inline-size: 3.25rem;
font-variant-numeric: tabular-nums;
}
& [data-playback] [data-icon='pause'],
& [data-playback][aria-pressed='true'] [data-icon='play'],
& [data-mute] [data-icon='muted'],
& [data-mute][aria-pressed='true'] [data-icon='volume'],
& [data-fullscreen] [data-icon='exit'],
& [data-fullscreen][aria-pressed='true'] [data-icon='enter'] {
display: none;
}
& [data-playback][aria-pressed='true'] [data-icon='pause'],
& [data-mute][aria-pressed='true'] [data-icon='muted'],
& [data-fullscreen][aria-pressed='true'] [data-icon='exit'] {
display: block;
}
& :where([data-fullscreen][hidden]) {
display: none;
}
& :where([data-scrub]) {
display: flex;
flex: 1 1 14rem;
align-items: center;
gap: var(--space-3);
min-inline-size: 0;
}
& :where([data-elapsed], [data-duration]) {
min-inline-size: 2.5ch;
font-size: 0.75rem;
font-variant-numeric: tabular-nums;
opacity: 0.85;
}
& :where([data-volume]) {
display: flex;
flex: 0 0 5.5rem;
align-items: center;
}
& :where([data-scrub] rui-slider, [data-volume] rui-slider),
& :where([data-scrub], [data-volume]) .rui-slider {
--rui-slider-track-length: 100%;
--rui-slider-track-color: rgb(255 255 255 / 0.28);
--rui-slider-fill-color: #fff;
--rui-slider-thumb-size: 0.875rem;
--rui-slider-thumb-background: #fff;
--rui-slider-thumb-border-color: #fff;
}
& :where([data-scrub] rui-slider, [data-volume] rui-slider) {
flex: 1;
min-inline-size: 0;
margin-inline: calc(var(--rui-slider-thumb-size) / 2);
}
& :where([data-scrub] .rui-slider__range-track) {
overflow: visible;
}
& .rui-slider__header {
display: none;
}
& :where([data-buffered]) {
position: absolute;
inset-block: 0;
inset-inline: 0;
border-radius: var(--rui-slider-track-radius, var(--radius-control));
overflow: hidden;
pointer-events: none;
}
& :where([data-buffered] i) {
position: absolute;
inset-block: 0;
inset-inline-start: calc(var(--start) * 1%);
inline-size: calc(var(--size) * 1%);
background: rgb(255 255 255 / 0.4);
}
& :where([data-status]) {
position: absolute;
inline-size: 1px;
block-size: 1px;
margin: 0;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
@container (max-width: 30rem) {
& :where([data-volume]) {
display: none;
}
}
@media (prefers-reduced-motion: reduce) {
& :where([data-controls], [data-big-play], [data-spinner]) {
transition: none;
}
& :where([data-stage][data-state='buffering'] [data-spinner]) {
animation: none;
}
}
}
@keyframes video-player-spin {
to {
rotate: 360deg;
}
}The class is the plain function's logic on a RadiantController: @query finds the parts, @onEvent delegates the clicks, keys and pointer events on the host, and @state fields with @bindTo write what is a plain copy of the media state onto the markup (the stage state, the pressed buttons, the clock, the status line, the speed and the error panel), with connect() in place of onConnected(). The buffered bar and the slider values are still written by hand, because they are not a copy of one value. Nothing differs in what it does. What differs is where it lives: there is no custom element tag to define, so the markup can come from a server template or a CMS and be any element, and the controller attaches to it through data-controller. The docs site starts one registry over the document, which connects the controller when the markup appears, including markup inserted later, and disconnects it when the element is removed, so the class only registers itself with @controller. createMediaController takes the controller as its host as it does an element: it attaches on connect and is destroyed on disconnect, which pauses the video, drops its source and releases the object URL, in a microtask that a move to another parent cancels. The hide timer and the thumb observer are cleaned up on disconnect, and connect() loads the clip again, with the captions off (disable()), when the element is moved. createCaptionsController takes the controller as its host too. pointerleave does not bubble, so its delegated listener runs in the capture phase.
A mount function wires the controller to the markup and returns the cleanup that undoes it.
Could not load the video
import '@ecopages/radiant-ui/slider';
import type { RuiSliderChangeDetail, RuiSliderElement } from '@ecopages/radiant-ui/slider';
import { CaptionsController, MediaController, type MediaState } from '@ecopages/radiant-ui/controllers';
import { cycleValue, formatMediaTime } from '@ecopages/radiant-ui/helpers';
import {
Announcer,
CAPTIONS,
HIDE_CONTROLS_MS,
RATES,
bufferedSegments,
seekFromKey,
seekValueText,
shortcutFor,
stageState,
type Shortcut,
} from './video-player.data';
import { fetchSource, releaseSource } from './video-player.loader';
export function mount(root: HTMLElement): () => void {
const part = <T extends HTMLElement>(selector: string) => root.querySelector<T>(selector)!;
const stage = part('[data-stage]');
const video = part<HTMLVideoElement>('[data-video]');
const controls = part('[data-controls]');
const seek = part<RuiSliderElement>('[data-seek]');
const seekThumb = seek.querySelector<HTMLElement>('[role="slider"]')!;
const volume = part<RuiSliderElement>('[data-volume-input]');
const playback = part('[data-playback]');
const mute = part('[data-mute]');
const rate = part('[data-rate]');
const captions = part('[data-captions]');
const fullscreen = part('[data-fullscreen]');
const buffered = part('[data-buffered]');
const status = part('[data-status]');
const error = part('[data-error]');
const listeners = new AbortController();
const { signal } = listeners;
let hideTimer: ReturnType<typeof setTimeout> | undefined;
let pointer = 'mouse';
let bufferedKey = '';
let valueText = '';
const announcer = new Announcer();
const captionsController = new CaptionsController({
getMedia: () => video,
getAvoid: () => controls,
tracks: [{ language: 'en', label: 'English', cues: CAPTIONS }],
onState: (state) => captions.setAttribute('aria-pressed', String(state.enabled)),
});
const media = new MediaController({
getMedia: () => video,
resolveSource: fetchSource,
releaseSource,
clearSourceOnDestroy: true,
onState: render,
onProgress: renderProgress,
});
/**
* Writes the clock, the seek thumb and the buffered bar.
*
* @remarks
* The slider repaints in a later update with its own `aria-valuetext`, a bare number of seconds, so the text is
* kept by the observer below and not only written here.
*/
function renderProgress(state: MediaState): void {
const known = Number.isFinite(state.duration);
if (known && seek.max !== state.duration) seek.max = state.duration;
seek.value = [state.position];
valueText = seekValueText(state.position, state.duration);
keepValueText();
part('[data-elapsed]').textContent = formatMediaTime(state.position);
part('[data-duration]').textContent = formatMediaTime(state.duration);
const segments = bufferedSegments(state.bufferedRanges, state.duration);
const key = JSON.stringify(segments);
if (key !== bufferedKey) {
bufferedKey = key;
buffered.replaceChildren(
...segments.map(({ start, size }) => {
const segment = document.createElement('i');
segment.style.setProperty('--start', String(start));
segment.style.setProperty('--size', String(size));
return segment;
}),
);
}
}
function keepValueText(): void {
if (seekThumb.getAttribute('aria-valuetext') !== valueText) seekThumb.setAttribute('aria-valuetext', valueText);
}
function render(state: MediaState): void {
const shown = stageState(state);
const message = announcer.next(state);
stage.dataset.state = shown;
playback.setAttribute('aria-pressed', String(state.status === 'playing'));
mute.setAttribute('aria-pressed', String(state.muted));
volume.value = [state.muted ? 0 : state.volume];
rate.textContent = `${state.rate}x`;
rate.setAttribute('aria-label', `Speed ${state.rate}x`);
seek.disabled = !state.seekable;
error.hidden = shown !== 'error';
if (message !== '') say(message);
renderProgress(state);
wake();
}
/**
* Shows the controls and, while the video plays, hides them again after `HIDE_CONTROLS_MS` of quiet. They stay
* while the pointer is over them or a control has keyboard focus, so a reader who is aiming at one never loses it.
*/
function wake(): void {
clearTimeout(hideTimer);
stage.removeAttribute('data-controls-hidden');
if (stage.dataset.state !== 'playing') return;
hideTimer = setTimeout(() => {
if (controls.matches(':hover') || controls.querySelector(':focus-visible')) return wake();
stage.setAttribute('data-controls-hidden', '');
}, HIDE_CONTROLS_MS);
}
function say(message: string): void {
status.textContent = message;
}
function toggleCaptions(): void {
captionsController.toggle();
say(captionsController.getState().enabled ? 'Captions on' : 'Captions off');
}
/**
* Both calls reject when the browser refuses (no user gesture, a sandboxed frame), and the player has nothing to
* show for it: the button only follows `fullscreenchange`.
*/
function toggleFullscreen(): void {
const request = document.fullscreenElement === stage ? document.exitFullscreen() : stage.requestFullscreen();
request.catch(() => undefined);
}
function run(shortcut: Shortcut): void {
const state = media.getState();
switch (shortcut.type) {
case 'toggle':
return void media.toggle();
case 'skip':
return media.skip(shortcut.seconds);
case 'volume': {
const next = Math.round((state.volume + shortcut.delta) * 100) / 100;
if (shortcut.delta > 0 && state.muted) media.setMuted(false);
media.setVolume(next);
return say(`Volume ${Math.round(media.getState().volume * 100)}%`);
}
case 'mute':
return media.toggleMuted();
case 'captions':
return toggleCaptions();
case 'fullscreen':
return toggleFullscreen();
case 'jump':
return media.seek(state.duration * shortcut.fraction);
case 'start':
return media.seek(0);
case 'end':
return media.seek(state.duration);
}
}
stage.addEventListener(
'keydown',
(event) => {
wake();
const shortcut = shortcutFor(event);
if (!shortcut) return;
event.preventDefault();
run(shortcut);
},
{ signal },
);
/**
* A touch on the video is a tap that shows or hides the controls, which the click handler below decides, so it is
* not activity here.
*/
const activity = (event: PointerEvent) => {
if (event.target !== video || event.pointerType !== 'touch') wake();
};
for (const type of ['pointermove', 'pointerdown', 'pointerleave'] as const) {
stage.addEventListener(type, activity, { signal });
}
video.addEventListener('pointerdown', (event) => (pointer = event.pointerType), { signal });
video.addEventListener(
'click',
() => {
if (pointer === 'touch' && stage.dataset.state === 'playing') {
if (stage.hasAttribute('data-controls-hidden')) wake();
else stage.setAttribute('data-controls-hidden', '');
} else void media.toggle();
},
{ signal },
);
video.addEventListener('dblclick', toggleFullscreen, { signal });
part('[data-big-play]').addEventListener('click', () => void media.toggle(), { signal });
playback.addEventListener('click', () => void media.toggle(), { signal });
mute.addEventListener('click', () => media.toggleMuted(), { signal });
rate.addEventListener(
'click',
() => {
media.setRate(Number(cycleValue(RATES, String(media.getState().rate))));
say(`Speed ${media.getState().rate}x`);
},
{ signal },
);
captions.addEventListener('click', toggleCaptions, { signal });
fullscreen.addEventListener('click', toggleFullscreen, { signal });
part('[data-retry]').addEventListener('click', () => void media.retry(), { signal });
seek.addEventListener(
'rui-change',
(event) => media.scrub((event as CustomEvent<RuiSliderChangeDetail>).detail.value[0]),
{ signal },
);
/**
* The capture phase runs before the slider's own key handler, which this stops for the keys the player moves by
* whole seconds, so the slider's 0.01 s step never applies to an arrow key.
*/
seek.addEventListener(
'keydown',
(event) => {
const seconds = seekFromKey(event.key);
if (seconds === undefined) return;
event.preventDefault();
event.stopPropagation();
wake();
media.skip(seconds);
},
{ signal, capture: true },
);
volume.addEventListener(
'rui-change',
(event) => {
const level = (event as CustomEvent<RuiSliderChangeDetail>).detail.value[0];
media.setVolume(level);
if (level > 0) media.setMuted(false);
},
{ signal },
);
document.addEventListener(
'fullscreenchange',
() => fullscreen.setAttribute('aria-pressed', String(document.fullscreenElement === stage)),
{ signal },
);
const valueTextObserver = new MutationObserver(keepValueText);
valueTextObserver.observe(seekThumb, { attributes: true, attributeFilter: ['aria-valuetext'] });
fullscreen.hidden = !document.fullscreenEnabled;
captionsController.attach();
media.attach();
void media.load(video.dataset.src!);
return () => {
listeners.abort();
clearTimeout(hideTimer);
valueTextObserver.disconnect();
captionsController.destroy();
media.destroy();
};
}import type { MediaState } from '@ecopages/radiant-ui/controllers';
import { formatMediaTime } from '@ecopages/radiant-ui/helpers';
/** The sample clip and its poster, made by `scripts/generate-video-player-assets.mjs`. */
export const VIDEO = {
src: '/assets/video/radiant-reel.webm',
poster: '/assets/video/radiant-reel.jpg',
} as const;
/** The English captions of the clip, one for each of its five scenes, in seconds. */
export const CAPTIONS: readonly { start: number; end: number; text: string }[] = [
{ start: 0.2, end: 2.3, text: 'Scene one: a slow start' },
{ start: 2.6, end: 4.7, text: 'Scene two: the shapes arrive' },
{ start: 5, end: 7.1, text: 'Scene three: everything turns' },
{ start: 7.4, end: 9.5, text: 'Scene four: the light moves on' },
{ start: 9.8, end: 11.9, text: 'Scene five: and it settles' },
];
/**
* The playback rates the speed button cycles through, as the strings `cycleValue` works on, and the value the
* button shows with an `x`.
*/
export const RATES: readonly string[] = ['1', '1.25', '1.5', '2', '0.5'];
/** Seconds the arrow keys move the playback by, on the seek thumb and on the player. */
export const SEEK_STEP = 5;
/** Seconds `J`, `L`, Page Up and Page Down move the playback by. */
export const LONG_SEEK_STEP = 10;
/** The fraction of the full volume the arrow keys change it by. */
export const VOLUME_STEP = 0.1;
/** Milliseconds without a pointer or key event after which the controls hide while the video plays. */
export const HIDE_CONTROLS_MS = 2500;
/** What the stage shows: `data-state` on `[data-stage]` carries one of these and the stylesheet draws from it. */
export type StageState = 'idle' | 'buffering' | 'playing' | 'paused' | 'error';
/** What a shortcut asks the player to do. */
export type Shortcut =
| { type: 'toggle' }
| { type: 'skip'; seconds: number }
| { type: 'volume'; delta: number }
| { type: 'mute' }
| { type: 'captions' }
| { type: 'fullscreen' }
| { type: 'jump'; fraction: number }
| { type: 'start' }
| { type: 'end' };
const SHORTCUTS = new Map<string, Shortcut>([
[' ', { type: 'toggle' }],
['k', { type: 'toggle' }],
['j', { type: 'skip', seconds: -LONG_SEEK_STEP }],
['l', { type: 'skip', seconds: LONG_SEEK_STEP }],
['ArrowLeft', { type: 'skip', seconds: -SEEK_STEP }],
['ArrowRight', { type: 'skip', seconds: SEEK_STEP }],
['ArrowUp', { type: 'volume', delta: VOLUME_STEP }],
['ArrowDown', { type: 'volume', delta: -VOLUME_STEP }],
['m', { type: 'mute' }],
['c', { type: 'captions' }],
['f', { type: 'fullscreen' }],
['Home', { type: 'start' }],
['End', { type: 'end' }],
...Array.from({ length: 10 }, (_, digit): [string, Shortcut] => [
String(digit),
{ type: 'jump', fraction: digit / 10 },
]),
]);
const SLIDER_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'PageUp', 'PageDown']);
/**
* The shortcut a key event asks for, or `undefined` when the player must leave it alone.
*
* @remarks
* A key that carries Ctrl, Alt or Meta belongs to the browser. A button owns Space and Enter, which activate it. A
* slider thumb owns the arrows, Home, End and the page keys, which move it; the letters and digits still reach the
* player. The target is the element the key was pressed on, which a `keydown` listener on the stage always has.
*/
export function shortcutFor(
event: Pick<KeyboardEvent, 'key' | 'ctrlKey' | 'altKey' | 'metaKey' | 'target'>,
): Shortcut | undefined {
if (event.ctrlKey || event.altKey || event.metaKey) return undefined;
const target = event.target as Element;
if (target.closest('button') && (event.key === ' ' || event.key === 'Enter')) return undefined;
if (target.closest('[role="slider"]') && SLIDER_KEYS.has(event.key)) return undefined;
return SHORTCUTS.get(event.key.length === 1 ? event.key.toLowerCase() : event.key);
}
const SEEK_KEYS = new Map([
['ArrowRight', SEEK_STEP],
['ArrowUp', SEEK_STEP],
['ArrowLeft', -SEEK_STEP],
['ArrowDown', -SEEK_STEP],
['PageUp', LONG_SEEK_STEP],
['PageDown', -LONG_SEEK_STEP],
]);
/**
* Seconds a key moves the seek slider by, or `undefined` for any other key.
*
* @remarks
* The slider works in seconds with a step of 0.01, fine enough that the per-frame position write is not rounded and
* the thumb glides. A step that fine would make an arrow key inaudible, so the player handles these keys and the
* slider keeps Home and End.
*/
export function seekFromKey(key: string): number | undefined {
return SEEK_KEYS.get(key);
}
/** The state of the stage for a snapshot of the media element. */
export function stageState(state: Pick<MediaState, 'status' | 'waiting' | 'error'>): StageState {
if (state.error) return 'error';
if (state.waiting || state.status === 'loading') return 'buffering';
if (state.status === 'idle') return 'idle';
return state.status === 'playing' ? 'playing' : 'paused';
}
/** The text a snapshot is worth in the polite live region, `''` while there is nothing to say. */
export function statusMessage(state: Pick<MediaState, 'status' | 'waiting' | 'error' | 'blocked'>): string {
if (state.blocked) return 'Playback was blocked, press Play to start';
switch (stageState(state)) {
case 'error':
return 'Could not load the video';
case 'buffering':
return 'Buffering';
case 'playing':
return 'Playing';
case 'paused':
return state.status === 'ended' ? 'Ended' : 'Paused';
default:
return '';
}
}
/**
* Decides what the polite live region says.
*
* @remarks
* The player says nothing while the clip loads on its own: "Buffering" and "Paused" at page load, or after the
* player was moved, are noise to a reader who has done nothing yet. It starts to report once the clip has played,
* and a failure ("Could not load", "Playback was blocked") is always reported, because it answers an action or
* leaves the player unusable. A message is said once until it changes.
*/
export class Announcer {
private spoken = '';
private started = false;
/** Forgets what was said and silences the player again, for a clip that loads from the start. */
reset(): void {
this.spoken = '';
this.started = false;
}
/** The message to say for this snapshot, or `''` when there is nothing new to say. */
next(state: Pick<MediaState, 'status' | 'waiting' | 'error' | 'blocked'>): string {
if (state.status === 'playing') this.started = true;
const message = this.started || state.error || state.blocked ? statusMessage(state) : '';
if (message === this.spoken) return '';
this.spoken = message;
return message;
}
}
/** The `aria-valuetext` of the seek thumb, such as `1:15 of 4:00`. */
export function seekValueText(position: number, duration: number): string {
return `${formatMediaTime(position)} of ${formatMediaTime(duration)}`;
}
/** One buffered range as the percentages the stylesheet draws it with. */
export type BufferedSegment = { start: number; size: number };
/** The buffered ranges as percentages of the duration, empty until the duration is known. */
export function bufferedSegments(ranges: readonly (readonly [number, number])[], duration: number): BufferedSegment[] {
if (!Number.isFinite(duration) || duration <= 0) return [];
return ranges.map(([from, to]) => ({
start: (from / duration) * 100,
size: ((Math.min(to, duration) - from) / duration) * 100,
}));
}const inFlight = new Map<string, Promise<Blob>>();
function download(url: string): Promise<Blob> {
let pending = inFlight.get(url);
if (!pending) {
pending = fetchBlob(url).finally(() => inFlight.delete(url));
inFlight.set(url, pending);
}
return pending;
}
async function fetchBlob(url: string): Promise<Blob> {
const response = await fetch(url);
if (!response.ok) throw new Error(`${response.status} ${response.statusText} for ${url}`);
return response.blob();
}
/**
* Fetches a video into a `Blob` and returns an object URL, for `MediaController`'s `resolveSource`.
*
* @remarks
* A media element can only seek in a file whose server answers range requests, and many development and preview
* servers (this site's among them) do not: the element then reports nothing seekable and every seek snaps back to
* the start. The sample clip is about a megabyte, so it is fetched whole and played from memory, which always
* seeks. For long media serve the file with range support and pass its URL to `load()` without a `resolveSource`.
* A failed request rejects, which puts the controller in its `error` state; `retry()` calls this again.
*
* Requests for a url that is still downloading share one download, and each caller gets an object URL of its own.
* The page swaps the authoring pattern of a recipe by mounting the new form as soon as the old one is on the page,
* which would otherwise fetch the clip twice, and a shared object URL would be revoked under the form that is left
* running when the other releases it. A finished download is not kept, so a retry or a player that is moved asks the
* server again.
*/
export async function fetchSource(url: string): Promise<string> {
return URL.createObjectURL(await download(url));
}
/** Frees an object URL `fetchSource` made; `MediaController` calls it as `releaseSource` once the element has let go of it. */
export function releaseSource(url: string): void {
URL.revokeObjectURL(url);
}<div data-example="video-player">
<div
data-stage
data-state="idle"
role="group"
aria-label="Video player"
aria-describedby="video-player-plain-help"
tabindex="0"
>
<video
data-video
data-src="/assets/video/radiant-reel.webm"
poster="/assets/video/radiant-reel.jpg"
preload="metadata"
playsinline
></video>
<button
type="button"
class="rui-button rui-button--filled rui-button--lg rui-button--square"
data-big-play
aria-hidden="true"
tabindex="-1"
>
<svg viewBox="0 0 24 24" width="28" height="28" aria-hidden="true" focusable="false">
<path d="M8 5v14l11-7z" fill="currentColor" />
</svg>
</button>
<span data-spinner aria-hidden="true"></span>
<div data-error hidden>
<p data-error-message>Could not load the video</p>
<button type="button" class="rui-button rui-button--filled rui-button--sm" data-retry>Retry</button>
</div>
<div data-controls>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-playback
aria-label="Play"
aria-pressed="false"
>
<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="play">
<path d="M8 5v14l11-7z" fill="currentColor" /></svg
><svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="pause">
<path d="M6 5h4v14H6zM14 5h4v14h-4z" fill="currentColor" />
</svg>
</button>
<div data-scrub>
<span data-elapsed>0:00</span>
<rui-slider data-seek step="0.01" label="Seek" min="0" max="1" value="0" disabled>
<div class="rui-slider rui-slider--single" data-ref="root">
<div class="rui-slider__range">
<div
class="rui-slider__range-track"
data-ref="rangeTrack"
style="--rui-slider-fill-start: 0%; --rui-slider-fill-size: 0%; --rui-slider-value: 0%"
>
<div data-buffered aria-hidden="true"></div>
<div class="rui-slider__range-fill" data-ref="rangeFill"></div>
<button
type="button"
class="rui-slider__thumb"
data-ref="singleThumb"
data-thumb="value"
role="slider"
aria-label="Seek"
></button>
</div>
</div>
</div>
</rui-slider>
<span data-duration>0:00</span>
</div>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-mute
aria-label="Mute"
aria-pressed="false"
>
<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="volume">
<path d="M4 9v6h4l5 4V5L8 9z" fill="currentColor" />
<path
d="M16 9a4 4 0 0 1 0 6"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/></svg
><svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="muted">
<path d="M4 9v6h4l5 4V5L8 9z" fill="currentColor" />
<path
d="M16.5 9.5l5 5M21.5 9.5l-5 5"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</button>
<div data-volume>
<rui-slider data-volume-input step="0.05" label="Volume" min="0" max="1" value="1">
<div class="rui-slider rui-slider--single" data-ref="root">
<div class="rui-slider__range">
<div
class="rui-slider__range-track"
data-ref="rangeTrack"
style="
--rui-slider-fill-start: 0%;
--rui-slider-fill-size: 100%;
--rui-slider-value: 100%;
"
>
<div class="rui-slider__range-fill" data-ref="rangeFill"></div>
<button
type="button"
class="rui-slider__thumb"
data-ref="singleThumb"
data-thumb="value"
role="slider"
aria-label="Volume"
></button>
</div>
</div>
</div>
</rui-slider>
</div>
<button type="button" class="rui-button rui-button--ghost rui-button--md" data-rate aria-label="Speed 1x">
1x
</button>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-captions
aria-label="Captions"
aria-pressed="false"
>
<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false">
<rect
x="3"
y="5"
width="18"
height="14"
rx="2"
fill="none"
stroke="currentColor"
stroke-width="2"
/>
<path
d="M10.5 10.5a2 2 0 1 0 0 3M17 10.5a2 2 0 1 0 0 3"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</button>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-fullscreen
aria-label="Fullscreen"
aria-pressed="false"
>
<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="enter">
<path
d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/></svg
><svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" data-icon="exit">
<path
d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</button>
</div>
<p data-status aria-live="polite"></p>
</div>
<span data-help hidden id="video-player-plain-help"
>Space or K plays and pauses, J and L skip 10 seconds, the arrows seek 5 seconds or change the volume, M mutes,
C toggles captions, F toggles fullscreen, 0 to 9 jump through the video, Home and End go to its start and
end</span
>
</div>.primitive-example:is(
[data-example='video-player'],
:has(> video-player-element, > [data-controller='video-player'], > video-player-app)
) {
display: block;
width: min(100%, 44rem);
& :where([data-stage]) {
position: relative;
overflow: hidden;
box-sizing: border-box;
aspect-ratio: 16 / 9;
border-radius: var(--radius-container);
background: #000;
color: #fff;
box-shadow: var(--shadow-overlay);
container-type: inline-size;
user-select: none;
}
& :where([data-stage]:focus-visible) {
outline: 2px solid var(--focus-ring);
outline-offset: 2px;
}
& :where([data-stage]:fullscreen) {
aspect-ratio: auto;
inline-size: 100%;
block-size: 100%;
border-radius: 0;
}
& :where([data-stage]:fullscreen:focus-visible) {
outline-offset: -4px;
}
/* The ring is drawn over the picture, so it is white, which stands out from the dark bar and the error panel. */
& :where([data-controls], [data-error]) {
--focus-ring: #fff;
}
& :where([data-stage][data-controls-hidden][data-state='playing']) {
cursor: none;
}
& :where([data-video]) {
display: block;
inline-size: 100%;
block-size: 100%;
object-fit: contain;
cursor: pointer;
}
& :where([data-big-play]) {
position: absolute;
inset: 50% auto auto 50%;
translate: -50% -50%;
inline-size: calc(var(--size-control-lg) * 1.75);
block-size: calc(var(--size-control-lg) * 1.75);
border-radius: var(--radius-full);
box-shadow: var(--shadow-overlay);
opacity: 0;
pointer-events: none;
transition-property: opacity, scale;
transition-duration: var(--duration-normal);
transition-timing-function: var(--ease-out-strong);
scale: 0.9;
}
& :where([data-stage]:is([data-state='paused'], [data-state='idle']) [data-big-play]) {
opacity: 1;
pointer-events: auto;
scale: 1;
}
& :where([data-stage][data-state='idle'] [data-big-play]) {
opacity: 0.6;
}
& :where([data-spinner]) {
position: absolute;
inset: 50% auto auto 50%;
translate: -50% -50%;
box-sizing: border-box;
inline-size: calc(var(--size-control-lg) * 1.1);
block-size: calc(var(--size-control-lg) * 1.1);
border: 3px solid rgb(255 255 255 / 0.3);
border-block-start-color: #fff;
border-radius: var(--radius-full);
opacity: 0;
pointer-events: none;
transition: opacity var(--duration-normal) var(--ease-out-strong);
}
& :where([data-stage][data-state='buffering'] [data-spinner]) {
opacity: 1;
animation: video-player-spin 0.9s linear infinite;
}
& :where([data-error]:not([hidden])) {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: var(--space-4);
padding: var(--space-4);
background: color-mix(in srgb, #000 78%, transparent);
text-align: center;
}
& :where([data-error-message]) {
margin: 0;
}
& :where([data-video])::cue {
background: rgb(0 0 0 / 0.72);
color: #fff;
font-size: 1rem;
}
& :where([data-controls]) {
position: absolute;
inset: auto 0 0;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1) var(--space-2);
padding: var(--space-8) var(--space-3) var(--space-2);
background: linear-gradient(to top, rgb(0 0 0 / 0.78), rgb(0 0 0 / 0));
transition-property: opacity, translate;
transition-duration: var(--duration-normal);
transition-timing-function: var(--ease-out-strong);
}
& :where([data-stage][data-controls-hidden][data-state='playing'] [data-controls]) {
opacity: 0;
translate: 0 var(--space-2);
pointer-events: none;
}
& :where([data-controls] .rui-button--ghost) {
color: #fff;
}
@media (hover: hover) {
& :where([data-controls] .rui-button--ghost:hover:not(:disabled)) {
background: rgb(255 255 255 / 0.18);
}
}
& :where([data-controls] .rui-button--ghost:active:not(:disabled)) {
background: rgb(255 255 255 / 0.28);
}
/* The macOS themes draw a pressed button with a ring, which the inset bar replaces. */
& :where([data-controls] .rui-button--ghost[aria-pressed='true']) {
background: rgb(255 255 255 / 0.2);
color: #fff;
box-shadow: inset 0 -2px 0 var(--primary);
--tw-ring-shadow: 0 0 #0000;
}
& :where([data-rate]) {
min-inline-size: 3.25rem;
font-variant-numeric: tabular-nums;
}
& [data-playback] [data-icon='pause'],
& [data-playback][aria-pressed='true'] [data-icon='play'],
& [data-mute] [data-icon='muted'],
& [data-mute][aria-pressed='true'] [data-icon='volume'],
& [data-fullscreen] [data-icon='exit'],
& [data-fullscreen][aria-pressed='true'] [data-icon='enter'] {
display: none;
}
& [data-playback][aria-pressed='true'] [data-icon='pause'],
& [data-mute][aria-pressed='true'] [data-icon='muted'],
& [data-fullscreen][aria-pressed='true'] [data-icon='exit'] {
display: block;
}
& :where([data-fullscreen][hidden]) {
display: none;
}
& :where([data-scrub]) {
display: flex;
flex: 1 1 14rem;
align-items: center;
gap: var(--space-3);
min-inline-size: 0;
}
& :where([data-elapsed], [data-duration]) {
min-inline-size: 2.5ch;
font-size: 0.75rem;
font-variant-numeric: tabular-nums;
opacity: 0.85;
}
& :where([data-volume]) {
display: flex;
flex: 0 0 5.5rem;
align-items: center;
}
& :where([data-scrub] rui-slider, [data-volume] rui-slider),
& :where([data-scrub], [data-volume]) .rui-slider {
--rui-slider-track-length: 100%;
--rui-slider-track-color: rgb(255 255 255 / 0.28);
--rui-slider-fill-color: #fff;
--rui-slider-thumb-size: 0.875rem;
--rui-slider-thumb-background: #fff;
--rui-slider-thumb-border-color: #fff;
}
& :where([data-scrub] rui-slider, [data-volume] rui-slider) {
flex: 1;
min-inline-size: 0;
margin-inline: calc(var(--rui-slider-thumb-size) / 2);
}
& :where([data-scrub] .rui-slider__range-track) {
overflow: visible;
}
& .rui-slider__header {
display: none;
}
& :where([data-buffered]) {
position: absolute;
inset-block: 0;
inset-inline: 0;
border-radius: var(--rui-slider-track-radius, var(--radius-control));
overflow: hidden;
pointer-events: none;
}
& :where([data-buffered] i) {
position: absolute;
inset-block: 0;
inset-inline-start: calc(var(--start) * 1%);
inline-size: calc(var(--size) * 1%);
background: rgb(255 255 255 / 0.4);
}
& :where([data-status]) {
position: absolute;
inline-size: 1px;
block-size: 1px;
margin: 0;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
@container (max-width: 30rem) {
& :where([data-volume]) {
display: none;
}
}
@media (prefers-reduced-motion: reduce) {
& :where([data-controls], [data-big-play], [data-spinner]) {
transition: none;
}
& :where([data-stage][data-state='buffering'] [data-spinner]) {
animation: none;
}
}
}
@keyframes video-player-spin {
to {
rotate: 360deg;
}
}mount runs once for each example element on the page, and the function it returns undoes it; see how the examples run. The cleanup destroys the controller, which pauses the video, drops its source and releases the object URL, and it aborts the listeners, clears the hide timer and removes the fullscreenchange listener. It leaves fullscreen alone: the element that is full screen leaves the document with the page.
The stage carries the state, data-state as idle, buffering, playing, paused or error, and the stylesheet draws the spinner, the big play button, the error panel and the controls from it; data-controls-hidden marks the controls hidden, which only applies while it plays. Both come from pure helpers in video-player.data, so every form maps the controller's state the same way. The play button keeps one name, "Play", and says whether it plays with aria-pressed, as the mute, captions and fullscreen buttons do; a name that changed with the state would be read twice. The spinner is decoration, and a polite live region says "Playing", "Paused", "Buffering" and "Could not load the video", and nothing at all until the clip has first played (a failure is always said), through Announcer in video-player.data, so a page that loads is quiet and a moved player does not repeat itself. The speed button keeps its visible text, "1x", in its name ("Speed 1x"), so a voice user can say what they see. The keyboard help is hidden, which aria-describedby still reads, so it is not read a second time in browse order. The focus ring over the picture is white. The fullscreen button is hidden when document.fullscreenEnabled is false, and follows fullscreenchange otherwise, so leaving fullscreen with Escape updates it.
The seek slider works in seconds and reports rui-change only for the reader, never for the position the player writes to it. Its step of 0.01 s keeps the per-frame position write smooth and is too small for an arrow key, so a capture-phase keydown listener passes the arrows and the page keys to skip before the slider sees them, and a drag goes to scrub, which seeks once the pointer has rested. While a scrub is pending the controller reports the target as the position, so the thumb does not jump back. The slider writes its own aria-valuetext with every value, so the recipe writes "1:15 of 4:00" after it. The shortcuts are one keydown on the stage; shortcutFor leaves out keys with Ctrl, Alt or Meta, the activation keys of a button and the keys a slider thumb already handles.
The clip is fetched into a Blob by video-player.loader and played from memory, passed to the controller as resolveSource and releaseSource. A media element can only seek in a file whose server answers range requests, and many development and preview servers, this site's among them, do not, so seeking would snap back to the start. For long media, serve the file with range support and give load() its URL without a resolveSource. Requests for a clip that is still downloading share one download, each with an object URL of its own: the page mounts the next form as soon as the pattern changes, which would otherwise fetch the clip twice. A file that cannot be fetched puts the stage in error; Retry calls retry(), which loads it again.
The sample files
The clip and its poster are in src/public/assets/video and come from scripts/generate-video-player-assets.mjs, which draws the animation on a canvas in Chromium, records it with a generated sound track, and re-encodes the video with a keyframe every second with the ffmpeg that Playwright installs (from PLAYWRIGHT_BROWSERS_PATH, or the platform's cache folder). Nothing is downloaded, and running the script again rebuilds the two files. The captions are data in video-player.data, passed as the cues of one track to CaptionsController, which needs no .vtt file. It sets their line from the measured top of the controls, so they stay above the bar when it wraps to two rows on a narrow screen; the stage and the video are the same box, so the controls sit inside the video's rectangle.
Styles
The stage is a 16:9 box with --shadow-overlay, and its controls are a gradient bar that fades with data-controls-hidden. The buttons keep the Radiant classes and the slider its own parts, and the stylesheet only sets their colors for the dark bar. The :fullscreen rule lets the stage fill the screen, and reduced motion turns off the fades and the spinner's rotation. The stylesheet is the video-player.css tab in the files above.