---
title: Video player store
description: 'The video player with its snapshot in one store, so play, mute and speed patch the controls without re-running render().'
order: 10
---

import { PrimitiveExample } from '@/components/primitive-example';
import { RecipeCode, RecipeExample, RecipePattern, RecipePatterns } from '@/components/recipe-patterns';

export const config = {
	dependencies: {
		components: [PrimitiveExample, RecipePatterns, RecipeCode, RecipeExample],
		scripts: ['./video-player-store.component.tsx', './video-player.script.ts'],
		stylesheets: ['./video-player.css'],
	},
};

# Video player store

<p class="docs-lede">
	The same player as [Video player](/docs/recipes/video-player), with the snapshot in one store so a binding such
	as `this.$.media.muted` patches a node without redrawing the stage.
</p>

## Goal

The original component already binds the clock with `this.$`, so a playing clip does not redraw the stage. Play, mute and speed still do, because `render()` reads those `@state` fields. This recipe keeps the same controls, keyboard, captions and fullscreen, and holds the snapshot in one `createStore`. A binding such as `this.$.media.muted` follows that path, so play, mute and speed patch without a render. The [Video player](/docs/recipes/video-player) component form is the baseline this one is measured against.

The store is a component-form technique: `render()` owns the tree, and `this.$` patches it. The element and controller forms of the original player already write the DOM without `render()`, so this page has the component form, and the plain form of the original player as its baseline.

## Primitives

- [MediaController](/docs/controllers/media) owns playback, as on the original player. `onState` and `onProgress` write paths on the store; they do not call `render()`.
- [CaptionsController](/docs/controllers/captions) owns the captions. The recipe writes `media.captionsOn` from the state it reports.
- [formatMediaTime](/docs/helpers/media-time) is applied with `this.$.media.position.map(formatMediaTime)`, so the clock is a projection of one field.
- [cycleValue](/docs/helpers/overview) steps the speed button.
- `createStore` from `@ecopages/signals` holds the snapshot. A binding such as `this.$.media.muted` updates when that path changes.
- [`rui-slider`](/docs/forms/slider) takes `max`, `disabled` and `value` as a snapshot: its view helper stamps them on its parts when `render()` runs. So they come from private fields that `render()` reads, and each callback also writes the current value on the slider by hand. The buffered layer stays a node the recipe inserts, because the slider has no region for it.

Left to the recipe: the same keyboard, auto-hiding controls, fullscreen, live region and Blob load as the original, with the data and the loader of the [Video player](/docs/recipes/video-player). The volume slider's level (`0` while muted) and the seek thumb's time text are computed in the callbacks and written to the sliders, because the slider takes them as a snapshot.

## Example

Press Play or click the video, drag the scrub bar, change the volume, cycle the speed and turn the captions on. The behavior is the same as the video player; the difference is where the snapshot lives.

<RecipePatterns patterns={['component', 'plain']}>

<RecipePattern id="component">

The player is a `RadiantElement` whose `render()` does not run per frame. One `@state` field holds a `createStore` of the snapshot, and the changing text, attributes and pressed buttons in this host's tree are paths on `this.$.media`.

<PrimitiveExample host layout="stack">
	<video-player-store-app></video-player-store-app>
</PrimitiveExample>

