---
title: Audio player
description: 'A playlist player with seek, volume, loop, shuffle, an LED, Bars or Wave visualizer and tracks you reorder by dragging or from the keyboard, built from the media, audio visualizer, sortable and roving controllers.'
order: 8
---

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: [
			'./audio-player.script.ts',
			'./audio-player.element.ts',
			'./audio-player.component.tsx',
			'./audio-player.controller.ts',
		],
		stylesheets: ['./audio-player.css'],
	},
};

# Audio player

<p class="docs-lede">
	A player with a playlist you reorder: pick a track, scrub through it, and drag a track to where you want it.
</p>

## Goal

A music player, a podcast queue or a lesson playlist: the media is one `audio` element, and the list beside it is data the user edits. The current track keeps playing while the list is reordered, Enter or a click chooses a track, and the whole list works from the keyboard.

## Primitives

- [MediaController](/docs/controllers/media) is the playback core: it loads a track, plays, pauses, seeks and reports one state snapshot, so the player never listens to an `audio` event. The recipe loads each clip through a Blob with its `resolveSource` and `releaseSource` hooks, drives the seek bar with `scrub` (a debounced seek) and `skip`, and reads the position every animation frame from `onProgress`.
- [AudioVisualizerController](/docs/controllers/audio-visualizer) feeds the cover the sound of the `audio` element. Both presets draw on a canvas the visualizer adds to the cover: the LED look (`variant: 'led'`, the default) draws 40 bars of 14 segments, the Bars look (`variant: 'solid'`) draws 40 continuous bars with rounded tops, both with peak caps that hold for 450 ms and then fall, and `wave` draws the waveform edge to edge. `setPreset` swaps one for another while the track plays. Their colors are theme tokens. The bars follow log-spaced bands from 80 Hz to 2.4 kHz, where the clips have their sound, and shape each level with `floorLevel: 0.32` (the clips' noise is a band that is off), `range: 0.66` and `curve: 1.6`, so quiet bands light no segment while peaks reach the top; at rest the LED look shows one dim segment per bar and the solid one a dim hairline, both with no minimum height while playing, so the cover is never empty under reduced motion. The Play click calls `resume()` on the visualizer, which starts the audio context inside the gesture.
- `formatMediaTime` formats the clock and the total, from the [media time helpers](/docs/helpers/media-time).
- [SortableController](/docs/controllers/sortable) lets a track be dragged, or lifted with Space and moved with the arrows, and announces each step. It never moves a node, so the recipe keeps the order itself.
- [reorder](/docs/helpers/ordering) turns the `from` and `to` of a change into the new order.
- [RovingController](/docs/controllers/roving) gives the playlist one tab stop and moves it with the arrows. Its `getEnabled` is `false` while a track is lifted, so the arrows that steer the lifted track do not also move focus.
- `PlaybackOrder` in `audio-player.data` is the order the player steps through: list order or a shuffle, with a loop mode, over tracks it holds by identity. It is plain TypeScript with an injectable random source, and its unit tests need no browser. In a shuffle, Previous steps back through the tracks played and Next returns to the track it left before drawing a new one; choosing a track by hand or toggling the shuffle forgets those.

The recipe composes the design system, so it follows the selected theme: the seek bar and the volume are [`rui-slider`](/docs/forms/slider) elements, the LED, Bars and Wave switch is a [`rui-toolbar`](/docs/actions/toolbar) of three toggle buttons named LED bars, Solid bars and Waveform to the right of the title, and the transport buttons carry the Radiant button classes (`rui-button`, `rui-button--ghost` and `--filled`, `rui-button--square` for icon-only). Loop and shuffle are icon buttons in the same row, with no visible text. The component form renders them with the `RuiSlider`, `RuiToolbar` and `RuiButton` helpers. The plain, element and controller forms write the markup by hand, so they use the light-DOM contracts of the slider (see Custom markup on the slider page) and of the toolbar: a `rui-slider` host holding a root, a track with its fill and one `role="slider"` thumb, with the position seeded in the track's custom properties, and a `rui-toolbar` with `exclusive-toggles` around buttons that carry `data-toggle` and `aria-pressed`. The sound itself is one `audio` element, and the recipe needs no player library.

Left to the recipe: the playlist (the order, which track is current, and `PlaybackOrder` for what Next, Previous and the end of a track do), going on to the next track when the controller reports `ended`, mirroring the state into the buttons, the clock and the seek bar, the status messages, the numbering after a reorder, and the `aria-valuetext` of the two sliders: a `rui-slider` writes its own, the bare value, whenever it repaints, so `ValueText` in `audio-player.data` keeps the player's text on the thumb with a `MutationObserver`. The controller reads the `audio` element's own properties, so the recipe never stores whether it is playing: the `status` of the state says so.

## Example

Choose a track with a click or Enter, press Play or Pause, drag the seek bar, change the volume, and switch the cover between LED, Bars and Wave while it plays. Drag a track to a new place, or press Space on it, move it with the arrow keys and press Space to drop it: the track that is playing keeps playing. When a track ends the next one starts, and the last one stops the player unless the loop is on. The loop button cycles off, all and one, and its accessible name is the mode (`Loop: off`, `Loop: all`, `Loop: one`); it carries no `aria-pressed`, because a pressed state can only say two things. With `all` the last track wraps to the first when it ends, with `one` the same track starts again and Next still moves on, and with `off` the player stops at the end of the playlist with "End of the playlist". The shuffle button is an on and off toggle with the fixed name `Shuffle` and `aria-pressed`. While it is on, Next draws from a bag that holds every track once before any repeats and never plays the same track twice in a row, and Previous walks back through the tracks played. Previous restarts the current track when it has played for more than 3 seconds, in the list order and in a shuffle. Turning shuffle off continues in list order from the current track, and reordering the list keeps the bag and the history on the same tracks. Each change is announced through the status line ("Shuffle on", "Loop: all"). Nothing is stored between visits. Each row is described to a screen reader as "Enter plays, Space picks up to reorder". The seek thumb reads as "0:03 of 0:08" and the volume as "80%", not as the raw number of seconds. The four clips are short tones made for this page: `scripts/generate-audio-player-assets.mjs` renders them with Node alone, and running it again writes the same bytes.

Pick an authoring pattern below; they all behave the same, and the one you pick is remembered on the other recipes.

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

<RecipePattern id="element">

The same behavior as a `RadiantElement`. The markup is authored inside the element and the element finds its parts with `@query`; there is nothing to mount, clean up or run again.

```ts title="audio-player.element.ts"
import { RadiantElement, bindTo, customElement, onEvent, query, state } from '@ecopages/radiant';
import {
	createAudioVisualizerController,
	createMediaController,
	createRovingController,
	createSortableController,
	type MediaState,
} from '@ecopages/radiant-ui/controllers';
import '@ecopages/radiant-ui/slider';
import '@ecopages/radiant-ui/toolbar';
import type { RuiSliderChangeDetail, RuiSliderElement } from '@ecopages/radiant-ui/slider';
import { formatMediaTime, reorder } from '@ecopages/radiant-ui/helpers';
import {
	PLAYLIST_HINT,
	PlaybackOrder,
	SEEK_KEYS,
	ValueText,
	VOLUME,
	blobUrlOf,
	createVisualizers,
	loopLabel,
	nextLoopMode,
	seekValueText,
	shuffleAnnouncement,
	volumeValueText,
	type LoopMode,
	type VisualizerName,
} from './audio-player.data';

type Track = { element: HTMLElement; src: string; title: string; artist: string; length: string };

/**
 * @remarks
 * The authored rows are read once into `tracks`, which holds the order from then on. The text that follows the
 * player (title, artist, clock, status), the toggle and the seek bar are `@state` fields that `@bindTo` copies onto
 * the authored markup, so the element never writes to those nodes itself.
 *
 * Playback is a `MediaController` and the cover is an `AudioVisualizerController`, both created with the element as
 * their host, so they attach when it connects and are destroyed when it leaves: the element never listens to the
 * `audio` element and runs no animation frame loop. What stays here is the playlist: the order, which track is
 * current, going on to the next one when a track ends, and the buttons.
 */
@customElement('audio-player-element')
export class AudioPlayerElement extends RadiantElement {
	@query({ selector: '[data-audio]' }) private audio!: HTMLAudioElement;
	@query({ selector: '[data-cover]' }) private cover!: HTMLElement;
	@query({ selector: '[data-tracks]' }) private list!: HTMLElement;
	@query({ selector: '[data-seek]' }) private seek!: RuiSliderElement;
	@query({ selector: '[data-seek] [role="slider"]' }) private seekThumb!: HTMLElement;
	@query({ selector: '[data-volume-input] [role="slider"]' }) private volumeThumb!: HTMLElement;
	@query({ selector: '[data-track]', all: true }) private rows!: HTMLElement[];
	@query({ selector: '[data-name]', all: true }) private names!: HTMLElement[];
	@query({ selector: '[data-length]', all: true }) private lengths!: HTMLElement[];
	@query({ selector: '[data-number]', all: true }) private numbers!: HTMLElement[];

	@state
	@bindTo({ selector: '[data-title]', text: true })
	heading = '';

	@state
	@bindTo({ selector: '[data-artist]', text: true })
	artist = '';

	@state
	@bindTo({ selector: '[data-elapsed]', text: true })
	elapsed = '0:00';

	@state
	@bindTo({ selector: '[data-total]', text: true })
	total = '';

	@state
	@bindTo({ selector: '[data-status]', text: true })
	status = PLAYLIST_HINT;

	@state
	@bindTo({ selector: '[data-seek]', bool: 'disabled', invert: true })
	seekable = false;

	@state
	@bindTo({ selector: '[data-playback]', attr: 'aria-pressed', map: (playing) => String(playing) })
	playing = false;

	@state
	@bindTo({ selector: '[data-loop]', attr: 'data-mode' })
	loopMode: LoopMode = 'off';

	@state
	@bindTo({ selector: '[data-loop]', attr: 'aria-label' })
	loopName = loopLabel('off');

	@state
	@bindTo({ selector: '[data-shuffle]', attr: 'aria-pressed', map: (on) => String(on) })
	shuffled = false;

	private tracks: Track[] = [];
	private current!: Track;
	private order!: PlaybackOrder<Track>;
	private readonly presets = createVisualizers();
	private readonly seekText = new ValueText();
	private readonly volumeText = new ValueText();

	private readonly media = createMediaController(this, {
		getMedia: () => this.audio,
		resolveSource: blobUrlOf,
		releaseSource: (url) => URL.revokeObjectURL(url),
		clearSourceOnDestroy: true,
		onState: (state) => this.renderState(state),
		onProgress: (state) => this.renderProgress(state),
		onError: () => (this.status = `Could not load ${this.heading}`),
	});

	private readonly visualizer = createAudioVisualizerController(this, {
		getMedia: () => this.audio,
		getTarget: () => this.cover,
		preset: this.presets.led,
	});

	private readonly roving = createRovingController(this, {
		getItems: () => this.tracks.map((track) => track.element),
		getTarget: () => this.list,
		orientation: 'vertical',
		getEnabled: () => this.sortable.getState() === null,
	});

	private readonly sortable = createSortableController(this, {
		preview: true,
		liftKeys: [' '],
		createPlaceholder: () => document.createElement('li'),
		getContainer: () => this.list,
		getItems: () => this.tracks.map((track) => track.element),
		announce: (message) => (this.status = message),
		onChange: ({ item, from, to }) => {
			this.tracks = reorder(this.tracks, from, to);
			this.order.setItems(this.tracks);
			this.list.append(...this.tracks.map((track) => track.element));
			this.numbers.forEach((number, index) => (number.textContent = String(index + 1)));
			this.roving.focus(item);
		},
	});

	constructor() {
		super();
		this.registerCleanupCallback(() => {
			this.seekText.stop();
			this.volumeText.stop();
		});
	}

	override onConnected(): void {
		this.seekText.watch(this.seekThumb);
		this.volumeText.watch(this.volumeThumb);
		this.volumeText.set(volumeValueText(VOLUME));
		this.tracks = this.rows.map((element, index) => ({
			element,
			src: element.dataset.src!,
			title: this.names[index].textContent!,
			artist: element.dataset.artist!,
			length: this.lengths[index].textContent!,
		}));
		this.order = new PlaybackOrder(this.tracks, this.tracks[0]);
		this.loopMode = 'off';
		this.loopName = loopLabel('off');
		this.shuffled = false;
		this.roving.sync();
		this.media.setVolume(VOLUME);
		this.status = PLAYLIST_HINT;
		this.load(this.tracks[0], false);
	}

	/**
	 * The one place the media state reaches the page. A track that was playing and is now `ended` is the cue for the
	 * order to say what follows: seeking a paused track to its end reports `ended` too, and must not start another
	 * track.
	 */
	private renderState(state: MediaState): void {
		const playing = state.status === 'playing';
		const finished = state.status === 'ended' && this.playing;
		if (playing && !this.playing) this.status = `Playing ${this.heading}`;
		this.playing = playing;
		this.seekable = state.seekable && state.status !== 'error';
		if (Number.isFinite(state.duration)) {
			this.seek.max = state.duration;
			this.total = formatMediaTime(state.duration);
		}
		this.renderSeekText();
		if (finished) {
			const following = this.order.ended();
			if (following === undefined) this.status = 'End of the playlist';
			else if (following === this.current) this.restart(true);
			else this.load(following, true);
		}
	}

	/** The controller reports the pending scrub target as the position, so the thumb and the clock never jump back. */
	private renderProgress(state: MediaState): void {
		this.seek.value = [state.position];
		this.elapsed = formatMediaTime(state.position);
		this.renderSeekText();
	}

	private renderSeekText(): void {
		this.seekText.set(seekValueText(this.elapsed, this.total));
	}

	/** 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.
	 */
	@onEvent({ selector: '[data-seek]', type: 'keydown', options: { capture: true } })
	scrubWithKey(event: Event): void {
		const key = event as KeyboardEvent;
		const distance = SEEK_KEYS[key.key];
		if (distance === undefined) return;
		key.preventDefault();
		key.stopPropagation();
		this.media.skip(distance);
	}

	@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);
		this.volumeText.set(volumeValueText(level));
	}

	/**
	 * The toolbar stops a click on a toggle in its own capture handler, so this is delegated in the capture phase on
	 * the element above it. A click on the pressed button is stopped here, which keeps one of the two pressed.
	 */
	@onEvent({ selector: '[data-visualizer]', type: 'click', options: { capture: true } })
	pickVisualizer(event: Event): void {
		const button = (event.target as Element).closest<HTMLElement>('[data-visualizer]')!;
		if (button.getAttribute('aria-pressed') === 'true') event.stopPropagation();
		else this.visualizer.setPreset(this.presets[button.dataset.visualizer as VisualizerName]);
	}

	@onEvent({ selector: '[data-playback]', type: 'click' })
	togglePlayback(): void {
		this.choose(this.current);
	}

	@onEvent({ selector: '[data-previous]', type: 'click' })
	previous(): void {
		const step = this.order.previous(this.media.getState().position);
		if (step.restart) this.restart(false);
		else this.load(step.track, this.keepsPlaying());
	}

	@onEvent({ selector: '[data-next]', type: 'click' })
	next(): void {
		this.load(this.order.next(), this.keepsPlaying());
	}

	@onEvent({ selector: '[data-loop]', type: 'click' })
	cycleLoop(): void {
		this.order.loop = nextLoopMode(this.order.loop);
		this.loopMode = this.order.loop;
		this.loopName = loopLabel(this.order.loop);
		this.status = this.loopName;
	}

	@onEvent({ selector: '[data-shuffle]', type: 'click' })
	toggleShuffle(): void {
		this.order.setShuffle(!this.order.shuffle);
		this.shuffled = this.order.shuffle;
		this.status = shuffleAnnouncement(this.shuffled);
	}

	@onEvent({ selector: '[data-track]', type: 'click' })
	pick(event: Event): void {
		this.choose(this.trackOf(event));
	}

	@onEvent({ selector: '[data-track]', type: 'keydown' })
	pickWithKey(event: Event): void {
		if ((event as KeyboardEvent).key === 'Enter') this.choose(this.trackOf(event));
	}

	private trackOf(event: Event): Track {
		const row = (event.target as Element).closest('[data-track]');
		return this.tracks.find((track) => track.element === row)!;
	}

	private load(track: Track, autoplay: boolean): void {
		this.current = track;
		this.heading = track.title;
		this.artist = track.artist;
		this.elapsed = '0:00';
		this.total = track.length;
		this.seek.value = [0];
		this.tracks.forEach((candidate) => candidate.element.setAttribute('aria-current', String(candidate === track)));
		void this.media.load(track.src, { autoplay });
	}

	/** Plays the current track again from its start, or leaves it paused there. */
	private restart(play: boolean): void {
		this.media.seek(0);
		if (play) void this.media.play();
	}

	/**
	 * A track that is still loading counts as playing, so Next pressed twice while the first one loads keeps the
	 * playlist going.
	 */
	private keepsPlaying(): boolean {
		return ['playing', 'loading'].includes(this.media.getState().status);
	}

	private choose(track: Track): void {
		this.visualizer.resume();
		if (track !== this.current || this.media.getState().status === 'error') {
			this.order.select(track);
			this.load(track, true);
		} else void this.media.toggle();
	}
}
```

```ts title="audio-player.data.ts"
import { bars, logBands, wave } from '@ecopages/radiant-ui/controllers';

export type Track = { id: string; title: string; artist: string; src: string; length: string };

export const tracks: readonly Track[] = [
	{
		id: 'morning-light',
		title: 'Morning Light',
		artist: 'Radiant Demo',
		src: '/assets/audio/morning-light.wav',
		length: '0:08',
	},
	{ id: 'low-tide', title: 'Low Tide', artist: 'Radiant Demo', src: '/assets/audio/low-tide.wav', length: '0:08' },
	{ id: 'neon-rain', title: 'Neon Rain', artist: 'Radiant Demo', src: '/assets/audio/neon-rain.wav', length: '0:09' },
	{
		id: 'paper-planes',
		title: 'Paper Planes',
		artist: 'Radiant Demo',
		src: '/assets/audio/paper-planes.wav',
		length: '0:07',
	},
];

export type VisualizerName = 'led' | 'solid' | 'wave';

/**
 * The three ways to show the sound, each drawn on a canvas that the visualizer adds to the cover: LED-style bars,
 * solid bars with rounded tops, and a waveform that runs edge to edge. Both bar looks have peak caps.
 *
 * @remarks
 * A preset keeps the element it is mounted on, so each player builds its own. All take the cover's colors from the
 * theme's custom properties: `--on-primary` is readable on the cover's gradient in every theme. The bar looks share
 * the bands and the level shaping, so they move alike, keep a padding and draw a dim baseline at rest, so the cover
 * still shows them under `prefers-reduced-motion`, when the controller never draws a frame; the wave has no padding,
 * and the cover's own rounded corners clip it.
 */
const barsShared = {
	mode: 'canvas',
	bands: logBands(40, 80, 2400),
	fftSize: 2048,
	smoothing: 0.6,
	floorLevel: 0.32,
	range: 0.66,
	curve: 1.6,
	padding: 12,
	color: '--on-primary',
	colorEnd: '--secondary-container',
	peaks: { hold: 450, fall: 1.2 },
	idle: 'floor',
} as const;

export const createVisualizers = () => ({
	led: bars({ ...barsShared, variant: 'led', segments: 14, segmentGap: 2, gap: 2 }),
	solid: bars({ ...barsShared, variant: 'solid', gap: 3 }),
	wave: wave({ color: '--on-primary', fill: true, padding: 0 }),
});

export const VOLUME = 0.8;

/**
 * Seconds each key moves the seek slider by.
 *
 * @remarks
 * The slider works in seconds with a step of 0.01, fine enough that the per-frame position write is not rounded to
 * whole seconds and the thumb glides. A step that fine would make an arrow key inaudible, so the arrows and the page
 * keys are handled by the player with these distances, and the slider keeps Home and End.
 */
export const SEEK_KEYS: Readonly<Record<string, number>> = {
	ArrowRight: 1,
	ArrowUp: 1,
	ArrowLeft: -1,
	ArrowDown: -1,
	PageUp: 10,
	PageDown: -10,
};

/**
 * Fetches a clip into a `Blob` and returns an object URL for it, which is the `resolveSource` of the media
 * controller; `URL.revokeObjectURL` is its `releaseSource`.
 *
 * @remarks
 * A media element can only seek in a file whose server answers range requests, and many development and preview
 * servers do not. The clips here are short, so each is played from memory, which always seeks. For long media serve
 * the file with range support and load its URL directly.
 */
export async function blobUrlOf(url: string): Promise<string> {
	const response = await fetch(url);
	if (!response.ok) throw new Error(`${response.status} ${response.statusText} for ${url}`);
	return URL.createObjectURL(await response.blob());
}

/** The `aria-valuetext` of the seek thumb, such as `1:15 of 4:00`, from the clock and the total as they are shown. */
export function seekValueText(elapsed: string, total: string): string {
	return `${elapsed} of ${total}`;
}

/** The `aria-valuetext` of the volume thumb, such as `80%`. */
export function volumeValueText(level: number): string {
	return `${Math.round(level * 100)}%`;
}

/**
 * Keeps a text as the `aria-valuetext` of a slider thumb.
 *
 * @remarks
 * The slider writes its own `aria-valuetext`, the bare value, whenever it repaints, which is a later update than the
 * one that changed the value. A single write would be overwritten with "12.31" seconds or "0.80", so a
 * `MutationObserver` puts the text back. The media controller reports its first state when it attaches, which can be
 * before the player has a thumb to watch, so `set()` keeps the text and `watch()` writes it; call `watch()` again
 * when a render has replaced the thumb.
 */
export class ValueText {
	private text = '';
	private thumb: HTMLElement | undefined;
	private readonly observer = new MutationObserver(() => this.apply());

	watch(thumb: HTMLElement): void {
		this.observer.disconnect();
		this.thumb = thumb;
		this.observer.observe(thumb, { attributes: true, attributeFilter: ['aria-valuetext'] });
		this.apply();
	}

	set(text: string): void {
		this.text = text;
		this.apply();
	}

	stop(): void {
		this.observer.disconnect();
	}

	private apply(): void {
		if (this.thumb && this.thumb.getAttribute('aria-valuetext') !== this.text) {
			this.thumb.setAttribute('aria-valuetext', this.text);
		}
	}
}

/** The status the player starts with, until a track is picked. */
export const PLAYLIST_HINT = 'Pick a track, or drag one to reorder the playlist';

/** What the playlist rows are described by, so a screen reader user learns the keys the rows answer to. */
export const PLAYLIST_HELP = 'Enter plays, Space picks up to reorder';

export type LoopMode = 'off' | 'all' | 'one';

const LOOP_CYCLE: Readonly<Record<LoopMode, LoopMode>> = { off: 'all', all: 'one', one: 'off' };

/** The loop mode after `mode`: off, all, one and back to off. */
export function nextLoopMode(mode: LoopMode): LoopMode {
	return LOOP_CYCLE[mode];
}

/**
 * The accessible name of the loop button, which changes with the mode, such as `Loop: all`, and is also the polite
 * announcement of the change.
 *
 * @remarks
 * The button has three states, so it carries no `aria-pressed`: a pressed state can say only two.
 */
export function loopLabel(mode: LoopMode): string {
	return `Loop: ${mode}`;
}

/** The announcement of the shuffle toggle; its accessible name stays `Shuffle`. */
export function shuffleAnnouncement(on: boolean): string {
	return on ? 'Shuffle on' : 'Shuffle off';
}

/** Seconds a track must have played for Previous to restart it instead of moving to the one before. */
export const RESTART_AFTER = 3;

/** Where Previous goes: `restart` means to the start of `track`, which is the current one, and not to another. */
export type Step<T> = { track: T; restart: boolean };

/**
 * The order the player steps through: the list order, or a shuffle, with a loop mode.
 *
 * @remarks
 * Tracks are held by identity, never by index, so reordering the list with `setItems` keeps a shuffle's bag and
 * history pointing at the same tracks. The shuffle is a bag: every track is played once before any is played
 * again, and the track that just played is never drawn first from the next bag. `random` returns a number from 0
 * up to but not including 1, as `Math.random` does, so a test can supply a fixed sequence. The tracks are the same
 * set for the life of the order; `setItems` takes the same tracks in a new order.
 *
 * The `next` and `previous` of a person's click always move and wrap; `ended` is the end of a track, which stops
 * at the end of the playlist unless the loop mode is `all`, and repeats the track when it is `one`.
 */
export class PlaybackOrder<T> {
	loop: LoopMode = 'off';
	private items: readonly T[];
	private bag: T[] = [];
	private history: T[] = [];
	private forward: T[] = [];
	private shuffled = false;

	constructor(
		items: readonly T[],
		public current: T,
		private readonly random: () => number = Math.random,
	) {
		this.items = items;
	}

	get shuffle(): boolean {
		return this.shuffled;
	}

	/** Turns the shuffle on, with a full bag of the tracks that are not the current one, or off, to list order. */
	setShuffle(on: boolean): void {
		this.shuffled = on;
		this.history = [];
		this.forward = [];
		this.bag = on ? this.items.filter((item) => item !== this.current) : [];
	}

	/** Takes the same tracks in a new order; the bag and history keep the tracks they held. */
	setItems(items: readonly T[]): void {
		this.items = items;
	}

	/** A track the person chose: it becomes the current one and leaves the bag, as a track that has been played. */
	select(track: T): void {
		if (track === this.current) return;
		this.history.push(this.current);
		this.forward = [];
		this.bag = this.bag.filter((item) => item !== track);
		this.current = track;
	}

	/** The track a click on Next moves to, which is now the current one. */
	next(): T {
		const to = this.shuffled ? (this.forward.pop() ?? this.draw()) : this.neighbour(1);
		this.advance(to);
		return to;
	}

	/**
	 * What a click on Previous does, given the seconds the current track has played: past `RESTART_AFTER` it
	 * restarts the track, else it moves to the one before in the list, or to the one played before in a shuffle,
	 * and restarts when a shuffle has none. The track a shuffle steps back from is kept, so Next returns to it before
	 * drawing a new one.
	 */
	previous(played: number): Step<T> {
		if (played > RESTART_AFTER) return { track: this.current, restart: true };
		if (!this.shuffled) {
			this.current = this.neighbour(-1);
			return { track: this.current, restart: false };
		}
		const before = this.history.pop();
		if (before === undefined) return { track: this.current, restart: true };
		this.forward.push(this.current);
		this.current = before;
		return { track: before, restart: false };
	}

	/**
	 * The track that follows one that played to its end, `undefined` at the end of the playlist: the last track in
	 * list order, or the last of a bag, with the loop mode `off`.
	 */
	ended(): T | undefined {
		if (this.loop === 'one') return this.current;
		if (this.loop === 'off' && this.isLast()) return undefined;
		return this.next();
	}

	private isLast(): boolean {
		return this.shuffled
			? this.forward.length === 0 && this.unplayed().length === 0
			: this.items.indexOf(this.current) === this.items.length - 1;
	}

	private neighbour(direction: 1 | -1): T {
		const index = this.items.indexOf(this.current);
		return this.items[(index + direction + this.items.length) % this.items.length];
	}

	private unplayed(): T[] {
		return this.bag.filter((item) => item !== this.current);
	}

	private draw(): T {
		if (this.unplayed().length === 0) this.bag = [...this.items];
		const other = this.unplayed();
		const choices = other.length > 0 ? other : this.bag;
		const pick = choices[Math.floor(this.random() * choices.length)];
		this.bag.splice(this.bag.indexOf(pick), 1);
		return pick;
	}

	private advance(to: T): void {
		if (to === this.current) return;
		if (this.shuffled) this.history.push(this.current);
		this.current = to;
	}
}
```

```html title="audio-player.html"
<audio-player-element>
	<audio data-audio preload="auto"></audio>
	<div data-now>
		<span data-cover aria-hidden="true"></span>
		<div data-meta>
			<strong data-title>Morning Light</strong>
			<span data-artist>Radiant Demo</span>
			<rui-toolbar label="Visualizer" exclusive-toggles>
				<div class="rui-toolbar" data-ref="root" role="toolbar" aria-label="Visualizer">
					<button
						type="button"
						class="rui-button rui-button--ghost rui-button--sm"
						data-toggle
						data-visualizer="led"
						aria-label="LED bars"
						aria-pressed="true"
					>
						LED
					</button>
					<button
						type="button"
						class="rui-button rui-button--ghost rui-button--sm"
						data-toggle
						data-visualizer="solid"
						aria-label="Solid bars"
						aria-pressed="false"
					>
						Bars
					</button>
					<button
						type="button"
						class="rui-button rui-button--ghost rui-button--sm"
						data-toggle
						data-visualizer="wave"
						aria-label="Waveform"
						aria-pressed="false"
					>
						Wave
					</button>
				</div>
			</rui-toolbar>
		</div>
	</div>
	<div data-scrub>
		<output data-elapsed>0:00</output>
		<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 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>
		<output data-total>0:08</output>
	</div>
	<div data-controls>
		<button
			type="button"
			class="rui-button rui-button--ghost rui-button--md rui-button--square"
			data-previous
			aria-label="Previous track"
		>
			<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
				<path d="M5 5h2v14H5zM19 5v14L8 12z" fill="currentColor" />
			</svg>
		</button>
		<button
			type="button"
			class="rui-button rui-button--filled rui-button--lg rui-button--square"
			data-playback
			aria-label="Play"
			aria-pressed="false"
		>
			<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false" data-icon="play">
				<path d="M8 5v14l10-7z" fill="currentColor" /></svg
			><svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false" data-icon="pause">
				<path d="M7 5h3v14H7zM14 5h3v14h-3z" fill="currentColor" />
			</svg>
		</button>
		<button
			type="button"
			class="rui-button rui-button--ghost rui-button--md rui-button--square"
			data-next
			aria-label="Next track"
		>
			<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
				<path d="M17 5h2v14h-2zM5 5v14l11-7z" fill="currentColor" />
			</svg>
		</button>
		<button
			type="button"
			class="rui-button rui-button--ghost rui-button--md rui-button--square"
			data-loop
			data-mode="off"
			aria-label="Loop: off"
		>
			<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
				<path d="M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4z" fill="currentColor" />
				<path d="M13 15V9h-1l-2 1v1h1.5v4H13z" fill="currentColor" data-one />
			</svg>
		</button>
		<button
			type="button"
			class="rui-button rui-button--ghost rui-button--md rui-button--square"
			data-shuffle
			aria-label="Shuffle"
			aria-pressed="false"
		>
			<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
				<path
					d="M10.59 9.17 5.41 4 4 5.41l5.17 5.17 1.42-1.41zM14.5 4l2.04 2.04L4 18.59 5.41 20 17.96 7.46 20 9.5V4h-5.5zm.33 9.41-1.41 1.41 3.13 3.13L14.5 20H20v-5.5l-2.04 2.04-3.13-3.13z"
					fill="currentColor"
				/>
			</svg>
		</button>
		<div data-volume>
			<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
				<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"
				/>
			</svg>
			<rui-slider data-volume-input step="0.05" label="Volume" min="0" max="1" value="0.8">
				<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: 80%; --rui-slider-value: 80%"
						>
							<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>
	</div>
	<ol data-tracks aria-label="Playlist">
		<li
			data-track
			aria-describedby="audio-player-element-help"
			data-src="/assets/audio/morning-light.wav"
			data-artist="Radiant Demo"
			tabindex="0"
		>
			<span data-number>1</span>
			<span data-name>Morning Light</span>
			<span data-length>0:08</span>
		</li>
		<li
			data-track
			aria-describedby="audio-player-element-help"
			data-src="/assets/audio/low-tide.wav"
			data-artist="Radiant Demo"
			tabindex="-1"
		>
			<span data-number>2</span>
			<span data-name>Low Tide</span>
			<span data-length>0:08</span>
		</li>
		<li
			data-track
			aria-describedby="audio-player-element-help"
			data-src="/assets/audio/neon-rain.wav"
			data-artist="Radiant Demo"
			tabindex="-1"
		>
			<span data-number>3</span>
			<span data-name>Neon Rain</span>
			<span data-length>0:09</span>
		</li>
		<li
			data-track
			aria-describedby="audio-player-element-help"
			data-src="/assets/audio/paper-planes.wav"
			data-artist="Radiant Demo"
			tabindex="-1"
		>
			<span data-number>4</span>
			<span data-name>Paper Planes</span>
			<span data-length>0:07</span>
		</li>
	</ol>
	<span data-help hidden id="audio-player-element-help">Enter plays, Space picks up to reorder</span>
	<p data-status aria-live="polite">Pick a track, or drag one to reorder the playlist</p>
</audio-player-element>
```

```css title="audio-player.css"
.primitive-example:is(
	[data-example='audio-player'],
	:has(> audio-player-element, > [data-controller='audio-player'], > audio-player-app)
) {
	display: flex;
	flex-direction: column;
	align-items: stretch;
	gap: var(--space-stack);
	box-sizing: border-box;
	width: min(100%, 24rem);
	padding: var(--space-inset);
	border: 1px solid var(--border);
	border-radius: var(--radius-container);
	background: var(--surface);
	color: var(--on-surface);
	box-shadow: var(--shadow-overlay);
	--audio-player-muted: color-mix(in srgb, currentColor 78%, var(--surface));

	& :where([data-now]) {
		display: flex;
		flex-direction: column;
		gap: var(--space-4);
	}

	& :where([data-cover]) {
		display: block;
		position: relative;
		box-sizing: border-box;
		width: 100%;
		height: 7rem;
		overflow: hidden;
		border: 0;
		border-radius: var(--radius-container);
		background: linear-gradient(135deg, var(--primary), color-mix(in srgb, var(--primary) 78%, var(--surface)));
		color: var(--on-primary);
	}

	& :where([data-meta]) {
		display: grid;
		grid-template-columns: minmax(0, 1fr) auto;
		column-gap: var(--space-3);
		row-gap: 0.125rem;
		align-items: start;
		min-width: 0;
	}

	& :where([data-meta] > [data-title], [data-meta] > [data-artist]) {
		grid-column: 1;
		min-width: 0;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	& :where([data-meta] rui-toolbar) {
		grid-column: 2;
		grid-row: 1 / span 2;
		align-self: center;
	}

	& :where([data-title]) {
		font-size: 1.125rem;
		line-height: 1.25;
	}

	& :where([data-meta] > [data-artist]) {
		color: var(--audio-player-muted);
	}

	& :where([data-scrub]) {
		display: flex;
		align-items: center;
		gap: var(--space-3);
	}

	& :where([data-controls]) {
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		gap: var(--space-2);
	}

	& :where([data-elapsed], [data-total]) {
		min-width: 2.5ch;
		font-size: 0.75rem;
		font-variant-numeric: tabular-nums;
		color: var(--audio-player-muted);
	}

	& [data-loop] [data-one],
	& [data-playback] [data-icon='pause'],
	& [data-playback][aria-pressed='true'] [data-icon='play'] {
		display: none;
	}

	& [data-playback][aria-pressed='true'] [data-icon='pause'] {
		display: block;
	}

	& [data-loop][data-mode='one'] [data-one] {
		display: block;
	}

	& [data-loop]:not([data-mode='off']) {
		background: var(--background);
		color: var(--on-background);
		font-weight: 500;
		box-shadow: inset 0 0 0 2px var(--border);
	}

	& :where([data-volume]) {
		display: flex;
		flex: 1;
		align-items: center;
		gap: var(--space-2);
		min-width: 7rem;
		margin-inline-start: auto;
		opacity: 0.85;
	}

	& :where([data-volume] svg) {
		flex: none;
	}

	& :where([data-tracks]) {
		display: flex;
		flex-direction: column;
		gap: var(--space-1);
		margin: 0 calc(var(--space-2) * -1);
		padding: 0 var(--space-1);
	}

	& [data-track] {
		display: grid;
		grid-template-columns: 1.5rem 1fr auto auto;
		align-items: center;
		gap: var(--space-3);
		padding: var(--space-2);
		border: 0;
		border-radius: var(--radius-control);
		background: transparent;
		cursor: grab;
		touch-action: none;
		user-select: none;

		&::after {
			content: '';
			width: 0.75rem;
			height: 1rem;
			background: radial-gradient(circle, currentColor 1.2px, transparent 1.6px) 0 0 / 6px 6px;
			opacity: 0.3;
		}

		&:hover {
			background: var(--surface-container-high);
		}

		&[aria-current='true'] {
			background: color-mix(in srgb, var(--primary) 14%, var(--surface));
			color: var(--primary);
			font-weight: 600;

			& :where([data-number], [data-length]) {
				color: inherit;
			}
		}
	}

	& :where([data-number], [data-length]) {
		font-size: 0.8125rem;
		font-variant-numeric: tabular-nums;
		color: var(--audio-player-muted);
	}

	& [data-sortable-placeholder] {
		min-height: 2.5rem;
		box-sizing: border-box;
		border: 1px dashed color-mix(in srgb, var(--primary) 55%, transparent);
		border-radius: var(--radius-control);
		background: color-mix(in srgb, var(--primary) 8%, transparent);
	}

	& [data-track][data-sortable-drop] {
		box-shadow: none;
	}

	& :where([data-status]) {
		margin: 0;
		font-size: 0.75rem;
		color: var(--audio-player-muted);
	}

	& :where([data-scrub] rui-slider, [data-volume] rui-slider) {
		--rui-slider-track-length: 100%;
		flex: 1;
		min-width: 0;
		margin-inline: calc(var(--rui-slider-thumb-size, 1.25rem) / 2);
	}

	& .rui-slider__header {
		display: none;
	}
}

[data-track][data-sortable-state='lifted'] {
	z-index: 10;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: var(--space-1) var(--space-3);
	border: 1px solid var(--border);
	border-radius: var(--radius-control);
	background: var(--primary);
	color: var(--on-primary);
	font-size: 0.875rem;
	box-shadow: 0 0.5rem 1rem rgb(0 0 0 / 0.25);
	list-style: none;
	cursor: grabbing;
}

[data-track][data-sortable-state='lifted'] > :is([data-number], [data-length]),
[data-track][data-sortable-state='lifted']::after {
	display: none;
}

body:has([data-sortable-state='lifted']) .primitive-example [data-track]:hover {
	background: transparent;
}
```

The element finds its parts with `@query`, and the rows with `@query` and `all: true`, which reads the live DOM on every access, so the numbers are still in document order after a reorder. The authored rows are read once into a `tracks` array of plain objects, so the title, artist and length of a track are never looked up in its row again. The text that follows the player, the toggle and the seek bar are `@state` fields that `@bindTo` copies onto the authored markup: setting `this.elapsed`, `this.playing` or `this.seekable` is the whole update. What the element still writes itself is the seek slider's `value` and `max`, which `@bindTo` has no target for, and the `aria-valuetext` of the two sliders. The observer that keeps it is stopped by a callback registered once in the constructor.

The two controllers are made with `createMediaController(this, ...)` and `createAudioVisualizerController(this, ...)`, so they attach when the element connects and are destroyed when it leaves. The element listens to no media event and runs no animation frame loop. `onState` mirrors the status into `aria-pressed` and the status message, enables the seek bar and starts the next track when the status is `ended`; `onProgress` moves the thumb and the clock on every frame while the track plays. The clips are loaded into a `Blob` through `resolveSource` and revoked through `releaseSource`, so seeking works on servers without range support; serve long media with ranges and load its URL directly. A file that cannot be fetched reaches `onError`, which sets the status to "Could not load" and the track's title, and choosing the track again loads it again.

`@onEvent` covers the clicks, the Enter key and the two sliders' `rui-change` events. The seek slider works in seconds and emits `rui-change` only for the reader, never for the position the player writes to it, so each one goes to `scrub`: the clock follows the thumb at once and the controller seeks once the slider has been idle for 120 ms. A key handler delegated in the capture phase moves the thumb by whole seconds with `skip`, because the slider's own step of 0.01 s, which keeps the per-frame position write smooth, is too small for an arrow key. `onConnected` starts the player again, from the first track and paused, when the element is moved to another parent. Sortable is given `liftKeys: [' ']` so that Enter is left to choose a track.

The LED, Bars and Wave buttons are a `rui-toolbar` with `exclusive-toggles`. The toolbar stops a click on a toggle in its own capture handler, so the element delegates the click in the capture phase from above it and calls `setPreset` with the `bars` or the `wave` preset; a click on the button that is already pressed is stopped there, so one of the two always stays pressed. The cover is an empty element: both presets add their own decorative `canvas` to it, and the stylesheet gives the cover a height, its rounded corners and `overflow: hidden`, which clips the wave to them. The loop and shuffle buttons are `@state` fields (`loopMode`, `loopName`, `shuffled`) bound to the button's `data-mode`, `aria-label` and `aria-pressed`, over a `PlaybackOrder` built when the element connects. What the Radiant form removes: the `mount` function and its registration, the cleanup to return and call, and the re-run after a client-side navigation.

</RecipePattern>

<RecipePattern id="component">

The same behavior as a single `RadiantElement` that owns its markup: the track order, the current track and whether it plays are `@state`, and `render()` draws the player.

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

```tsx title="audio-player.component.tsx"
import { RadiantElement, customElement, onEvent, query, state } from '@ecopages/radiant';
import {
	createAudioVisualizerController,
	createMediaController,
	createRovingController,
	createSortableController,
	type MediaState,
} from '@ecopages/radiant-ui/controllers';
import { RuiButton } from '@ecopages/radiant-ui/button';
import { formatMediaTime, reorder } from '@ecopages/radiant-ui/helpers';
import { RuiSlider } from '@ecopages/radiant-ui/slider';
import type { RuiSliderChangeDetail, RuiSliderElement } from '@ecopages/radiant-ui/slider';
import { RuiToolbar } from '@ecopages/radiant-ui/toolbar';

import {
	PLAYLIST_HELP,
	PLAYLIST_HINT,
	PlaybackOrder,
	SEEK_KEYS,
	ValueText,
	VOLUME,
	blobUrlOf,
	createVisualizers,
	loopLabel,
	nextLoopMode,
	seekValueText,
	shuffleAnnouncement,
	tracks,
	type LoopMode,
	type Track,
	type VisualizerName,
	volumeValueText,
} from './audio-player.data';

/**
 * @remarks
 * The order, the current track, whether it plays and the chosen visualizer are `@state`, so a reorder, a new track
 * or a new visualizer is a render. The clock, the status and the seek position change several times a second, so
 * they never go through the list: the clock and the status are bound with `this.$` and the seek position is
 * written to the slider, which keeps a lifted track from being re-rendered under the pointer.
 *
 * Playback is a `MediaController` and the cover is an `AudioVisualizerController`, both created with the element as
 * their host: the element never listens to the `audio` element and runs no animation frame loop. What stays here is
 * the playlist: the order, which track is current, going on to the next one when a track ends, and the buttons.
 */
@customElement('audio-player-app')
export class AudioPlayerApp extends RadiantElement<{ status: string; elapsed: string; total: string }> {
	@state order = tracks.map((track) => track.id);
	@state current = tracks[0].id;
	@state playing = false;
	@state ready = false;
	@state view: VisualizerName = 'led';
	@state loop: LoopMode = 'off';
	@state shuffled = false;
	@state elapsed = '0:00';
	@state total = tracks[0].length;
	@state duration = 1;
	@state status = PLAYLIST_HINT;

	@query({ selector: '[data-audio]' }) private audio!: HTMLAudioElement;
	@query({ selector: '[data-cover]' }) private cover!: HTMLElement;
	@query({ selector: '[data-seek]' }) private seek!: RuiSliderElement;
	@query({ selector: '[data-volume-input]' }) private volume!: RuiSliderElement;
	@query({ selector: '[data-tracks]' }) private list!: HTMLElement;
	@query({ selector: '[data-track]', all: true }) private rows!: HTMLElement[];

	private focusTrack: string | null = null;
	private playback = new PlaybackOrder(this.order, this.current);
	private level = VOLUME;
	private readonly presets = createVisualizers();
	private readonly seekText = new ValueText();
	private readonly volumeText = new ValueText();

	private readonly media = createMediaController(this, {
		getMedia: () => this.audio,
		resolveSource: blobUrlOf,
		releaseSource: (url) => URL.revokeObjectURL(url),
		clearSourceOnDestroy: true,
		onState: (state) => this.renderState(state),
		onProgress: (state) => this.renderProgress(state),
		onError: () => (this.status = `Could not load ${this.track(this.current).title}`),
	});

	private readonly visualizer = createAudioVisualizerController(this, {
		getMedia: () => this.audio,
		getTarget: () => this.cover,
		preset: this.presets.led,
	});

	private readonly roving = createRovingController(this, {
		getItems: () => this.rows,
		getTarget: () => this.list,
		orientation: 'vertical',
		getEnabled: () => this.sortable.getState() === null,
	});

	private readonly sortable = createSortableController(this, {
		preview: true,
		liftKeys: [' '],
		createPlaceholder: () => document.createElement('li'),
		getContainer: () => this.list,
		getItems: () => this.rows,
		announce: (message) => (this.status = message),
		onChange: ({ item, from, to }) => {
			this.focusTrack = item.dataset.track!;
			this.order = reorder(this.order, from, to);
			this.playback.setItems(this.order);
		},
	});

	private track(id: string): Track {
		return tracks.find((candidate) => candidate.id === id)!;
	}

	private load(id: string, autoplay: boolean): void {
		const track = this.track(id);
		this.current = id;
		this.elapsed = '0:00';
		this.total = track.length;
		this.seek.value = [0];
		void this.media.load(track.src, { autoplay });
	}

	/** Plays the current track again from its start, or leaves it paused there. */
	private restart(play: boolean): void {
		this.media.seek(0);
		if (play) void this.media.play();
	}

	/**
	 * A track that is still loading counts as playing, so Next pressed twice while the first one loads keeps the
	 * playlist going.
	 */
	private keepsPlaying(): boolean {
		return ['playing', 'loading'].includes(this.media.getState().status);
	}

	private next(): void {
		this.load(this.playback.next(), this.keepsPlaying());
	}

	private previous(): void {
		const step = this.playback.previous(this.media.getState().position);
		if (step.restart) this.restart(false);
		else this.load(step.track, this.keepsPlaying());
	}

	private cycleLoop(): void {
		this.playback.loop = nextLoopMode(this.playback.loop);
		this.loop = this.playback.loop;
		this.status = loopLabel(this.loop);
	}

	private toggleShuffle(): void {
		this.playback.setShuffle(!this.playback.shuffle);
		this.shuffled = this.playback.shuffle;
		this.status = shuffleAnnouncement(this.shuffled);
	}

	private choose(id: string): void {
		this.visualizer.resume();
		if (id !== this.current || this.media.getState().status === 'error') {
			this.playback.select(id);
			this.load(id, true);
		} else void this.media.toggle();
	}

	/**
	 * Starts the player on the first track of the current order, paused, each time the element connects.
	 *
	 * @remarks
	 * It runs after the render, so the `audio` element and the cover exist, and again when the element is moved to
	 * another parent. The controllers attach when the element connects, before the first render, when there is no
	 * media yet, so they attach again here.
	 */
	constructor() {
		super();
		this.registerCleanupCallback(() => {
			this.seekText.stop();
			this.volumeText.stop();
		});
	}

	override onConnected(): void {
		this.media.attach();
		this.visualizer.refresh();
		this.media.setVolume(VOLUME);
		this.volumeText.set(volumeValueText(VOLUME));
		this.status = PLAYLIST_HINT;
		this.playback = new PlaybackOrder(this.order, this.order[0]);
		this.loop = 'off';
		this.shuffled = false;
		this.load(this.order[0], false);
	}

	/**
	 * Attaches both list controllers to the list the render produced and focuses the track that was just moved.
	 *
	 * @remarks
	 * The controllers attach when the element connects, before the first render, when no list exists yet; the
	 * `attach()` again resolves the list each controller listens on, and `sync()` gives the roving controller the
	 * rows of the committed list. Every row renders `tabindex="-1"` and the roving controller moves the one tab stop:
	 * a row with no `tabindex` attribute reports `-1` already, so `sync()` would leave it unfocusable. The keyed rows
	 * keep their nodes across renders, so the moved track is the same node, found by its id.
	 */
	protected override updated(): void {
		this.seekText.watch(this.seek.querySelector<HTMLElement>('[role="slider"]')!);
		this.volumeText.watch(this.volume.querySelector<HTMLElement>('[role="slider"]')!);
		this.renderSeekText();
		this.volumeText.set(volumeValueText(this.level));
		this.sortable.attach();
		this.roving.attach();
		this.roving.sync();
		if (this.focusTrack) {
			this.roving.focus(this.rows.find((row) => row.dataset.track === this.focusTrack)!);
			this.focusTrack = null;
		}
	}

	/**
	 * The one place the media state reaches the page. A track that was playing and is now `ended` is the cue for the
	 * order to say what follows: seeking a paused track to its end reports `ended` too, and must not start another
	 * track.
	 */
	private renderState(state: MediaState): void {
		const playing = state.status === 'playing';
		const finished = state.status === 'ended' && this.playing;
		if (playing && !this.playing) this.status = `Playing ${this.track(this.current).title}`;
		this.playing = playing;
		this.ready = state.seekable && state.status !== 'error';
		if (Number.isFinite(state.duration)) {
			this.duration = state.duration;
			this.total = formatMediaTime(state.duration);
		}
		this.renderSeekText();
		if (finished) {
			const following = this.playback.ended();
			if (following === undefined) this.status = 'End of the playlist';
			else if (following === this.current) this.restart(true);
			else this.load(following, true);
		}
	}

	/** The controller reports the pending scrub target as the position, so the thumb and the clock never jump back. */
	private renderProgress(state: MediaState): void {
		this.seek.value = [state.position];
		this.elapsed = formatMediaTime(state.position);
		this.renderSeekText();
	}

	private renderSeekText(): void {
		this.seekText.set(seekValueText(this.elapsed, this.total));
	}

	/**
	 * @remarks
	 * The slider works in seconds and reports `rui-change` only for the reader (a pointer, Home or End), never for the
	 * position `renderProgress` writes to it.
	 */
	private onSeek(event: Event): void {
		this.media.scrub((event as CustomEvent<RuiSliderChangeDetail>).detail.value[0]);
	}

	/**
	 * @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.
	 */
	@onEvent({ selector: '[data-seek]', type: 'keydown', options: { capture: true } })
	onSeekKey(event: KeyboardEvent): void {
		const distance = SEEK_KEYS[event.key];
		if (distance === undefined) return;
		event.preventDefault();
		event.stopPropagation();
		this.media.skip(distance);
	}

	private onVolume(event: Event): void {
		this.level = (event as CustomEvent<RuiSliderChangeDetail>).detail.value[0];
		this.media.setVolume(this.level);
		this.volumeText.set(volumeValueText(this.level));
	}

	private show(view: VisualizerName): void {
		this.view = view;
		this.visualizer.setPreset(this.presets[view]);
	}

	override render() {
		const now = this.track(this.current);
		return (
			<>
				<audio data-audio preload="auto"></audio>
				<div data-now>
					<span data-cover aria-hidden="true"></span>
					<div data-meta>
						<strong data-title>{now.title}</strong>
						<span data-artist>{now.artist}</span>
						<RuiToolbar label="Visualizer">
							<RuiButton
								variant="ghost"
								size="sm"
								data-visualizer="led"
								aria-label="LED bars"
								pressed={this.view === 'led'}
								on:click={() => this.show('led')}
							>
								LED
							</RuiButton>
							<RuiButton
								variant="ghost"
								size="sm"
								data-visualizer="solid"
								aria-label="Solid bars"
								pressed={this.view === 'solid'}
								on:click={() => this.show('solid')}
							>
								Bars
							</RuiButton>
							<RuiButton
								variant="ghost"
								size="sm"
								data-visualizer="wave"
								aria-label="Waveform"
								pressed={this.view === 'wave'}
								on:click={() => this.show('wave')}
							>
								Wave
							</RuiButton>
						</RuiToolbar>
					</div>
				</div>
				<div data-scrub>
					<output data-elapsed>{this.$.elapsed}</output>
					<RuiSlider
						data-seek
						label="Seek"
						min={0}
						max={this.duration}
						step={0.01}
						value={0}
						disabled={!this.ready}
						on:rui-change={(event: Event) => this.onSeek(event)}
					/>
					<output data-total>{this.$.total}</output>
				</div>
				<div data-controls>
					<RuiButton
						variant="ghost"
						square
						data-previous
						aria-label="Previous track"
						on:click={() => this.previous()}
					>
						<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
							<path d="M5 5h2v14H5zM19 5v14L8 12z" fill="currentColor" />
						</svg>
					</RuiButton>
					<RuiButton
						variant="filled"
						size="lg"
						square
						data-playback
						aria-label="Play"
						pressed={this.playing}
						on:click={() => this.choose(this.current)}
					>
						<svg
							viewBox="0 0 24 24"
							width="16"
							height="16"
							aria-hidden="true"
							focusable="false"
							data-icon="play"
						>
							<path d="M8 5v14l10-7z" fill="currentColor" />
						</svg>
						<svg
							viewBox="0 0 24 24"
							width="16"
							height="16"
							aria-hidden="true"
							focusable="false"
							data-icon="pause"
						>
							<path d="M7 5h3v14H7zM14 5h3v14h-3z" fill="currentColor" />
						</svg>
					</RuiButton>
					<RuiButton variant="ghost" square data-next aria-label="Next track" on:click={() => this.next()}>
						<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
							<path d="M17 5h2v14h-2zM5 5v14l11-7z" fill="currentColor" />
						</svg>
					</RuiButton>
					<RuiButton
						variant="ghost"
						square
						data-loop
						data-mode={this.loop}
						aria-label={loopLabel(this.loop)}
						on:click={() => this.cycleLoop()}
					>
						<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
							<path
								d="M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4z"
								fill="currentColor"
							/>
							<path d="M13 15V9h-1l-2 1v1h1.5v4H13z" fill="currentColor" data-one />
						</svg>
					</RuiButton>
					<RuiButton
						variant="ghost"
						square
						data-shuffle
						aria-label="Shuffle"
						pressed={this.shuffled}
						on:click={() => this.toggleShuffle()}
					>
						<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
							<path
								d="M10.59 9.17 5.41 4 4 5.41l5.17 5.17 1.42-1.41zM14.5 4l2.04 2.04L4 18.59 5.41 20 17.96 7.46 20 9.5V4h-5.5zm.33 9.41-1.41 1.41 3.13 3.13L14.5 20H20v-5.5l-2.04 2.04-3.13-3.13z"
								fill="currentColor"
							/>
						</svg>
					</RuiButton>
					<div data-volume>
						<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
							<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"
							/>
						</svg>
						<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>
				</div>
				<ol data-tracks aria-label="Playlist">
					{this.order.map((id, index) => {
						const track = this.track(id);
						return (
							<li
								key={id}
								data-track={id}
								aria-current={id === this.current}
								aria-describedby="audio-player-app-help"
								tabindex="-1"
								on:click={() => this.choose(id)}
								on:keydown={(event: KeyboardEvent) => event.key === 'Enter' && this.choose(id)}
							>
								<span data-number>{index + 1}</span>
								<span data-name>{track.title}</span>
								<span data-length>{track.length}</span>
							</li>
						);
					})}
				</ol>
				<span data-help hidden id="audio-player-app-help">
					{PLAYLIST_HELP}
				</span>
				<p data-status aria-live="polite">
					{this.$.status}
				</p>
			</>
		);
	}
}
```

```ts title="audio-player.data.ts"
import { bars, logBands, wave } from '@ecopages/radiant-ui/controllers';

export type Track = { id: string; title: string; artist: string; src: string; length: string };

export const tracks: readonly Track[] = [
	{
		id: 'morning-light',
		title: 'Morning Light',
		artist: 'Radiant Demo',
		src: '/assets/audio/morning-light.wav',
		length: '0:08',
	},
	{ id: 'low-tide', title: 'Low Tide', artist: 'Radiant Demo', src: '/assets/audio/low-tide.wav', length: '0:08' },
	{ id: 'neon-rain', title: 'Neon Rain', artist: 'Radiant Demo', src: '/assets/audio/neon-rain.wav', length: '0:09' },
	{
		id: 'paper-planes',
		title: 'Paper Planes',
		artist: 'Radiant Demo',
		src: '/assets/audio/paper-planes.wav',
		length: '0:07',
	},
];

export type VisualizerName = 'led' | 'solid' | 'wave';

/**
 * The three ways to show the sound, each drawn on a canvas that the visualizer adds to the cover: LED-style bars,
 * solid bars with rounded tops, and a waveform that runs edge to edge. Both bar looks have peak caps.
 *
 * @remarks
 * A preset keeps the element it is mounted on, so each player builds its own. All take the cover's colors from the
 * theme's custom properties: `--on-primary` is readable on the cover's gradient in every theme. The bar looks share
 * the bands and the level shaping, so they move alike, keep a padding and draw a dim baseline at rest, so the cover
 * still shows them under `prefers-reduced-motion`, when the controller never draws a frame; the wave has no padding,
 * and the cover's own rounded corners clip it.
 */
const barsShared = {
	mode: 'canvas',
	bands: logBands(40, 80, 2400),
	fftSize: 2048,
	smoothing: 0.6,
	floorLevel: 0.32,
	range: 0.66,
	curve: 1.6,
	padding: 12,
	color: '--on-primary',
	colorEnd: '--secondary-container',
	peaks: { hold: 450, fall: 1.2 },
	idle: 'floor',
} as const;

export const createVisualizers = () => ({
	led: bars({ ...barsShared, variant: 'led', segments: 14, segmentGap: 2, gap: 2 }),
	solid: bars({ ...barsShared, variant: 'solid', gap: 3 }),
	wave: wave({ color: '--on-primary', fill: true, padding: 0 }),
});

export const VOLUME = 0.8;

/**
 * Seconds each key moves the seek slider by.
 *
 * @remarks
 * The slider works in seconds with a step of 0.01, fine enough that the per-frame position write is not rounded to
 * whole seconds and the thumb glides. A step that fine would make an arrow key inaudible, so the arrows and the page
 * keys are handled by the player with these distances, and the slider keeps Home and End.
 */
export const SEEK_KEYS: Readonly<Record<string, number>> = {
	ArrowRight: 1,
	ArrowUp: 1,
	ArrowLeft: -1,
	ArrowDown: -1,
	PageUp: 10,
	PageDown: -10,
};

/**
 * Fetches a clip into a `Blob` and returns an object URL for it, which is the `resolveSource` of the media
 * controller; `URL.revokeObjectURL` is its `releaseSource`.
 *
 * @remarks
 * A media element can only seek in a file whose server answers range requests, and many development and preview
 * servers do not. The clips here are short, so each is played from memory, which always seeks. For long media serve
 * the file with range support and load its URL directly.
 */
export async function blobUrlOf(url: string): Promise<string> {
	const response = await fetch(url);
	if (!response.ok) throw new Error(`${response.status} ${response.statusText} for ${url}`);
	return URL.createObjectURL(await response.blob());
}

/** The `aria-valuetext` of the seek thumb, such as `1:15 of 4:00`, from the clock and the total as they are shown. */
export function seekValueText(elapsed: string, total: string): string {
	return `${elapsed} of ${total}`;
}

/** The `aria-valuetext` of the volume thumb, such as `80%`. */
export function volumeValueText(level: number): string {
	return `${Math.round(level * 100)}%`;
}

/**
 * Keeps a text as the `aria-valuetext` of a slider thumb.
 *
 * @remarks
 * The slider writes its own `aria-valuetext`, the bare value, whenever it repaints, which is a later update than the
 * one that changed the value. A single write would be overwritten with "12.31" seconds or "0.80", so a
 * `MutationObserver` puts the text back. The media controller reports its first state when it attaches, which can be
 * before the player has a thumb to watch, so `set()` keeps the text and `watch()` writes it; call `watch()` again
 * when a render has replaced the thumb.
 */
export class ValueText {
	private text = '';
	private thumb: HTMLElement | undefined;
	private readonly observer = new MutationObserver(() => this.apply());

	watch(thumb: HTMLElement): void {
		this.observer.disconnect();
		this.thumb = thumb;
		this.observer.observe(thumb, { attributes: true, attributeFilter: ['aria-valuetext'] });
		this.apply();
	}

	set(text: string): void {
		this.text = text;
		this.apply();
	}

	stop(): void {
		this.observer.disconnect();
	}

	private apply(): void {
		if (this.thumb && this.thumb.getAttribute('aria-valuetext') !== this.text) {
			this.thumb.setAttribute('aria-valuetext', this.text);
		}
	}
}

/** The status the player starts with, until a track is picked. */
export const PLAYLIST_HINT = 'Pick a track, or drag one to reorder the playlist';

/** What the playlist rows are described by, so a screen reader user learns the keys the rows answer to. */
export const PLAYLIST_HELP = 'Enter plays, Space picks up to reorder';

export type LoopMode = 'off' | 'all' | 'one';

const LOOP_CYCLE: Readonly<Record<LoopMode, LoopMode>> = { off: 'all', all: 'one', one: 'off' };

/** The loop mode after `mode`: off, all, one and back to off. */
export function nextLoopMode(mode: LoopMode): LoopMode {
	return LOOP_CYCLE[mode];
}

/**
 * The accessible name of the loop button, which changes with the mode, such as `Loop: all`, and is also the polite
 * announcement of the change.
 *
 * @remarks
 * The button has three states, so it carries no `aria-pressed`: a pressed state can say only two.
 */
export function loopLabel(mode: LoopMode): string {
	return `Loop: ${mode}`;
}

/** The announcement of the shuffle toggle; its accessible name stays `Shuffle`. */
export function shuffleAnnouncement(on: boolean): string {
	return on ? 'Shuffle on' : 'Shuffle off';
}

/** Seconds a track must have played for Previous to restart it instead of moving to the one before. */
export const RESTART_AFTER = 3;

/** Where Previous goes: `restart` means to the start of `track`, which is the current one, and not to another. */
export type Step<T> = { track: T; restart: boolean };

/**
 * The order the player steps through: the list order, or a shuffle, with a loop mode.
 *
 * @remarks
 * Tracks are held by identity, never by index, so reordering the list with `setItems` keeps a shuffle's bag and
 * history pointing at the same tracks. The shuffle is a bag: every track is played once before any is played
 * again, and the track that just played is never drawn first from the next bag. `random` returns a number from 0
 * up to but not including 1, as `Math.random` does, so a test can supply a fixed sequence. The tracks are the same
 * set for the life of the order; `setItems` takes the same tracks in a new order.
 *
 * The `next` and `previous` of a person's click always move and wrap; `ended` is the end of a track, which stops
 * at the end of the playlist unless the loop mode is `all`, and repeats the track when it is `one`.
 */
export class PlaybackOrder<T> {
	loop: LoopMode = 'off';
	private items: readonly T[];
	private bag: T[] = [];
	private history: T[] = [];
	private forward: T[] = [];
	private shuffled = false;

	constructor(
		items: readonly T[],
		public current: T,
		private readonly random: () => number = Math.random,
	) {
		this.items = items;
	}

	get shuffle(): boolean {
		return this.shuffled;
	}

	/** Turns the shuffle on, with a full bag of the tracks that are not the current one, or off, to list order. */
	setShuffle(on: boolean): void {
		this.shuffled = on;
		this.history = [];
		this.forward = [];
		this.bag = on ? this.items.filter((item) => item !== this.current) : [];
	}

	/** Takes the same tracks in a new order; the bag and history keep the tracks they held. */
	setItems(items: readonly T[]): void {
		this.items = items;
	}

	/** A track the person chose: it becomes the current one and leaves the bag, as a track that has been played. */
	select(track: T): void {
		if (track === this.current) return;
		this.history.push(this.current);
		this.forward = [];
		this.bag = this.bag.filter((item) => item !== track);
		this.current = track;
	}

	/** The track a click on Next moves to, which is now the current one. */
	next(): T {
		const to = this.shuffled ? (this.forward.pop() ?? this.draw()) : this.neighbour(1);
		this.advance(to);
		return to;
	}

	/**
	 * What a click on Previous does, given the seconds the current track has played: past `RESTART_AFTER` it
	 * restarts the track, else it moves to the one before in the list, or to the one played before in a shuffle,
	 * and restarts when a shuffle has none. The track a shuffle steps back from is kept, so Next returns to it before
	 * drawing a new one.
	 */
	previous(played: number): Step<T> {
		if (played > RESTART_AFTER) return { track: this.current, restart: true };
		if (!this.shuffled) {
			this.current = this.neighbour(-1);
			return { track: this.current, restart: false };
		}
		const before = this.history.pop();
		if (before === undefined) return { track: this.current, restart: true };
		this.forward.push(this.current);
		this.current = before;
		return { track: before, restart: false };
	}

	/**
	 * The track that follows one that played to its end, `undefined` at the end of the playlist: the last track in
	 * list order, or the last of a bag, with the loop mode `off`.
	 */
	ended(): T | undefined {
		if (this.loop === 'one') return this.current;
		if (this.loop === 'off' && this.isLast()) return undefined;
		return this.next();
	}

	private isLast(): boolean {
		return this.shuffled
			? this.forward.length === 0 && this.unplayed().length === 0
			: this.items.indexOf(this.current) === this.items.length - 1;
	}

	private neighbour(direction: 1 | -1): T {
		const index = this.items.indexOf(this.current);
		return this.items[(index + direction + this.items.length) % this.items.length];
	}

	private unplayed(): T[] {
		return this.bag.filter((item) => item !== this.current);
	}

	private draw(): T {
		if (this.unplayed().length === 0) this.bag = [...this.items];
		const other = this.unplayed();
		const choices = other.length > 0 ? other : this.bag;
		const pick = choices[Math.floor(this.random() * choices.length)];
		this.bag.splice(this.bag.indexOf(pick), 1);
		return pick;
	}

	private advance(to: T): void {
		if (to === this.current) return;
		if (this.shuffled) this.history.push(this.current);
		this.current = to;
	}
}
```

```css title="audio-player.css"
.primitive-example:is(
	[data-example='audio-player'],
	:has(> audio-player-element, > [data-controller='audio-player'], > audio-player-app)
) {
	display: flex;
	flex-direction: column;
	align-items: stretch;
	gap: var(--space-stack);
	box-sizing: border-box;
	width: min(100%, 24rem);
	padding: var(--space-inset);
	border: 1px solid var(--border);
	border-radius: var(--radius-container);
	background: var(--surface);
	color: var(--on-surface);
	box-shadow: var(--shadow-overlay);
	--audio-player-muted: color-mix(in srgb, currentColor 78%, var(--surface));

	& :where([data-now]) {
		display: flex;
		flex-direction: column;
		gap: var(--space-4);
	}

	& :where([data-cover]) {
		display: block;
		position: relative;
		box-sizing: border-box;
		width: 100%;
		height: 7rem;
		overflow: hidden;
		border: 0;
		border-radius: var(--radius-container);
		background: linear-gradient(135deg, var(--primary), color-mix(in srgb, var(--primary) 78%, var(--surface)));
		color: var(--on-primary);
	}

	& :where([data-meta]) {
		display: grid;
		grid-template-columns: minmax(0, 1fr) auto;
		column-gap: var(--space-3);
		row-gap: 0.125rem;
		align-items: start;
		min-width: 0;
	}

	& :where([data-meta] > [data-title], [data-meta] > [data-artist]) {
		grid-column: 1;
		min-width: 0;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	& :where([data-meta] rui-toolbar) {
		grid-column: 2;
		grid-row: 1 / span 2;
		align-self: center;
	}

	& :where([data-title]) {
		font-size: 1.125rem;
		line-height: 1.25;
	}

	& :where([data-meta] > [data-artist]) {
		color: var(--audio-player-muted);
	}

	& :where([data-scrub]) {
		display: flex;
		align-items: center;
		gap: var(--space-3);
	}

	& :where([data-controls]) {
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		gap: var(--space-2);
	}

	& :where([data-elapsed], [data-total]) {
		min-width: 2.5ch;
		font-size: 0.75rem;
		font-variant-numeric: tabular-nums;
		color: var(--audio-player-muted);
	}

	& [data-loop] [data-one],
	& [data-playback] [data-icon='pause'],
	& [data-playback][aria-pressed='true'] [data-icon='play'] {
		display: none;
	}

	& [data-playback][aria-pressed='true'] [data-icon='pause'] {
		display: block;
	}

	& [data-loop][data-mode='one'] [data-one] {
		display: block;
	}

	& [data-loop]:not([data-mode='off']) {
		background: var(--background);
		color: var(--on-background);
		font-weight: 500;
		box-shadow: inset 0 0 0 2px var(--border);
	}

	& :where([data-volume]) {
		display: flex;
		flex: 1;
		align-items: center;
		gap: var(--space-2);
		min-width: 7rem;
		margin-inline-start: auto;
		opacity: 0.85;
	}

	& :where([data-volume] svg) {
		flex: none;
	}

	& :where([data-tracks]) {
		display: flex;
		flex-direction: column;
		gap: var(--space-1);
		margin: 0 calc(var(--space-2) * -1);
		padding: 0 var(--space-1);
	}

	& [data-track] {
		display: grid;
		grid-template-columns: 1.5rem 1fr auto auto;
		align-items: center;
		gap: var(--space-3);
		padding: var(--space-2);
		border: 0;
		border-radius: var(--radius-control);
		background: transparent;
		cursor: grab;
		touch-action: none;
		user-select: none;

		&::after {
			content: '';
			width: 0.75rem;
			height: 1rem;
			background: radial-gradient(circle, currentColor 1.2px, transparent 1.6px) 0 0 / 6px 6px;
			opacity: 0.3;
		}

		&:hover {
			background: var(--surface-container-high);
		}

		&[aria-current='true'] {
			background: color-mix(in srgb, var(--primary) 14%, var(--surface));
			color: var(--primary);
			font-weight: 600;

			& :where([data-number], [data-length]) {
				color: inherit;
			}
		}
	}

	& :where([data-number], [data-length]) {
		font-size: 0.8125rem;
		font-variant-numeric: tabular-nums;
		color: var(--audio-player-muted);
	}

	& [data-sortable-placeholder] {
		min-height: 2.5rem;
		box-sizing: border-box;
		border: 1px dashed color-mix(in srgb, var(--primary) 55%, transparent);
		border-radius: var(--radius-control);
		background: color-mix(in srgb, var(--primary) 8%, transparent);
	}

	& [data-track][data-sortable-drop] {
		box-shadow: none;
	}

	& :where([data-status]) {
		margin: 0;
		font-size: 0.75rem;
		color: var(--audio-player-muted);
	}

	& :where([data-scrub] rui-slider, [data-volume] rui-slider) {
		--rui-slider-track-length: 100%;
		flex: 1;
		min-width: 0;
		margin-inline: calc(var(--rui-slider-thumb-size, 1.25rem) / 2);
	}

	& .rui-slider__header {
		display: none;
	}
}

[data-track][data-sortable-state='lifted'] {
	z-index: 10;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: var(--space-1) var(--space-3);
	border: 1px solid var(--border);
	border-radius: var(--radius-control);
	background: var(--primary);
	color: var(--on-primary);
	font-size: 0.875rem;
	box-shadow: 0 0.5rem 1rem rgb(0 0 0 / 0.25);
	list-style: none;
	cursor: grabbing;
}

[data-track][data-sortable-state='lifted'] > :is([data-number], [data-length]),
[data-track][data-sortable-state='lifted']::after {
	display: none;
}

body:has([data-sortable-state='lifted']) .primitive-example [data-track]:hover {
	background: transparent;
}
```

The order is an array of track ids, so a drop is a new array: `onChange` does not touch the DOM, it writes the reordered ids with `reorder`, and `render()` moves the keyed rows, numbers them again and keeps `aria-current` on the track that plays, which is why the sound is not interrupted. `@query` finds the `audio` element, the cover, the seek input and the rows, and the handlers are JSX `on:*` attributes. The one exception is the key handler of the seek slider, a delegated `@onEvent` in the capture phase, because it has to run before the slider's own.

Playback and the cover belong to `createMediaController(this, ...)` and `createAudioVisualizerController(this, ...)`, so the `audio` element has no handler at all. The controllers attach when the element connects, before the first render, when there is no `audio` yet; `onConnected` runs after the render and attaches them again. `onState` mirrors the status into `playing` and `ready`, which drive `aria-pressed` and the seek bar, and starts the next track when the status is `ended`. The button keeps one name, "Play", as a toggle button should, and the CSS shows the matching icon. The clock and the status change several times a second, so they are bound with `this.$` and never re-render the list; the seek position is the one value written to the DOM by hand, from `onProgress`, because `this.$` binds text positions only.

The seek slider works in seconds, its `max` is the track's duration once the state reports one, and it emits `rui-change` only for the reader. Each one goes to `scrub`, which previews the clock at once and seeks after 120 ms of quiet; its step of 0.01 s keeps the per-frame position write smooth and is too small for an arrow key, so the arrows and the page keys move by whole seconds with `skip` through the capture handler. `updated()` attaches the sortable and roving controllers to the committed list, because they attach before the first render, and focuses the track that moved. Every row renders `tabindex="-1"` and the roving controller owns the one tab stop: a row with no `tabindex` attribute already reports `-1`, so the controller would leave it unfocusable. Each clip goes through `resolveSource` into a `Blob` and is played from memory, so seeking works on servers that do not answer range requests; serve long media with ranges and load its URL directly. A file that cannot be fetched sets the status to "Could not load" and the track's title through `onError`, and choosing it again loads it again. `onConnected` starts the player on the first track, paused, each time the element connects, so an element moved to another parent starts again.

The selected visualizer is `@state`: the LED, Bars and Wave buttons are `RuiButton`s in a `RuiToolbar` whose `pressed` follows it, and a click sets it and calls `setPreset`. The buttons are controlled, so they carry no `data-toggle` and the toolbar leaves their state to the component; that is also why `exclusiveToggles` has nothing to do here and is left off. Both presets draw on a decorative `canvas` the visualizer adds to the cover, so the level never goes through `@state`, which would render the list every frame. The loop mode and the shuffle are `@state` that the buttons render: the loop button's name is `Loop: off`, `Loop: all` or `Loop: one` from the state, and `pressed` follows the shuffle. The visualizer builds nothing when the reader prefers reduced motion.

Compared with the Radiant element above, the markup lives inside the element, so there is nothing to keep in step with the page and the playlist is state you can change, but restyling the structure means editing the class. It also needs the render path on the server to have content before the script runs: this docs build prerenders the tag empty and the client draws it, so the page shows nothing until the script loads, which a page of authored children does not.

</RecipePattern>

<RecipePattern id="controller">

The same behavior as a `RadiantController` attached to the authored markup, which carries `data-controller="audio-player"` on a plain `div`.

```ts title="audio-player.controller.ts"
import { RadiantController, bindTo, controller, onEvent, query, state } from '@ecopages/radiant';
import {
	createAudioVisualizerController,
	createMediaController,
	createRovingController,
	createSortableController,
	type MediaState,
} from '@ecopages/radiant-ui/controllers';
import '@ecopages/radiant-ui/slider';
import '@ecopages/radiant-ui/toolbar';
import type { RuiSliderChangeDetail, RuiSliderElement } from '@ecopages/radiant-ui/slider';
import { formatMediaTime, reorder } from '@ecopages/radiant-ui/helpers';
import {
	PLAYLIST_HINT,
	PlaybackOrder,
	SEEK_KEYS,
	ValueText,
	VOLUME,
	blobUrlOf,
	createVisualizers,
	loopLabel,
	nextLoopMode,
	seekValueText,
	shuffleAnnouncement,
	volumeValueText,
	type LoopMode,
	type VisualizerName,
} from './audio-player.data';

type Track = { element: HTMLElement; src: string; title: string; artist: string; length: string };

/**
 * @remarks
 * The authored rows are read once into `tracks`, which holds the order from then on. The text that follows the player
 * (title, artist, clock, status), the toggle and the seek bar are `@state` fields that `@bindTo` copies onto the
 * authored markup, so the controller never writes to those nodes itself.
 *
 * `createMediaController(this, ...)`, `createAudioVisualizerController(this, ...)`, `createRovingController(this,
 * ...)` and `createSortableController(this, ...)` accept a `RadiantController` as their host, because it has the
 * `registerConnectedCallback` and `registerCleanupCallback` they need: they attach when the registry connects the
 * host and are destroyed when it disconnects. The controller never listens to the `audio` element and runs no
 * animation frame loop; what stays here is the playlist: the order, which track is current, going on to the next
 * one when a track ends, and the buttons.
 */
@controller('audio-player')
export class AudioPlayerController extends RadiantController {
	@query({ selector: '[data-audio]' }) private audio!: HTMLAudioElement;
	@query({ selector: '[data-cover]' }) private cover!: HTMLElement;
	@query({ selector: '[data-tracks]' }) private list!: HTMLElement;
	@query({ selector: '[data-seek]' }) private seek!: RuiSliderElement;
	@query({ selector: '[data-seek] [role="slider"]' }) private seekThumb!: HTMLElement;
	@query({ selector: '[data-volume-input] [role="slider"]' }) private volumeThumb!: HTMLElement;
	@query({ selector: '[data-track]', all: true }) private rows!: HTMLElement[];
	@query({ selector: '[data-name]', all: true }) private names!: HTMLElement[];
	@query({ selector: '[data-length]', all: true }) private lengths!: HTMLElement[];
	@query({ selector: '[data-number]', all: true }) private numbers!: HTMLElement[];

	@state
	@bindTo({ selector: '[data-title]', text: true })
	heading = '';

	@state
	@bindTo({ selector: '[data-artist]', text: true })
	artist = '';

	@state
	@bindTo({ selector: '[data-elapsed]', text: true })
	elapsed = '0:00';

	@state
	@bindTo({ selector: '[data-total]', text: true })
	total = '';

	@state
	@bindTo({ selector: '[data-status]', text: true })
	status = PLAYLIST_HINT;

	@state
	@bindTo({ selector: '[data-seek]', bool: 'disabled', invert: true })
	seekable = false;

	@state
	@bindTo({ selector: '[data-playback]', attr: 'aria-pressed', map: (playing) => String(playing) })
	playing = false;

	@state
	@bindTo({ selector: '[data-loop]', attr: 'data-mode' })
	loopMode: LoopMode = 'off';

	@state
	@bindTo({ selector: '[data-loop]', attr: 'aria-label' })
	loopName = loopLabel('off');

	@state
	@bindTo({ selector: '[data-shuffle]', attr: 'aria-pressed', map: (on) => String(on) })
	shuffled = false;

	private tracks: Track[] = [];
	private current!: Track;
	private order!: PlaybackOrder<Track>;
	private readonly presets = createVisualizers();
	private readonly seekText = new ValueText();
	private readonly volumeText = new ValueText();

	private readonly media = createMediaController(this, {
		getMedia: () => this.audio,
		resolveSource: blobUrlOf,
		releaseSource: (url) => URL.revokeObjectURL(url),
		clearSourceOnDestroy: true,
		onState: (state) => this.renderState(state),
		onProgress: (state) => this.renderProgress(state),
		onError: () => (this.status = `Could not load ${this.heading}`),
	});

	private readonly visualizer = createAudioVisualizerController(this, {
		getMedia: () => this.audio,
		getTarget: () => this.cover,
		preset: this.presets.led,
	});

	private readonly roving = createRovingController(this, {
		getItems: () => this.tracks.map((track) => track.element),
		getTarget: () => this.list,
		orientation: 'vertical',
		getEnabled: () => this.sortable.getState() === null,
	});

	private readonly sortable = createSortableController(this, {
		preview: true,
		liftKeys: [' '],
		createPlaceholder: () => document.createElement('li'),
		getContainer: () => this.list,
		getItems: () => this.tracks.map((track) => track.element),
		announce: (message) => (this.status = message),
		onChange: ({ item, from, to }) => {
			this.tracks = reorder(this.tracks, from, to);
			this.order.setItems(this.tracks);
			this.list.append(...this.tracks.map((track) => track.element));
			this.numbers.forEach((number, index) => (number.textContent = String(index + 1)));
			this.roving.focus(item);
		},
	});

	constructor(host: Element) {
		super(host);
		this.registerCleanupCallback(() => {
			this.seekText.stop();
			this.volumeText.stop();
		});
	}

	override connect(): void {
		super.connect();
		this.seekText.watch(this.seekThumb);
		this.volumeText.watch(this.volumeThumb);
		this.volumeText.set(volumeValueText(VOLUME));
		this.tracks = this.rows.map((element, index) => ({
			element,
			src: element.dataset.src!,
			title: this.names[index].textContent!,
			artist: element.dataset.artist!,
			length: this.lengths[index].textContent!,
		}));
		this.order = new PlaybackOrder(this.tracks, this.tracks[0]);
		this.loopMode = 'off';
		this.loopName = loopLabel('off');
		this.shuffled = false;
		this.roving.sync();
		this.media.setVolume(VOLUME);
		this.status = PLAYLIST_HINT;
		this.load(this.tracks[0], false);
	}

	/**
	 * The one place the media state reaches the page. A track that was playing and is now `ended` is the cue for the
	 * order to say what follows: seeking a paused track to its end reports `ended` too, and must not start another
	 * track.
	 */
	private renderState(state: MediaState): void {
		const playing = state.status === 'playing';
		const finished = state.status === 'ended' && this.playing;
		if (playing && !this.playing) this.status = `Playing ${this.heading}`;
		this.playing = playing;
		this.seekable = state.seekable && state.status !== 'error';
		if (Number.isFinite(state.duration)) {
			this.seek.max = state.duration;
			this.total = formatMediaTime(state.duration);
		}
		this.renderSeekText();
		if (finished) {
			const following = this.order.ended();
			if (following === undefined) this.status = 'End of the playlist';
			else if (following === this.current) this.restart(true);
			else this.load(following, true);
		}
	}

	/** The controller reports the pending scrub target as the position, so the thumb and the clock never jump back. */
	private renderProgress(state: MediaState): void {
		this.seek.value = [state.position];
		this.elapsed = formatMediaTime(state.position);
		this.renderSeekText();
	}

	private renderSeekText(): void {
		this.seekText.set(seekValueText(this.elapsed, this.total));
	}

	/** 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.
	 */
	@onEvent({ selector: '[data-seek]', type: 'keydown', options: { capture: true } })
	scrubWithKey(event: Event): void {
		const key = event as KeyboardEvent;
		const distance = SEEK_KEYS[key.key];
		if (distance === undefined) return;
		key.preventDefault();
		key.stopPropagation();
		this.media.skip(distance);
	}

	@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);
		this.volumeText.set(volumeValueText(level));
	}

	/**
	 * The toolbar stops a click on a toggle in its own capture handler, so this is delegated in the capture phase on
	 * the element above it. A click on the pressed button is stopped here, which keeps one of the two pressed.
	 */
	@onEvent({ selector: '[data-visualizer]', type: 'click', options: { capture: true } })
	pickVisualizer(event: Event): void {
		const button = (event.target as Element).closest<HTMLElement>('[data-visualizer]')!;
		if (button.getAttribute('aria-pressed') === 'true') event.stopPropagation();
		else this.visualizer.setPreset(this.presets[button.dataset.visualizer as VisualizerName]);
	}

	@onEvent({ selector: '[data-playback]', type: 'click' })
	togglePlayback(): void {
		this.choose(this.current);
	}

	@onEvent({ selector: '[data-previous]', type: 'click' })
	previous(): void {
		const step = this.order.previous(this.media.getState().position);
		if (step.restart) this.restart(false);
		else this.load(step.track, this.keepsPlaying());
	}

	@onEvent({ selector: '[data-next]', type: 'click' })
	next(): void {
		this.load(this.order.next(), this.keepsPlaying());
	}

	@onEvent({ selector: '[data-loop]', type: 'click' })
	cycleLoop(): void {
		this.order.loop = nextLoopMode(this.order.loop);
		this.loopMode = this.order.loop;
		this.loopName = loopLabel(this.order.loop);
		this.status = this.loopName;
	}

	@onEvent({ selector: '[data-shuffle]', type: 'click' })
	toggleShuffle(): void {
		this.order.setShuffle(!this.order.shuffle);
		this.shuffled = this.order.shuffle;
		this.status = shuffleAnnouncement(this.shuffled);
	}

	@onEvent({ selector: '[data-track]', type: 'click' })
	pick(event: Event): void {
		this.choose(this.trackOf(event));
	}

	@onEvent({ selector: '[data-track]', type: 'keydown' })
	pickWithKey(event: Event): void {
		if ((event as KeyboardEvent).key === 'Enter') this.choose(this.trackOf(event));
	}

	private trackOf(event: Event): Track {
		const row = (event.target as Element).closest('[data-track]');
		return this.tracks.find((track) => track.element === row)!;
	}

	private load(track: Track, autoplay: boolean): void {
		this.current = track;
		this.heading = track.title;
		this.artist = track.artist;
		this.elapsed = '0:00';
		this.total = track.length;
		this.seek.value = [0];
		this.tracks.forEach((candidate) => candidate.element.setAttribute('aria-current', String(candidate === track)));
		void this.media.load(track.src, { autoplay });
	}

	/** Plays the current track again from its start, or leaves it paused there. */
	private restart(play: boolean): void {
		this.media.seek(0);
		if (play) void this.media.play();
	}

	/**
	 * A track that is still loading counts as playing, so Next pressed twice while the first one loads keeps the
	 * playlist going.
	 */
	private keepsPlaying(): boolean {
		return ['playing', 'loading'].includes(this.media.getState().status);
	}

	private choose(track: Track): void {
		this.visualizer.resume();
		if (track !== this.current || this.media.getState().status === 'error') {
			this.order.select(track);
			this.load(track, true);
		} else void this.media.toggle();
	}
}
```

```ts title="audio-player.data.ts"
import { bars, logBands, wave } from '@ecopages/radiant-ui/controllers';

export type Track = { id: string; title: string; artist: string; src: string; length: string };

export const tracks: readonly Track[] = [
	{
		id: 'morning-light',
		title: 'Morning Light',
		artist: 'Radiant Demo',
		src: '/assets/audio/morning-light.wav',
		length: '0:08',
	},
	{ id: 'low-tide', title: 'Low Tide', artist: 'Radiant Demo', src: '/assets/audio/low-tide.wav', length: '0:08' },
	{ id: 'neon-rain', title: 'Neon Rain', artist: 'Radiant Demo', src: '/assets/audio/neon-rain.wav', length: '0:09' },
	{
		id: 'paper-planes',
		title: 'Paper Planes',
		artist: 'Radiant Demo',
		src: '/assets/audio/paper-planes.wav',
		length: '0:07',
	},
];

export type VisualizerName = 'led' | 'solid' | 'wave';

/**
 * The three ways to show the sound, each drawn on a canvas that the visualizer adds to the cover: LED-style bars,
 * solid bars with rounded tops, and a waveform that runs edge to edge. Both bar looks have peak caps.
 *
 * @remarks
 * A preset keeps the element it is mounted on, so each player builds its own. All take the cover's colors from the
 * theme's custom properties: `--on-primary` is readable on the cover's gradient in every theme. The bar looks share
 * the bands and the level shaping, so they move alike, keep a padding and draw a dim baseline at rest, so the cover
 * still shows them under `prefers-reduced-motion`, when the controller never draws a frame; the wave has no padding,
 * and the cover's own rounded corners clip it.
 */
const barsShared = {
	mode: 'canvas',
	bands: logBands(40, 80, 2400),
	fftSize: 2048,
	smoothing: 0.6,
	floorLevel: 0.32,
	range: 0.66,
	curve: 1.6,
	padding: 12,
	color: '--on-primary',
	colorEnd: '--secondary-container',
	peaks: { hold: 450, fall: 1.2 },
	idle: 'floor',
} as const;

export const createVisualizers = () => ({
	led: bars({ ...barsShared, variant: 'led', segments: 14, segmentGap: 2, gap: 2 }),
	solid: bars({ ...barsShared, variant: 'solid', gap: 3 }),
	wave: wave({ color: '--on-primary', fill: true, padding: 0 }),
});

export const VOLUME = 0.8;

/**
 * Seconds each key moves the seek slider by.
 *
 * @remarks
 * The slider works in seconds with a step of 0.01, fine enough that the per-frame position write is not rounded to
 * whole seconds and the thumb glides. A step that fine would make an arrow key inaudible, so the arrows and the page
 * keys are handled by the player with these distances, and the slider keeps Home and End.
 */
export const SEEK_KEYS: Readonly<Record<string, number>> = {
	ArrowRight: 1,
	ArrowUp: 1,
	ArrowLeft: -1,
	ArrowDown: -1,
	PageUp: 10,
	PageDown: -10,
};

/**
 * Fetches a clip into a `Blob` and returns an object URL for it, which is the `resolveSource` of the media
 * controller; `URL.revokeObjectURL` is its `releaseSource`.
 *
 * @remarks
 * A media element can only seek in a file whose server answers range requests, and many development and preview
 * servers do not. The clips here are short, so each is played from memory, which always seeks. For long media serve
 * the file with range support and load its URL directly.
 */
export async function blobUrlOf(url: string): Promise<string> {
	const response = await fetch(url);
	if (!response.ok) throw new Error(`${response.status} ${response.statusText} for ${url}`);
	return URL.createObjectURL(await response.blob());
}

/** The `aria-valuetext` of the seek thumb, such as `1:15 of 4:00`, from the clock and the total as they are shown. */
export function seekValueText(elapsed: string, total: string): string {
	return `${elapsed} of ${total}`;
}

/** The `aria-valuetext` of the volume thumb, such as `80%`. */
export function volumeValueText(level: number): string {
	return `${Math.round(level * 100)}%`;
}

/**
 * Keeps a text as the `aria-valuetext` of a slider thumb.
 *
 * @remarks
 * The slider writes its own `aria-valuetext`, the bare value, whenever it repaints, which is a later update than the
 * one that changed the value. A single write would be overwritten with "12.31" seconds or "0.80", so a
 * `MutationObserver` puts the text back. The media controller reports its first state when it attaches, which can be
 * before the player has a thumb to watch, so `set()` keeps the text and `watch()` writes it; call `watch()` again
 * when a render has replaced the thumb.
 */
export class ValueText {
	private text = '';
	private thumb: HTMLElement | undefined;
	private readonly observer = new MutationObserver(() => this.apply());

	watch(thumb: HTMLElement): void {
		this.observer.disconnect();
		this.thumb = thumb;
		this.observer.observe(thumb, { attributes: true, attributeFilter: ['aria-valuetext'] });
		this.apply();
	}

	set(text: string): void {
		this.text = text;
		this.apply();
	}

	stop(): void {
		this.observer.disconnect();
	}

	private apply(): void {
		if (this.thumb && this.thumb.getAttribute('aria-valuetext') !== this.text) {
			this.thumb.setAttribute('aria-valuetext', this.text);
		}
	}
}

/** The status the player starts with, until a track is picked. */
export const PLAYLIST_HINT = 'Pick a track, or drag one to reorder the playlist';

/** What the playlist rows are described by, so a screen reader user learns the keys the rows answer to. */
export const PLAYLIST_HELP = 'Enter plays, Space picks up to reorder';

export type LoopMode = 'off' | 'all' | 'one';

const LOOP_CYCLE: Readonly<Record<LoopMode, LoopMode>> = { off: 'all', all: 'one', one: 'off' };

/** The loop mode after `mode`: off, all, one and back to off. */
export function nextLoopMode(mode: LoopMode): LoopMode {
	return LOOP_CYCLE[mode];
}

/**
 * The accessible name of the loop button, which changes with the mode, such as `Loop: all`, and is also the polite
 * announcement of the change.
 *
 * @remarks
 * The button has three states, so it carries no `aria-pressed`: a pressed state can say only two.
 */
export function loopLabel(mode: LoopMode): string {
	return `Loop: ${mode}`;
}

/** The announcement of the shuffle toggle; its accessible name stays `Shuffle`. */
export function shuffleAnnouncement(on: boolean): string {
	return on ? 'Shuffle on' : 'Shuffle off';
}

/** Seconds a track must have played for Previous to restart it instead of moving to the one before. */
export const RESTART_AFTER = 3;

/** Where Previous goes: `restart` means to the start of `track`, which is the current one, and not to another. */
export type Step<T> = { track: T; restart: boolean };

/**
 * The order the player steps through: the list order, or a shuffle, with a loop mode.
 *
 * @remarks
 * Tracks are held by identity, never by index, so reordering the list with `setItems` keeps a shuffle's bag and
 * history pointing at the same tracks. The shuffle is a bag: every track is played once before any is played
 * again, and the track that just played is never drawn first from the next bag. `random` returns a number from 0
 * up to but not including 1, as `Math.random` does, so a test can supply a fixed sequence. The tracks are the same
 * set for the life of the order; `setItems` takes the same tracks in a new order.
 *
 * The `next` and `previous` of a person's click always move and wrap; `ended` is the end of a track, which stops
 * at the end of the playlist unless the loop mode is `all`, and repeats the track when it is `one`.
 */
export class PlaybackOrder<T> {
	loop: LoopMode = 'off';
	private items: readonly T[];
	private bag: T[] = [];
	private history: T[] = [];
	private forward: T[] = [];
	private shuffled = false;

	constructor(
		items: readonly T[],
		public current: T,
		private readonly random: () => number = Math.random,
	) {
		this.items = items;
	}

	get shuffle(): boolean {
		return this.shuffled;
	}

	/** Turns the shuffle on, with a full bag of the tracks that are not the current one, or off, to list order. */
	setShuffle(on: boolean): void {
		this.shuffled = on;
		this.history = [];
		this.forward = [];
		this.bag = on ? this.items.filter((item) => item !== this.current) : [];
	}

	/** Takes the same tracks in a new order; the bag and history keep the tracks they held. */
	setItems(items: readonly T[]): void {
		this.items = items;
	}

	/** A track the person chose: it becomes the current one and leaves the bag, as a track that has been played. */
	select(track: T): void {
		if (track === this.current) return;
		this.history.push(this.current);
		this.forward = [];
		this.bag = this.bag.filter((item) => item !== track);
		this.current = track;
	}

	/** The track a click on Next moves to, which is now the current one. */
	next(): T {
		const to = this.shuffled ? (this.forward.pop() ?? this.draw()) : this.neighbour(1);
		this.advance(to);
		return to;
	}

	/**
	 * What a click on Previous does, given the seconds the current track has played: past `RESTART_AFTER` it
	 * restarts the track, else it moves to the one before in the list, or to the one played before in a shuffle,
	 * and restarts when a shuffle has none. The track a shuffle steps back from is kept, so Next returns to it before
	 * drawing a new one.
	 */
	previous(played: number): Step<T> {
		if (played > RESTART_AFTER) return { track: this.current, restart: true };
		if (!this.shuffled) {
			this.current = this.neighbour(-1);
			return { track: this.current, restart: false };
		}
		const before = this.history.pop();
		if (before === undefined) return { track: this.current, restart: true };
		this.forward.push(this.current);
		this.current = before;
		return { track: before, restart: false };
	}

	/**
	 * The track that follows one that played to its end, `undefined` at the end of the playlist: the last track in
	 * list order, or the last of a bag, with the loop mode `off`.
	 */
	ended(): T | undefined {
		if (this.loop === 'one') return this.current;
		if (this.loop === 'off' && this.isLast()) return undefined;
		return this.next();
	}

	private isLast(): boolean {
		return this.shuffled
			? this.forward.length === 0 && this.unplayed().length === 0
			: this.items.indexOf(this.current) === this.items.length - 1;
	}

	private neighbour(direction: 1 | -1): T {
		const index = this.items.indexOf(this.current);
		return this.items[(index + direction + this.items.length) % this.items.length];
	}

	private unplayed(): T[] {
		return this.bag.filter((item) => item !== this.current);
	}

	private draw(): T {
		if (this.unplayed().length === 0) this.bag = [...this.items];
		const other = this.unplayed();
		const choices = other.length > 0 ? other : this.bag;
		const pick = choices[Math.floor(this.random() * choices.length)];
		this.bag.splice(this.bag.indexOf(pick), 1);
		return pick;
	}

	private advance(to: T): void {
		if (to === this.current) return;
		if (this.shuffled) this.history.push(this.current);
		this.current = to;
	}
}
```

```html title="audio-player.html"
<div data-controller="audio-player">
	<audio data-audio preload="auto"></audio>
	<div data-now>
		<span data-cover aria-hidden="true"></span>
		<div data-meta>
			<strong data-title>Morning Light</strong>
			<span data-artist>Radiant Demo</span>
			<rui-toolbar label="Visualizer" exclusive-toggles>
				<div class="rui-toolbar" data-ref="root" role="toolbar" aria-label="Visualizer">
					<button
						type="button"
						class="rui-button rui-button--ghost rui-button--sm"
						data-toggle
						data-visualizer="led"
						aria-label="LED bars"
						aria-pressed="true"
					>
						LED
					</button>
					<button
						type="button"
						class="rui-button rui-button--ghost rui-button--sm"
						data-toggle
						data-visualizer="solid"
						aria-label="Solid bars"
						aria-pressed="false"
					>
						Bars
					</button>
					<button
						type="button"
						class="rui-button rui-button--ghost rui-button--sm"
						data-toggle
						data-visualizer="wave"
						aria-label="Waveform"
						aria-pressed="false"
					>
						Wave
					</button>
				</div>
			</rui-toolbar>
		</div>
	</div>
	<div data-scrub>
		<output data-elapsed>0:00</output>
		<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 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>
		<output data-total>0:08</output>
	</div>
	<div data-controls>
		<button
			type="button"
			class="rui-button rui-button--ghost rui-button--md rui-button--square"
			data-previous
			aria-label="Previous track"
		>
			<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
				<path d="M5 5h2v14H5zM19 5v14L8 12z" fill="currentColor" />
			</svg>
		</button>
		<button
			type="button"
			class="rui-button rui-button--filled rui-button--lg rui-button--square"
			data-playback
			aria-label="Play"
			aria-pressed="false"
		>
			<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false" data-icon="play">
				<path d="M8 5v14l10-7z" fill="currentColor" /></svg
			><svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false" data-icon="pause">
				<path d="M7 5h3v14H7zM14 5h3v14h-3z" fill="currentColor" />
			</svg>
		</button>
		<button
			type="button"
			class="rui-button rui-button--ghost rui-button--md rui-button--square"
			data-next
			aria-label="Next track"
		>
			<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
				<path d="M17 5h2v14h-2zM5 5v14l11-7z" fill="currentColor" />
			</svg>
		</button>
		<button
			type="button"
			class="rui-button rui-button--ghost rui-button--md rui-button--square"
			data-loop
			data-mode="off"
			aria-label="Loop: off"
		>
			<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
				<path d="M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4z" fill="currentColor" />
				<path d="M13 15V9h-1l-2 1v1h1.5v4H13z" fill="currentColor" data-one />
			</svg>
		</button>
		<button
			type="button"
			class="rui-button rui-button--ghost rui-button--md rui-button--square"
			data-shuffle
			aria-label="Shuffle"
			aria-pressed="false"
		>
			<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
				<path
					d="M10.59 9.17 5.41 4 4 5.41l5.17 5.17 1.42-1.41zM14.5 4l2.04 2.04L4 18.59 5.41 20 17.96 7.46 20 9.5V4h-5.5zm.33 9.41-1.41 1.41 3.13 3.13L14.5 20H20v-5.5l-2.04 2.04-3.13-3.13z"
					fill="currentColor"
				/>
			</svg>
		</button>
		<div data-volume>
			<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
				<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"
				/>
			</svg>
			<rui-slider data-volume-input step="0.05" label="Volume" min="0" max="1" value="0.8">
				<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: 80%; --rui-slider-value: 80%"
						>
							<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>
	</div>
	<ol data-tracks aria-label="Playlist">
		<li
			data-track
			aria-describedby="audio-player-controller-help"
			data-src="/assets/audio/morning-light.wav"
			data-artist="Radiant Demo"
			tabindex="0"
		>
			<span data-number>1</span>
			<span data-name>Morning Light</span>
			<span data-length>0:08</span>
		</li>
		<li
			data-track
			aria-describedby="audio-player-controller-help"
			data-src="/assets/audio/low-tide.wav"
			data-artist="Radiant Demo"
			tabindex="-1"
		>
			<span data-number>2</span>
			<span data-name>Low Tide</span>
			<span data-length>0:08</span>
		</li>
		<li
			data-track
			aria-describedby="audio-player-controller-help"
			data-src="/assets/audio/neon-rain.wav"
			data-artist="Radiant Demo"
			tabindex="-1"
		>
			<span data-number>3</span>
			<span data-name>Neon Rain</span>
			<span data-length>0:09</span>
		</li>
		<li
			data-track
			aria-describedby="audio-player-controller-help"
			data-src="/assets/audio/paper-planes.wav"
			data-artist="Radiant Demo"
			tabindex="-1"
		>
			<span data-number>4</span>
			<span data-name>Paper Planes</span>
			<span data-length>0:07</span>
		</li>
	</ol>
	<span data-help hidden id="audio-player-controller-help">Enter plays, Space picks up to reorder</span>
	<p data-status aria-live="polite">Pick a track, or drag one to reorder the playlist</p>
</div>
```

```css title="audio-player.css"
.primitive-example:is(
	[data-example='audio-player'],
	:has(> audio-player-element, > [data-controller='audio-player'], > audio-player-app)
) {
	display: flex;
	flex-direction: column;
	align-items: stretch;
	gap: var(--space-stack);
	box-sizing: border-box;
	width: min(100%, 24rem);
	padding: var(--space-inset);
	border: 1px solid var(--border);
	border-radius: var(--radius-container);
	background: var(--surface);
	color: var(--on-surface);
	box-shadow: var(--shadow-overlay);
	--audio-player-muted: color-mix(in srgb, currentColor 78%, var(--surface));

	& :where([data-now]) {
		display: flex;
		flex-direction: column;
		gap: var(--space-4);
	}

	& :where([data-cover]) {
		display: block;
		position: relative;
		box-sizing: border-box;
		width: 100%;
		height: 7rem;
		overflow: hidden;
		border: 0;
		border-radius: var(--radius-container);
		background: linear-gradient(135deg, var(--primary), color-mix(in srgb, var(--primary) 78%, var(--surface)));
		color: var(--on-primary);
	}

	& :where([data-meta]) {
		display: grid;
		grid-template-columns: minmax(0, 1fr) auto;
		column-gap: var(--space-3);
		row-gap: 0.125rem;
		align-items: start;
		min-width: 0;
	}

	& :where([data-meta] > [data-title], [data-meta] > [data-artist]) {
		grid-column: 1;
		min-width: 0;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	& :where([data-meta] rui-toolbar) {
		grid-column: 2;
		grid-row: 1 / span 2;
		align-self: center;
	}

	& :where([data-title]) {
		font-size: 1.125rem;
		line-height: 1.25;
	}

	& :where([data-meta] > [data-artist]) {
		color: var(--audio-player-muted);
	}

	& :where([data-scrub]) {
		display: flex;
		align-items: center;
		gap: var(--space-3);
	}

	& :where([data-controls]) {
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		gap: var(--space-2);
	}

	& :where([data-elapsed], [data-total]) {
		min-width: 2.5ch;
		font-size: 0.75rem;
		font-variant-numeric: tabular-nums;
		color: var(--audio-player-muted);
	}

	& [data-loop] [data-one],
	& [data-playback] [data-icon='pause'],
	& [data-playback][aria-pressed='true'] [data-icon='play'] {
		display: none;
	}

	& [data-playback][aria-pressed='true'] [data-icon='pause'] {
		display: block;
	}

	& [data-loop][data-mode='one'] [data-one] {
		display: block;
	}

	& [data-loop]:not([data-mode='off']) {
		background: var(--background);
		color: var(--on-background);
		font-weight: 500;
		box-shadow: inset 0 0 0 2px var(--border);
	}

	& :where([data-volume]) {
		display: flex;
		flex: 1;
		align-items: center;
		gap: var(--space-2);
		min-width: 7rem;
		margin-inline-start: auto;
		opacity: 0.85;
	}

	& :where([data-volume] svg) {
		flex: none;
	}

	& :where([data-tracks]) {
		display: flex;
		flex-direction: column;
		gap: var(--space-1);
		margin: 0 calc(var(--space-2) * -1);
		padding: 0 var(--space-1);
	}

	& [data-track] {
		display: grid;
		grid-template-columns: 1.5rem 1fr auto auto;
		align-items: center;
		gap: var(--space-3);
		padding: var(--space-2);
		border: 0;
		border-radius: var(--radius-control);
		background: transparent;
		cursor: grab;
		touch-action: none;
		user-select: none;

		&::after {
			content: '';
			width: 0.75rem;
			height: 1rem;
			background: radial-gradient(circle, currentColor 1.2px, transparent 1.6px) 0 0 / 6px 6px;
			opacity: 0.3;
		}

		&:hover {
			background: var(--surface-container-high);
		}

		&[aria-current='true'] {
			background: color-mix(in srgb, var(--primary) 14%, var(--surface));
			color: var(--primary);
			font-weight: 600;

			& :where([data-number], [data-length]) {
				color: inherit;
			}
		}
	}

	& :where([data-number], [data-length]) {
		font-size: 0.8125rem;
		font-variant-numeric: tabular-nums;
		color: var(--audio-player-muted);
	}

	& [data-sortable-placeholder] {
		min-height: 2.5rem;
		box-sizing: border-box;
		border: 1px dashed color-mix(in srgb, var(--primary) 55%, transparent);
		border-radius: var(--radius-control);
		background: color-mix(in srgb, var(--primary) 8%, transparent);
	}

	& [data-track][data-sortable-drop] {
		box-shadow: none;
	}

	& :where([data-status]) {
		margin: 0;
		font-size: 0.75rem;
		color: var(--audio-player-muted);
	}

	& :where([data-scrub] rui-slider, [data-volume] rui-slider) {
		--rui-slider-track-length: 100%;
		flex: 1;
		min-width: 0;
		margin-inline: calc(var(--rui-slider-thumb-size, 1.25rem) / 2);
	}

	& .rui-slider__header {
		display: none;
	}
}

[data-track][data-sortable-state='lifted'] {
	z-index: 10;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: var(--space-1) var(--space-3);
	border: 1px solid var(--border);
	border-radius: var(--radius-control);
	background: var(--primary);
	color: var(--on-primary);
	font-size: 0.875rem;
	box-shadow: 0 0.5rem 1rem rgb(0 0 0 / 0.25);
	list-style: none;
	cursor: grabbing;
}

[data-track][data-sortable-state='lifted'] > :is([data-number], [data-length]),
[data-track][data-sortable-state='lifted']::after {
	display: none;
}

body:has([data-sortable-state='lifted']) .primitive-example [data-track]:hover {
	background: transparent;
}
```

The class is the element form's logic on a `RadiantController`: the same `@query`, `@state` with `@bindTo` and `@onEvent` decorators, with `connect()` in place of `onConnected()`. 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`, `createAudioVisualizerController`, `createRovingController` and `createSortableController` take the controller as their host, as they do an element, so they attach on connect and are destroyed on disconnect. That is the whole cleanup: the media controller pauses the sound, drops its source and revokes the object URLs in a microtask, which a move to another parent cancels because the controller attaches again at once, and `connect()` starts the player again, from the first track and paused, when the element is moved. The Bars and Wave switch is wired as in the element form, with a capture handler delegated above the toolbar, and so are the loop and shuffle buttons.

</RecipePattern>

<RecipePattern id="plain">

A `mount` function wires the controllers to the markup and returns the cleanup that undoes it.

```ts title="audio-player.script.ts"
import '@ecopages/radiant-ui/slider';
import '@ecopages/radiant-ui/toolbar';
import type { RuiSliderChangeDetail, RuiSliderElement } from '@ecopages/radiant-ui/slider';
import {
	AudioVisualizerController,
	MediaController,
	RovingController,
	SortableController,
	type MediaState,
} from '@ecopages/radiant-ui/controllers';
import { formatMediaTime, reorder } from '@ecopages/radiant-ui/helpers';
import {
	PLAYLIST_HINT,
	PlaybackOrder,
	SEEK_KEYS,
	ValueText,
	VOLUME,
	blobUrlOf,
	createVisualizers,
	loopLabel,
	nextLoopMode,
	seekValueText,
	shuffleAnnouncement,
	volumeValueText,
	type VisualizerName,
} from './audio-player.data';

export function mount(root: HTMLElement): () => void {
	const part = <T extends HTMLElement>(selector: string) => root.querySelector<T>(selector)!;
	const audio = part<HTMLAudioElement>('[data-audio]');
	const list = part('[data-tracks]');
	const seek = part<RuiSliderElement>('[data-seek]');
	const volume = part<RuiSliderElement>('[data-volume-input]');
	const toggle = part('[data-playback]');
	const loopButton = part('[data-loop]');
	const shuffleButton = part('[data-shuffle]');
	const status = part('[data-status]');
	const [title, artist, elapsed, total] = ['[data-title]', '[data-artist]', '[data-elapsed]', '[data-total]'].map(
		(selector) => part(selector),
	);
	const seekText = new ValueText();
	const volumeText = new ValueText();
	const listeners = new AbortController();
	const { signal } = listeners;

	let tracks = [...list.children] as HTMLElement[];
	let current = tracks[0];
	let wasPlaying = false;
	const order = new PlaybackOrder(tracks, current);
	const presets = createVisualizers();

	const media = new MediaController({
		getMedia: () => audio,
		resolveSource: blobUrlOf,
		releaseSource: (url) => URL.revokeObjectURL(url),
		clearSourceOnDestroy: true,
		onState: renderState,
		onProgress: renderProgress,
		onError: () => (status.textContent = `Could not load ${title.textContent}`),
	});

	const visualizer = new AudioVisualizerController({
		getMedia: () => audio,
		getTarget: () => part('[data-cover]'),
		preset: presets.led,
	});

	const roving = new RovingController({
		getItems: () => tracks,
		getTarget: () => list,
		orientation: 'vertical',
		getEnabled: () => sortable.getState() === null,
	});

	const sortable = new SortableController({
		preview: true,
		liftKeys: [' '],
		createPlaceholder: () => document.createElement('li'),
		getContainer: () => list,
		getItems: () => tracks,
		announce: (message) => (status.textContent = message),
		onChange: ({ item, from, to }) => {
			tracks = reorder(tracks, from, to);
			order.setItems(tracks);
			list.append(...tracks);
			tracks.forEach((track, index) => (track.querySelector('[data-number]')!.textContent = String(index + 1)));
			roving.focus(item);
		},
	});

	/**
	 * The one place the media state reaches the page. A track that was playing and is now `ended` is the cue for the
	 * order to say what follows: seeking a paused track to its end reports `ended` too, and must not start another
	 * track.
	 */
	function renderState(state: MediaState): void {
		const playing = state.status === 'playing';
		const finished = state.status === 'ended' && wasPlaying;
		toggle.setAttribute('aria-pressed', String(playing));
		if (playing && !wasPlaying) status.textContent = `Playing ${title.textContent}`;
		wasPlaying = playing;
		seek.disabled = !state.seekable || state.status === 'error';
		if (Number.isFinite(state.duration)) {
			seek.max = state.duration;
			total.textContent = formatMediaTime(state.duration);
		}
		renderSeekText();
		if (finished) {
			const following = order.ended();
			if (following === undefined) status.textContent = 'End of the playlist';
			else if (following === current) restart(true);
			else load(following, true);
		}
	}

	/** The controller reports the pending scrub target as the position, so the thumb and the clock never jump back. */
	function renderProgress(state: MediaState): void {
		seek.value = [state.position];
		elapsed.textContent = formatMediaTime(state.position);
		renderSeekText();
	}

	function renderSeekText(): void {
		seekText.set(seekValueText(elapsed.textContent!, total.textContent!));
	}

	function load(track: HTMLElement, autoplay: boolean): void {
		current = track;
		title.textContent = track.querySelector('[data-name]')!.textContent;
		artist.textContent = track.dataset.artist!;
		elapsed.textContent = '0:00';
		total.textContent = track.querySelector('[data-length]')!.textContent;
		seek.value = [0];
		tracks.forEach((candidate) => candidate.setAttribute('aria-current', String(candidate === track)));
		void media.load(track.dataset.src!, { autoplay });
	}

	/** Plays the current track again from its start, or leaves it paused there. */
	function restart(play: boolean): void {
		media.seek(0);
		if (play) void media.play();
	}

	/**
	 * A track that is still loading counts as playing, so Next pressed twice while the first one loads keeps the
	 * playlist going.
	 */
	const keepsPlaying = () => ['playing', 'loading'].includes(media.getState().status);

	function choose(track: HTMLElement): void {
		visualizer.resume();
		if (track !== current || media.getState().status === 'error') {
			order.select(track);
			load(track, true);
		} else void media.toggle();
	}

	function previous(): void {
		const step = order.previous(media.getState().position);
		if (step.restart) restart(false);
		else load(step.track, keepsPlaying());
	}

	function cycleLoop(): void {
		order.loop = nextLoopMode(order.loop);
		loopButton.dataset.mode = order.loop;
		loopButton.setAttribute('aria-label', loopLabel(order.loop));
		status.textContent = loopLabel(order.loop);
	}

	function toggleShuffle(): void {
		order.setShuffle(!order.shuffle);
		shuffleButton.setAttribute('aria-pressed', String(order.shuffle));
		status.textContent = shuffleAnnouncement(order.shuffle);
	}

	seek.addEventListener(
		'rui-change',
		(event) => media.scrub((event as CustomEvent<RuiSliderChangeDetail>).detail.value[0]),
		{ signal },
	);
	seek.addEventListener(
		'keydown',
		(event) => {
			const distance = SEEK_KEYS[event.key];
			if (distance === undefined) return;
			event.preventDefault();
			event.stopPropagation();
			media.skip(distance);
		},
		{ signal, capture: true },
	);
	volume.addEventListener(
		'rui-change',
		(event) => {
			const level = (event as CustomEvent<RuiSliderChangeDetail>).detail.value[0];
			media.setVolume(level);
			volumeText.set(volumeValueText(level));
		},
		{ signal },
	);

	/**
	 * The toolbar stops a click on a toggle in its own capture handler, so this listens higher up. A click on the
	 * pressed button is stopped here, which keeps one of the two pressed.
	 */
	root.addEventListener(
		'click',
		(event) => {
			const button = (event.target as Element).closest<HTMLElement>('[data-visualizer]');
			if (!button) return;
			if (button.getAttribute('aria-pressed') === 'true') event.stopPropagation();
			else visualizer.setPreset(presets[button.dataset.visualizer as VisualizerName]);
		},
		{ signal, capture: true },
	);
	toggle.addEventListener('click', () => choose(current), { signal });
	part('[data-previous]').addEventListener('click', previous, { signal });
	part('[data-next]').addEventListener('click', () => load(order.next(), keepsPlaying()), { signal });
	loopButton.addEventListener('click', cycleLoop, { signal });
	shuffleButton.addEventListener('click', toggleShuffle, { signal });
	list.addEventListener(
		'click',
		(event) => {
			const row = (event.target as Element).closest<HTMLElement>('[data-track]');
			if (row) choose(row);
		},
		{ signal },
	);
	list.addEventListener(
		'keydown',
		(event) => {
			if (event.key === 'Enter') choose((event.target as Element).closest<HTMLElement>('[data-track]')!);
		},
		{ signal },
	);

	seekText.watch(seek.querySelector<HTMLElement>('[role="slider"]')!);
	volumeText.watch(volume.querySelector<HTMLElement>('[role="slider"]')!);
	volumeText.set(volumeValueText(VOLUME));
	media.attach();
	visualizer.attach();
	media.setVolume(VOLUME);
	status.textContent = PLAYLIST_HINT;
	load(current, false);
	sortable.attach();
	roving.attach();
	roving.sync();
	return () => {
		listeners.abort();
		seekText.stop();
		volumeText.stop();
		media.destroy();
		visualizer.destroy();
		sortable.destroy();
		roving.destroy();
		loopButton.dataset.mode = 'off';
		loopButton.setAttribute('aria-label', loopLabel('off'));
		shuffleButton.setAttribute('aria-pressed', 'false');
		status.textContent = PLAYLIST_HINT;
	};
}
```

```ts title="audio-player.data.ts"
import { bars, logBands, wave } from '@ecopages/radiant-ui/controllers';

export type Track = { id: string; title: string; artist: string; src: string; length: string };

export const tracks: readonly Track[] = [
	{
		id: 'morning-light',
		title: 'Morning Light',
		artist: 'Radiant Demo',
		src: '/assets/audio/morning-light.wav',
		length: '0:08',
	},
	{ id: 'low-tide', title: 'Low Tide', artist: 'Radiant Demo', src: '/assets/audio/low-tide.wav', length: '0:08' },
	{ id: 'neon-rain', title: 'Neon Rain', artist: 'Radiant Demo', src: '/assets/audio/neon-rain.wav', length: '0:09' },
	{
		id: 'paper-planes',
		title: 'Paper Planes',
		artist: 'Radiant Demo',
		src: '/assets/audio/paper-planes.wav',
		length: '0:07',
	},
];

export type VisualizerName = 'led' | 'solid' | 'wave';

/**
 * The three ways to show the sound, each drawn on a canvas that the visualizer adds to the cover: LED-style bars,
 * solid bars with rounded tops, and a waveform that runs edge to edge. Both bar looks have peak caps.
 *
 * @remarks
 * A preset keeps the element it is mounted on, so each player builds its own. All take the cover's colors from the
 * theme's custom properties: `--on-primary` is readable on the cover's gradient in every theme. The bar looks share
 * the bands and the level shaping, so they move alike, keep a padding and draw a dim baseline at rest, so the cover
 * still shows them under `prefers-reduced-motion`, when the controller never draws a frame; the wave has no padding,
 * and the cover's own rounded corners clip it.
 */
const barsShared = {
	mode: 'canvas',
	bands: logBands(40, 80, 2400),
	fftSize: 2048,
	smoothing: 0.6,
	floorLevel: 0.32,
	range: 0.66,
	curve: 1.6,
	padding: 12,
	color: '--on-primary',
	colorEnd: '--secondary-container',
	peaks: { hold: 450, fall: 1.2 },
	idle: 'floor',
} as const;

export const createVisualizers = () => ({
	led: bars({ ...barsShared, variant: 'led', segments: 14, segmentGap: 2, gap: 2 }),
	solid: bars({ ...barsShared, variant: 'solid', gap: 3 }),
	wave: wave({ color: '--on-primary', fill: true, padding: 0 }),
});

export const VOLUME = 0.8;

/**
 * Seconds each key moves the seek slider by.
 *
 * @remarks
 * The slider works in seconds with a step of 0.01, fine enough that the per-frame position write is not rounded to
 * whole seconds and the thumb glides. A step that fine would make an arrow key inaudible, so the arrows and the page
 * keys are handled by the player with these distances, and the slider keeps Home and End.
 */
export const SEEK_KEYS: Readonly<Record<string, number>> = {
	ArrowRight: 1,
	ArrowUp: 1,
	ArrowLeft: -1,
	ArrowDown: -1,
	PageUp: 10,
	PageDown: -10,
};

/**
 * Fetches a clip into a `Blob` and returns an object URL for it, which is the `resolveSource` of the media
 * controller; `URL.revokeObjectURL` is its `releaseSource`.
 *
 * @remarks
 * A media element can only seek in a file whose server answers range requests, and many development and preview
 * servers do not. The clips here are short, so each is played from memory, which always seeks. For long media serve
 * the file with range support and load its URL directly.
 */
export async function blobUrlOf(url: string): Promise<string> {
	const response = await fetch(url);
	if (!response.ok) throw new Error(`${response.status} ${response.statusText} for ${url}`);
	return URL.createObjectURL(await response.blob());
}

/** The `aria-valuetext` of the seek thumb, such as `1:15 of 4:00`, from the clock and the total as they are shown. */
export function seekValueText(elapsed: string, total: string): string {
	return `${elapsed} of ${total}`;
}

/** The `aria-valuetext` of the volume thumb, such as `80%`. */
export function volumeValueText(level: number): string {
	return `${Math.round(level * 100)}%`;
}

/**
 * Keeps a text as the `aria-valuetext` of a slider thumb.
 *
 * @remarks
 * The slider writes its own `aria-valuetext`, the bare value, whenever it repaints, which is a later update than the
 * one that changed the value. A single write would be overwritten with "12.31" seconds or "0.80", so a
 * `MutationObserver` puts the text back. The media controller reports its first state when it attaches, which can be
 * before the player has a thumb to watch, so `set()` keeps the text and `watch()` writes it; call `watch()` again
 * when a render has replaced the thumb.
 */
export class ValueText {
	private text = '';
	private thumb: HTMLElement | undefined;
	private readonly observer = new MutationObserver(() => this.apply());

	watch(thumb: HTMLElement): void {
		this.observer.disconnect();
		this.thumb = thumb;
		this.observer.observe(thumb, { attributes: true, attributeFilter: ['aria-valuetext'] });
		this.apply();
	}

	set(text: string): void {
		this.text = text;
		this.apply();
	}

	stop(): void {
		this.observer.disconnect();
	}

	private apply(): void {
		if (this.thumb && this.thumb.getAttribute('aria-valuetext') !== this.text) {
			this.thumb.setAttribute('aria-valuetext', this.text);
		}
	}
}

/** The status the player starts with, until a track is picked. */
export const PLAYLIST_HINT = 'Pick a track, or drag one to reorder the playlist';

/** What the playlist rows are described by, so a screen reader user learns the keys the rows answer to. */
export const PLAYLIST_HELP = 'Enter plays, Space picks up to reorder';

export type LoopMode = 'off' | 'all' | 'one';

const LOOP_CYCLE: Readonly<Record<LoopMode, LoopMode>> = { off: 'all', all: 'one', one: 'off' };

/** The loop mode after `mode`: off, all, one and back to off. */
export function nextLoopMode(mode: LoopMode): LoopMode {
	return LOOP_CYCLE[mode];
}

/**
 * The accessible name of the loop button, which changes with the mode, such as `Loop: all`, and is also the polite
 * announcement of the change.
 *
 * @remarks
 * The button has three states, so it carries no `aria-pressed`: a pressed state can say only two.
 */
export function loopLabel(mode: LoopMode): string {
	return `Loop: ${mode}`;
}

/** The announcement of the shuffle toggle; its accessible name stays `Shuffle`. */
export function shuffleAnnouncement(on: boolean): string {
	return on ? 'Shuffle on' : 'Shuffle off';
}

/** Seconds a track must have played for Previous to restart it instead of moving to the one before. */
export const RESTART_AFTER = 3;

/** Where Previous goes: `restart` means to the start of `track`, which is the current one, and not to another. */
export type Step<T> = { track: T; restart: boolean };

/**
 * The order the player steps through: the list order, or a shuffle, with a loop mode.
 *
 * @remarks
 * Tracks are held by identity, never by index, so reordering the list with `setItems` keeps a shuffle's bag and
 * history pointing at the same tracks. The shuffle is a bag: every track is played once before any is played
 * again, and the track that just played is never drawn first from the next bag. `random` returns a number from 0
 * up to but not including 1, as `Math.random` does, so a test can supply a fixed sequence. The tracks are the same
 * set for the life of the order; `setItems` takes the same tracks in a new order.
 *
 * The `next` and `previous` of a person's click always move and wrap; `ended` is the end of a track, which stops
 * at the end of the playlist unless the loop mode is `all`, and repeats the track when it is `one`.
 */
export class PlaybackOrder<T> {
	loop: LoopMode = 'off';
	private items: readonly T[];
	private bag: T[] = [];
	private history: T[] = [];
	private forward: T[] = [];
	private shuffled = false;

	constructor(
		items: readonly T[],
		public current: T,
		private readonly random: () => number = Math.random,
	) {
		this.items = items;
	}

	get shuffle(): boolean {
		return this.shuffled;
	}

	/** Turns the shuffle on, with a full bag of the tracks that are not the current one, or off, to list order. */
	setShuffle(on: boolean): void {
		this.shuffled = on;
		this.history = [];
		this.forward = [];
		this.bag = on ? this.items.filter((item) => item !== this.current) : [];
	}

	/** Takes the same tracks in a new order; the bag and history keep the tracks they held. */
	setItems(items: readonly T[]): void {
		this.items = items;
	}

	/** A track the person chose: it becomes the current one and leaves the bag, as a track that has been played. */
	select(track: T): void {
		if (track === this.current) return;
		this.history.push(this.current);
		this.forward = [];
		this.bag = this.bag.filter((item) => item !== track);
		this.current = track;
	}

	/** The track a click on Next moves to, which is now the current one. */
	next(): T {
		const to = this.shuffled ? (this.forward.pop() ?? this.draw()) : this.neighbour(1);
		this.advance(to);
		return to;
	}

	/**
	 * What a click on Previous does, given the seconds the current track has played: past `RESTART_AFTER` it
	 * restarts the track, else it moves to the one before in the list, or to the one played before in a shuffle,
	 * and restarts when a shuffle has none. The track a shuffle steps back from is kept, so Next returns to it before
	 * drawing a new one.
	 */
	previous(played: number): Step<T> {
		if (played > RESTART_AFTER) return { track: this.current, restart: true };
		if (!this.shuffled) {
			this.current = this.neighbour(-1);
			return { track: this.current, restart: false };
		}
		const before = this.history.pop();
		if (before === undefined) return { track: this.current, restart: true };
		this.forward.push(this.current);
		this.current = before;
		return { track: before, restart: false };
	}

	/**
	 * The track that follows one that played to its end, `undefined` at the end of the playlist: the last track in
	 * list order, or the last of a bag, with the loop mode `off`.
	 */
	ended(): T | undefined {
		if (this.loop === 'one') return this.current;
		if (this.loop === 'off' && this.isLast()) return undefined;
		return this.next();
	}

	private isLast(): boolean {
		return this.shuffled
			? this.forward.length === 0 && this.unplayed().length === 0
			: this.items.indexOf(this.current) === this.items.length - 1;
	}

	private neighbour(direction: 1 | -1): T {
		const index = this.items.indexOf(this.current);
		return this.items[(index + direction + this.items.length) % this.items.length];
	}

	private unplayed(): T[] {
		return this.bag.filter((item) => item !== this.current);
	}

	private draw(): T {
		if (this.unplayed().length === 0) this.bag = [...this.items];
		const other = this.unplayed();
		const choices = other.length > 0 ? other : this.bag;
		const pick = choices[Math.floor(this.random() * choices.length)];
		this.bag.splice(this.bag.indexOf(pick), 1);
		return pick;
	}

	private advance(to: T): void {
		if (to === this.current) return;
		if (this.shuffled) this.history.push(this.current);
		this.current = to;
	}
}
```

```html title="audio-player.html"
<div data-example="audio-player">
	<audio data-audio preload="auto"></audio>
	<div data-now>
		<span data-cover aria-hidden="true"></span>
		<div data-meta>
			<strong data-title>Morning Light</strong>
			<span data-artist>Radiant Demo</span>
			<rui-toolbar label="Visualizer" exclusive-toggles>
				<div class="rui-toolbar" data-ref="root" role="toolbar" aria-label="Visualizer">
					<button
						type="button"
						class="rui-button rui-button--ghost rui-button--sm"
						data-toggle
						data-visualizer="led"
						aria-label="LED bars"
						aria-pressed="true"
					>
						LED
					</button>
					<button
						type="button"
						class="rui-button rui-button--ghost rui-button--sm"
						data-toggle
						data-visualizer="solid"
						aria-label="Solid bars"
						aria-pressed="false"
					>
						Bars
					</button>
					<button
						type="button"
						class="rui-button rui-button--ghost rui-button--sm"
						data-toggle
						data-visualizer="wave"
						aria-label="Waveform"
						aria-pressed="false"
					>
						Wave
					</button>
				</div>
			</rui-toolbar>
		</div>
	</div>
	<div data-scrub>
		<output data-elapsed>0:00</output>
		<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 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>
		<output data-total>0:08</output>
	</div>
	<div data-controls>
		<button
			type="button"
			class="rui-button rui-button--ghost rui-button--md rui-button--square"
			data-previous
			aria-label="Previous track"
		>
			<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
				<path d="M5 5h2v14H5zM19 5v14L8 12z" fill="currentColor" />
			</svg>
		</button>
		<button
			type="button"
			class="rui-button rui-button--filled rui-button--lg rui-button--square"
			data-playback
			aria-label="Play"
			aria-pressed="false"
		>
			<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false" data-icon="play">
				<path d="M8 5v14l10-7z" fill="currentColor" /></svg
			><svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false" data-icon="pause">
				<path d="M7 5h3v14H7zM14 5h3v14h-3z" fill="currentColor" />
			</svg>
		</button>
		<button
			type="button"
			class="rui-button rui-button--ghost rui-button--md rui-button--square"
			data-next
			aria-label="Next track"
		>
			<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
				<path d="M17 5h2v14h-2zM5 5v14l11-7z" fill="currentColor" />
			</svg>
		</button>
		<button
			type="button"
			class="rui-button rui-button--ghost rui-button--md rui-button--square"
			data-loop
			data-mode="off"
			aria-label="Loop: off"
		>
			<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
				<path d="M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4z" fill="currentColor" />
				<path d="M13 15V9h-1l-2 1v1h1.5v4H13z" fill="currentColor" data-one />
			</svg>
		</button>
		<button
			type="button"
			class="rui-button rui-button--ghost rui-button--md rui-button--square"
			data-shuffle
			aria-label="Shuffle"
			aria-pressed="false"
		>
			<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
				<path
					d="M10.59 9.17 5.41 4 4 5.41l5.17 5.17 1.42-1.41zM14.5 4l2.04 2.04L4 18.59 5.41 20 17.96 7.46 20 9.5V4h-5.5zm.33 9.41-1.41 1.41 3.13 3.13L14.5 20H20v-5.5l-2.04 2.04-3.13-3.13z"
					fill="currentColor"
				/>
			</svg>
		</button>
		<div data-volume>
			<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
				<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"
				/>
			</svg>
			<rui-slider data-volume-input step="0.05" label="Volume" min="0" max="1" value="0.8">
				<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: 80%; --rui-slider-value: 80%"
						>
							<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>
	</div>
	<ol data-tracks aria-label="Playlist">
		<li
			data-track
			aria-describedby="audio-player-plain-help"
			data-src="/assets/audio/morning-light.wav"
			data-artist="Radiant Demo"
			tabindex="0"
		>
			<span data-number>1</span>
			<span data-name>Morning Light</span>
			<span data-length>0:08</span>
		</li>
		<li
			data-track
			aria-describedby="audio-player-plain-help"
			data-src="/assets/audio/low-tide.wav"
			data-artist="Radiant Demo"
			tabindex="-1"
		>
			<span data-number>2</span>
			<span data-name>Low Tide</span>
			<span data-length>0:08</span>
		</li>
		<li
			data-track
			aria-describedby="audio-player-plain-help"
			data-src="/assets/audio/neon-rain.wav"
			data-artist="Radiant Demo"
			tabindex="-1"
		>
			<span data-number>3</span>
			<span data-name>Neon Rain</span>
			<span data-length>0:09</span>
		</li>
		<li
			data-track
			aria-describedby="audio-player-plain-help"
			data-src="/assets/audio/paper-planes.wav"
			data-artist="Radiant Demo"
			tabindex="-1"
		>
			<span data-number>4</span>
			<span data-name>Paper Planes</span>
			<span data-length>0:07</span>
		</li>
	</ol>
	<span data-help hidden id="audio-player-plain-help">Enter plays, Space picks up to reorder</span>
	<p data-status aria-live="polite">Pick a track, or drag one to reorder the playlist</p>
</div>
```

```css title="audio-player.css"
.primitive-example:is(
	[data-example='audio-player'],
	:has(> audio-player-element, > [data-controller='audio-player'], > audio-player-app)
) {
	display: flex;
	flex-direction: column;
	align-items: stretch;
	gap: var(--space-stack);
	box-sizing: border-box;
	width: min(100%, 24rem);
	padding: var(--space-inset);
	border: 1px solid var(--border);
	border-radius: var(--radius-container);
	background: var(--surface);
	color: var(--on-surface);
	box-shadow: var(--shadow-overlay);
	--audio-player-muted: color-mix(in srgb, currentColor 78%, var(--surface));

	& :where([data-now]) {
		display: flex;
		flex-direction: column;
		gap: var(--space-4);
	}

	& :where([data-cover]) {
		display: block;
		position: relative;
		box-sizing: border-box;
		width: 100%;
		height: 7rem;
		overflow: hidden;
		border: 0;
		border-radius: var(--radius-container);
		background: linear-gradient(135deg, var(--primary), color-mix(in srgb, var(--primary) 78%, var(--surface)));
		color: var(--on-primary);
	}

	& :where([data-meta]) {
		display: grid;
		grid-template-columns: minmax(0, 1fr) auto;
		column-gap: var(--space-3);
		row-gap: 0.125rem;
		align-items: start;
		min-width: 0;
	}

	& :where([data-meta] > [data-title], [data-meta] > [data-artist]) {
		grid-column: 1;
		min-width: 0;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	& :where([data-meta] rui-toolbar) {
		grid-column: 2;
		grid-row: 1 / span 2;
		align-self: center;
	}

	& :where([data-title]) {
		font-size: 1.125rem;
		line-height: 1.25;
	}

	& :where([data-meta] > [data-artist]) {
		color: var(--audio-player-muted);
	}

	& :where([data-scrub]) {
		display: flex;
		align-items: center;
		gap: var(--space-3);
	}

	& :where([data-controls]) {
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		gap: var(--space-2);
	}

	& :where([data-elapsed], [data-total]) {
		min-width: 2.5ch;
		font-size: 0.75rem;
		font-variant-numeric: tabular-nums;
		color: var(--audio-player-muted);
	}

	& [data-loop] [data-one],
	& [data-playback] [data-icon='pause'],
	& [data-playback][aria-pressed='true'] [data-icon='play'] {
		display: none;
	}

	& [data-playback][aria-pressed='true'] [data-icon='pause'] {
		display: block;
	}

	& [data-loop][data-mode='one'] [data-one] {
		display: block;
	}

	& [data-loop]:not([data-mode='off']) {
		background: var(--background);
		color: var(--on-background);
		font-weight: 500;
		box-shadow: inset 0 0 0 2px var(--border);
	}

	& :where([data-volume]) {
		display: flex;
		flex: 1;
		align-items: center;
		gap: var(--space-2);
		min-width: 7rem;
		margin-inline-start: auto;
		opacity: 0.85;
	}

	& :where([data-volume] svg) {
		flex: none;
	}

	& :where([data-tracks]) {
		display: flex;
		flex-direction: column;
		gap: var(--space-1);
		margin: 0 calc(var(--space-2) * -1);
		padding: 0 var(--space-1);
	}

	& [data-track] {
		display: grid;
		grid-template-columns: 1.5rem 1fr auto auto;
		align-items: center;
		gap: var(--space-3);
		padding: var(--space-2);
		border: 0;
		border-radius: var(--radius-control);
		background: transparent;
		cursor: grab;
		touch-action: none;
		user-select: none;

		&::after {
			content: '';
			width: 0.75rem;
			height: 1rem;
			background: radial-gradient(circle, currentColor 1.2px, transparent 1.6px) 0 0 / 6px 6px;
			opacity: 0.3;
		}

		&:hover {
			background: var(--surface-container-high);
		}

		&[aria-current='true'] {
			background: color-mix(in srgb, var(--primary) 14%, var(--surface));
			color: var(--primary);
			font-weight: 600;

			& :where([data-number], [data-length]) {
				color: inherit;
			}
		}
	}

	& :where([data-number], [data-length]) {
		font-size: 0.8125rem;
		font-variant-numeric: tabular-nums;
		color: var(--audio-player-muted);
	}

	& [data-sortable-placeholder] {
		min-height: 2.5rem;
		box-sizing: border-box;
		border: 1px dashed color-mix(in srgb, var(--primary) 55%, transparent);
		border-radius: var(--radius-control);
		background: color-mix(in srgb, var(--primary) 8%, transparent);
	}

	& [data-track][data-sortable-drop] {
		box-shadow: none;
	}

	& :where([data-status]) {
		margin: 0;
		font-size: 0.75rem;
		color: var(--audio-player-muted);
	}

	& :where([data-scrub] rui-slider, [data-volume] rui-slider) {
		--rui-slider-track-length: 100%;
		flex: 1;
		min-width: 0;
		margin-inline: calc(var(--rui-slider-thumb-size, 1.25rem) / 2);
	}

	& .rui-slider__header {
		display: none;
	}
}

[data-track][data-sortable-state='lifted'] {
	z-index: 10;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: var(--space-1) var(--space-3);
	border: 1px solid var(--border);
	border-radius: var(--radius-control);
	background: var(--primary);
	color: var(--on-primary);
	font-size: 0.875rem;
	box-shadow: 0 0.5rem 1rem rgb(0 0 0 / 0.25);
	list-style: none;
	cursor: grabbing;
}

[data-track][data-sortable-state='lifted'] > :is([data-number], [data-length]),
[data-track][data-sortable-state='lifted']::after {
	display: none;
}

body:has([data-sortable-state='lifted']) .primitive-example [data-track]:hover {
	background: transparent;
}
```

`mount` runs once for each example element on the page, and the function it returns undoes it; see [how the examples run](/docs/recipes/overview#how-the-examples-run). It builds a `MediaController` and an `AudioVisualizerController` over the `audio` element and the cover, and the cleanup destroys them with the sortable and roving controllers: the media controller pauses the sound, drops its source and revokes the object URLs, so a removed player stops making sound. The seek slider works in seconds and reports `rui-change` only for the reader, never for the position the player writes to it. Each one goes to `scrub`. 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 moves the thumb by whole seconds with `skip` before the slider sees the key. The play button's hook is `data-playback` and not `data-toggle`, which `RuiButton` and the toolbar use for their own toggle buttons. Each clip goes through the controller's `resolveSource` into a `Blob` and is played from memory: a media element can only seek in a file whose server answers range requests, and many development and preview servers do not, so seeking would snap back to the start. For long media, serve the file with range support and load its URL directly. The LED, Bars and Wave buttons are a `rui-toolbar` with `exclusive-toggles`; a click listener on the example in the capture phase calls `setPreset`, because the toolbar stops the click of a toggle before it reaches a listener on the button.

</RecipePattern>

</RecipePatterns>

### Styles

The current track is selected with `aria-current`, so the stylesheet needs no class the script would have to keep in step. The lifted track leaves the example while it is dragged, so its style selects it by `data-track` alone. The cover is a rounded box with `overflow: hidden` and no border, and the canvas the visualizer adds fills it, so the wave runs edge to edge and is clipped by the corners, while the bars keep their own padding through the preset's `padding` option. The loop button shows the pressed look for `all` and `one` through its `data-mode`, and the icon with the 1 only for `one`. The stylesheet is the `audio-player.css` tab in the files above.