```tsx title="video-player-store.component.tsx"
import { RadiantElement, customElement, onEvent, query, state } from '@ecopages/radiant';
import {
	createCaptionsController,
	createHotkeyController,
	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 { RuiSliderElement } from '@ecopages/radiant-ui/slider';
import { createStore } from '@ecopages/signals';

import {
	Announcer,
	CAPTIONS,
	HIDE_CONTROLS_MS,
	RATES,
	SEEK_KEYS,
	SHORTCUTS,
	VIDEO,
	bufferedSegments,
	isOwnedByControl,
	seekValueText,
	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';

/**
 * The media snapshot the player paints from. A write to one path patches the nodes bound to it with
 * `this.$.media.*`.
 *
 * @remarks
 * Only what a node shows is here. The volume slider's level (`0` while muted) and the seek thumb's time text are
 * written to the sliders by hand, because `RuiSlider` takes them as a snapshot.
 */
export type PlayerMedia = {
	stage: StageState;
	playing: boolean;
	muted: boolean;
	captionsOn: boolean;
	fullscreenAvailable: boolean;
	fullscreen: boolean;
	rate: number;
	status: string;
	position: number;
	duration: number;
	controlsHidden: boolean;
};

const INITIAL_MEDIA: PlayerMedia = {
	stage: 'idle',
	playing: false,
	muted: false,
	captionsOn: false,
	fullscreenAvailable: false,
	fullscreen: false,
	rate: 1,
	status: '',
	position: 0,
	duration: Number.NaN,
	controlsHidden: false,
};

/**
 * @remarks
 * One `createStore` holds the snapshot, and `render()` reads it only through `this.$.media`, so a path write
 * patches its nodes without a render. The sliders are the exception: `RuiSlider` stamps `max`, `disabled` and
 * `value` on its parts from the props of the render that drew it, and a later render would put a stale value back.
 * So `render()` reads them from private fields, which are not reactive, and `requestUpdate()` runs only when the
 * clip becomes seekable. Each callback writes the current value to the slider as well, and the buffered layer and
 * the thumb's `aria-valuetext` by hand.
 */
@customElement('video-player-store-app')
export class VideoPlayerStoreApp extends RadiantElement<{ media: PlayerMedia }> {
	@state media: PlayerMedia = createStore({ ...INITIAL_MEDIA });

	@query('[data-stage]') private stageNode!: HTMLElement;
	@query('[data-video]') private video!: HTMLVideoElement;
	@query('[data-controls]') private controls!: HTMLElement;
	@query('[data-seek]') private seek!: RuiSliderElement;
	@query('[data-volume-input]') private volume!: RuiSliderElement;

	private hideTimer: ReturnType<typeof setTimeout> | undefined;
	private pointer = 'mouse';
	private position = 0;
	private seekMax = 1;
	private level = 1;
	private seekable = false;
	private bufferedKey = '';
	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.media.captionsOn = state.enabled;
		},
	});

	private readonly playback = createMediaController(this, {
		getMedia: () => this.video,
		resolveSource: fetchSource,
		releaseSource,
		clearSourceOnDestroy: true,
		onState: (state) => this.writeState(state),
		onProgress: (state) => this.writeProgress(state),
	});

	private readonly stageKeys = createHotkeyController(this, {
		getTarget: () => this.stageNode,
		hotkeys: Array.from(SHORTCUTS, ([keys, shortcut]) => ({
			keys,
			handler: (event: KeyboardEvent) => (isOwnedByControl(event) ? false : this.run(shortcut)),
		})),
	});

	private readonly seekKeys = createHotkeyController(this, {
		getTarget: () => this.seek,
		capture: true,
		hotkeys: Array.from(SEEK_KEYS, ([keys, seconds]) => ({
			keys,
			handler: (event: KeyboardEvent) => {
				event.stopPropagation();
				this.wake();
				this.playback.skip(seconds);
			},
		})),
	});

	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.media.fullscreenAvailable = document.fullscreenEnabled;
		this.announcer.reset();
		this.playback.attach();
		this.stageKeys.attach();
		this.seekKeys.attach();
		void this.playback.load(this.video.dataset.src!);
	}

	@onEvent({ document: true, type: 'fullscreenchange' })
	followFullscreen(): void {
		this.media.fullscreen = document.fullscreenElement === this.stageNode;
	}

	/**
	 * 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 writeState(state: MediaState): void {
		const media = this.media;
		const message = this.announcer.next(state);
		media.stage = stageState(state);
		media.playing = state.status === 'playing';
		media.muted = state.muted;
		media.rate = state.rate;
		if (message !== '') media.status = message;
		if (Number.isFinite(state.duration)) this.seekMax = state.duration;
		if (state.seekable !== this.seekable) {
			this.seekable = state.seekable;
			this.requestUpdate();
		}
		this.seek.max = this.seekMax;
		this.level = state.muted ? 0 : state.volume;
		this.volume.value = [this.level];
		this.writeProgress(state);
		this.wake();
	}

	/** The controller reports the pending scrub target as the position, so the thumb and the clock never jump back. */
	private writeProgress(state: MediaState): void {
		const media = this.media;
		media.position = state.position;
		media.duration = state.duration;
		this.position = state.position;
		this.seek.value = [state.position];
		this.keepValueText();
		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;
		const valueText = seekValueText(this.media.position, this.media.duration);
		if (thumb && valueText !== '' && thumb.getAttribute('aria-valuetext') !== valueText) {
			thumb.setAttribute('aria-valuetext', 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.media.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 `controlsHidden` on the store so the `data-controls-hidden` binding patches in the same turn.
	 *
	 * @remarks
	 * A render is deferred, and a touch tap or a pointer move must show the result immediately. The path write
	 * notifies the binding without waiting for a render.
	 */
	private hideControls(hidden: boolean): void {
		this.media.controlsHidden = hidden;
	}

	private toggleCaptions(): void {
		this.captions.toggle();
		this.media.status = this.media.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.playback.getState();
		switch (shortcut.type) {
			case 'toggle':
				return void this.playback.toggle();
			case 'skip':
				return this.playback.skip(shortcut.seconds);
			case 'volume': {
				const next = Math.round((state.volume + shortcut.delta) * 100) / 100;
				if (shortcut.delta > 0 && state.muted) this.playback.setMuted(false);
				this.playback.setVolume(next);
				this.media.status = `Volume ${Math.round(this.playback.getState().volume * 100)}%`;
				return;
			}
			case 'mute':
				return this.playback.toggleMuted();
			case 'captions':
				return this.toggleCaptions();
			case 'fullscreen':
				return this.toggleFullscreen();
			case 'jump':
				return this.playback.seek(state.duration * shortcut.fraction);
			case 'start':
				return this.playback.seek(0);
			case 'end':
				return this.playback.seek(state.duration);
		}
	}

	/**
	 * 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.media.stage === 'playing') {
			if (this.media.controlsHidden) this.wake();
			else this.hideControls(true);
		} else void this.playback.toggle();
	}

	private cycleRate(): void {
		this.playback.setRate(Number(cycleValue(RATES, String(this.playback.getState().rate))));
		this.media.status = `Speed ${this.playback.getState().rate}x`;
	}

	/** The slider works in seconds and dispatches `input` only for the reader, never for the position written to it. */
	private onSeek(): void {
		this.playback.scrub(this.seek.value[0]);
	}

	private onVolume(): void {
		const level = this.volume.value[0];
		this.playback.setVolume(level);
		if (level > 0) this.playback.setMuted(false);
	}

	override render() {
		const media = this.$.media;
		return (
			<>
				<div
					data-stage
					data-state={media.stage}
					data-controls-hidden={media.controlsHidden.map((hidden) => (hidden ? '' : undefined))}
					role="group"
					aria-label="Video player"
					aria-describedby="video-player-store-app-help"
					tabindex="0"
					on:keydown={() => this.wake()}
					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.playback.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={media.stage.map((stage) => stage !== 'error')}>
						<p data-error-message>Could not load the video</p>
						<RuiButton size="sm" data-retry on:click={() => void this.playback.retry()}>
							Retry
						</RuiButton>
					</div>
					<div data-controls>
						<RuiButton
							variant="ghost"
							square
							data-playback
							aria-label="Play"
							pressed={media.playing}
							on:click={() => void this.playback.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>{media.position.map(formatMediaTime)}</span>
							<RuiSlider
								data-seek
								label="Seek"
								min={0}
								max={this.seekMax}
								step={0.01}
								value={this.position}
								disabled={!this.seekable}
								on:input={() => this.onSeek()}
							/>
							<span data-duration>{media.duration.map(formatMediaTime)}</span>
						</div>
						<RuiButton
							variant="ghost"
							square
							data-mute
							aria-label="Mute"
							pressed={media.muted}
							on:click={() => this.playback.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:input={() => this.onVolume()}
							/>
						</div>
						<RuiButton
							variant="ghost"
							data-rate
							aria-label={media.rate.map((rate) => `Speed ${rate}x`)}
							on:click={() => this.cycleRate()}
						>
							{media.rate.map((rate) => `${rate}x`)}
						</RuiButton>
						<RuiButton
							variant="ghost"
							square
							data-captions
							aria-label="Captions"
							pressed={media.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={media.fullscreenAvailable.map((available) => !available)}
							pressed={media.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">
						{media.status}
					</p>
				</div>
				<span data-help hidden id="video-player-store-app-help">
					{HELP}
				</span>
			</>
		);
	}
}
```

```ts title="video-player.data.ts"
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' };

/** The player's keys as hotkey strings, and what each asks the player to do. */
export const SHORTCUTS: ReadonlyMap<string, Shortcut> = new Map<string, Shortcut>([
	['Space', { 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']);

/**
 * Whether the focused control keeps this key, so the player declines it.
 *
 * @remarks
 * A button keeps Space and Enter, which activate it. A slider thumb keeps the arrows, Home, End and the page keys,
 * which move it; letters and digits still reach the player. The slider rule stays although the slider prevents the
 * keys it handles, because a disabled slider prevents nothing.
 */
export function isOwnedByControl(event: Pick<KeyboardEvent, 'key' | 'target'>): boolean {
	const target = event.target as Element;
	if (target.closest('button') && (event.key === ' ' || event.key === 'Enter')) return true;
	return target.closest('[role="slider"]') !== null && SLIDER_KEYS.has(event.key);
}

/**
 * Seconds each key on the seek thumb moves the playback by, as hotkey strings.
 *
 * @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 before the
 * slider does and leaves it Home and End.
 */
export const SEEK_KEYS: ReadonlyMap<string, number> = new Map([
	['ArrowRight', SEEK_STEP],
	['ArrowUp', SEEK_STEP],
	['ArrowLeft', -SEEK_STEP],
	['ArrowDown', -SEEK_STEP],
	['PageUp', LONG_SEEK_STEP],
	['PageDown', -LONG_SEEK_STEP],
]);

/** 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,
	}));
}
```

```ts title="video-player.loader.ts"
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);
}
```

```css title="video-player.css"
.primitive-example:has(
	> video-player-element,
	> [data-controller='video-player'],
	> video-player-app,
	> video-player-store-app,
	> [data-example='video-player']
) {
	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;
	}
}
```

`render()` never reads a store path. `{this.media.position}` would subscribe the whole view to every frame; `{this.$.media.position}` patches one node. `map` covers a single-field projection such as each clock. `stage` is one store path, written from the controller's status in the same callback as the rest of the snapshot.

`render()` still reads private fields for the sliders: `seekMax` and `seekable` so the helper can stamp `max` and `disabled` when the clip is ready, and `position` and `level` so a render keeps the thumbs where they are. The fields are not reactive, so writing them per frame runs no render; `requestUpdate()` runs only when the clip becomes seekable. A value written only on the slider would not last: the next render puts the helper's snapshot back. The per-frame `value`, the buffered layer and the thumb's `aria-valuetext` are written to the slider by hand: those nodes are not positions in this host's tree that a binding can own. `data-controls-hidden` is a store path, so a touch tap hides or shows the bar in the same turn without waiting for a render. `fullscreenchange` writes `media.fullscreen` the same way.

Compared with the original component, play, mute and speed no longer redraw the stage: they are bindings too, the error panel's `hidden` on `media.stage` included. The cost is the slider writes the helper still forces, and one render when the clip becomes seekable.

</RecipePattern>

<RecipePattern id="plain">

The plain form of the [Video player](/docs/recipes/video-player), the same files that page runs. It has no store and no `this.$`: it writes the DOM from the controller callbacks.

```ts title="video-player.script.ts"
import '@ecopages/radiant-ui/slider';
import type { RuiSliderElement } from '@ecopages/radiant-ui/slider';
import {
	CaptionsController,
	HotkeyController,
	MediaController,
	type MediaState,
} from '@ecopages/radiant-ui/controllers';
import { cycleValue, formatMediaTime } from '@ecopages/radiant-ui/helpers';
import {
	Announcer,
	CAPTIONS,
	HIDE_CONTROLS_MS,
	RATES,
	SEEK_KEYS,
	SHORTCUTS,
	bufferedSegments,
	isOwnedByControl,
	seekValueText,
	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', wake, { 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('input', () => media.scrub(seek.value[0]), { signal });

	volume.addEventListener(
		'input',
		() => {
			const level = volume.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 stageKeys = new HotkeyController({
		getTarget: () => stage,
		hotkeys: Array.from(SHORTCUTS, ([keys, shortcut]) => ({
			keys,
			handler: (event: KeyboardEvent) => (isOwnedByControl(event) ? false : run(shortcut)),
		})),
	});
	/**
	 * The seek keys listen on the slider in the capture phase, which runs before its own key handler, and stop the
	 * key for the keys the player moves by whole seconds, so the slider's 0.01 s step never applies to an arrow key.
	 */
	const seekKeys = new HotkeyController({
		getTarget: () => seek,
		capture: true,
		hotkeys: Array.from(SEEK_KEYS, ([keys, seconds]) => ({
			keys,
			handler: (event: KeyboardEvent) => {
				event.stopPropagation();
				wake();
				media.skip(seconds);
			},
		})),
	});

	const valueTextObserver = new MutationObserver(keepValueText);
	valueTextObserver.observe(seekThumb, { attributes: true, attributeFilter: ['aria-valuetext'] });
	fullscreen.hidden = !document.fullscreenEnabled;
	captionsController.attach();
	media.attach();
	stageKeys.attach();
	seekKeys.attach();
	void media.load(video.dataset.src!);
	return () => {
		listeners.abort();
		clearTimeout(hideTimer);
		valueTextObserver.disconnect();
		stageKeys.destroy();
		seekKeys.destroy();
		captionsController.destroy();
		media.destroy();
	};
}
```

```ts title="video-player.data.ts"
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' };

/** The player's keys as hotkey strings, and what each asks the player to do. */
export const SHORTCUTS: ReadonlyMap<string, Shortcut> = new Map<string, Shortcut>([
	['Space', { 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']);

/**
 * Whether the focused control keeps this key, so the player declines it.
 *
 * @remarks
 * A button keeps Space and Enter, which activate it. A slider thumb keeps the arrows, Home, End and the page keys,
 * which move it; letters and digits still reach the player. The slider rule stays although the slider prevents the
 * keys it handles, because a disabled slider prevents nothing.
 */
export function isOwnedByControl(event: Pick<KeyboardEvent, 'key' | 'target'>): boolean {
	const target = event.target as Element;
	if (target.closest('button') && (event.key === ' ' || event.key === 'Enter')) return true;
	return target.closest('[role="slider"]') !== null && SLIDER_KEYS.has(event.key);
}

/**
 * Seconds each key on the seek thumb moves the playback by, as hotkey strings.
 *
 * @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 before the
 * slider does and leaves it Home and End.
 */
export const SEEK_KEYS: ReadonlyMap<string, number> = new Map([
	['ArrowRight', SEEK_STEP],
	['ArrowUp', SEEK_STEP],
	['ArrowLeft', -SEEK_STEP],
	['ArrowDown', -SEEK_STEP],
	['PageUp', LONG_SEEK_STEP],
	['PageDown', -LONG_SEEK_STEP],
]);

/** 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,
	}));
}
```

```ts title="video-player.loader.ts"
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);
}
```

```html title="video-player.html"
<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>
```

```css title="video-player.css"
.primitive-example:has(
	> video-player-element,
	> [data-controller='video-player'],
	> video-player-app,
	> video-player-store-app,
	> [data-example='video-player']
) {
	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` returns the cleanup that undoes it; see [how the examples run](/docs/recipes/overview#how-the-examples-run). This form is here because every recipe keeps a plain baseline. It is not a store rewrite: there is no `render()` to spare. Use it to compare what the component form removes (the queries, the listeners, the copies onto the markup) with what the store adds (one snapshot, path bindings, `map`). For long media, serve the file with range support and give `load()` its URL without a `resolveSource`.

</RecipePattern>

</RecipePatterns>

### Styles

The stylesheet is the original player's `video-player.css`, which also matches `video-player-store-app`. It is the last tab in the files above.
