~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
214 lines · 7.7 KB Raw History
// What plays a view's players' tracks: one <audio>, apart from any player,
// so what plays goes on as the players come and go (a tile closed or drawn
// again, a view navigated away from). The app makes one and mounts its
// <audio> once (`{@attach host.attach}`), and gives it to its views
// (View's `player`); a `Player` with none keeps a host of its own.
//
// It holds only the tracks it plays, never the answer they came from: no
// `openSubtitle`, which closes over the view. `origin` is the app's, to say
// where the music came from; a player compares it, with the tracks' srcs,
// to know the queue as its own.

import type { Track } from './Player.svelte';

/** A track as a host holds it: no link back into the view it came from. */
export type QueuedTrack = Omit<Track, 'openSubtitle'>;

export interface PlayerHost {
	readonly queue: readonly QueuedTrack[];
	readonly index: number | null;
	readonly track: QueuedTrack | null;
	/** Seconds in, and the track's length (as the audio knows it, else as the track says). */
	readonly time: number;
	readonly duration: number;
	readonly paused: boolean;
	readonly error: string | null;
	readonly origin: unknown;
	/** Play `queue` from `index`, as `origin`'s. The track playing already goes on from where it is. */
	play(queue: readonly Track[], index: number, origin: unknown): void;
	/** Take `queue` as the one playing grown (a page more): what plays goes on. Nothing unless it starts as the queue does, from the same origin. */
	extend(queue: readonly Track[], origin: unknown): void;
	toggle(): void;
	next(): void;
	previous(): void;
	seek(to: number): void;
	/** Stop, let go of the stream, and forget the queue. */
	clear(): void;
}

/** Past this many seconds in, "previous" restarts the track instead. */
const RESTART = 3;

const queued = (queue: readonly Track[]): QueuedTrack[] => queue.map(({ src, title, subtitle, duration, art }) => ({ src, title, subtitle, duration, art }));

/** Whether `longer` starts with `queue`'s tracks. */
export const startsWith = (longer: readonly { src: string | null }[], queue: readonly { src: string | null }[]) =>
	queue.length > 0 && queue.length <= longer.length && queue.every((track, i) => track.src === longer[i].src);

export class AudioHost implements PlayerHost {
	queue: readonly QueuedTrack[] = $state.raw([]);
	index: number | null = $state(null);
	time = $state(0);
	paused = $state(true);
	error: string | null = $state(null);
	origin: unknown = $state.raw(null);
	#length = $state(0);
	#audio: HTMLAudioElement | null = null;
	/** Whether it tells the system (media keys, the lock screen) what plays: the app's one host, not a player's own. */
	#session: boolean;

	constructor({ session = true }: { session?: boolean } = {}) {
		this.#session = session && typeof navigator !== 'undefined' && 'mediaSession' in navigator;
	}

	get track(): QueuedTrack | null {
		return this.index === null ? null : (this.queue[this.index] ?? null);
	}

	get duration(): number {
		return Number.isFinite(this.#length) && this.#length > 0 ? this.#length : (this.track?.duration ?? 0);
	}

	/** Mount the host's <audio>: `<audio preload="none" {@attach host.attach}>`. Taken away, it stops and lets go of its stream. */
	attach = (audio: HTMLAudioElement) => {
		this.#audio = audio;
		const listeners: [string, () => void][] = [
			['timeupdate', () => (this.time = audio.currentTime)],
			['durationchange', () => (this.#length = audio.duration)],
			['play', () => this.#playing(false)],
			['pause', () => this.#playing(true)],
			['ended', () => this.next()],
			['error', () => this.track && audio.getAttribute('src') && (this.error = 'This track could not be played.')]
		];
		for (const [name, listener] of listeners) audio.addEventListener(name, listener);
		return () => {
			for (const [name, listener] of listeners) audio.removeEventListener(name, listener);
			this.clear();
			this.#audio = null;
		};
	};

	/** The system's media keys and lock screen, while something is loaded: taken only then, so an idle host leaves them to the page's other media. */
	#handle(on: boolean) {
		if (!this.#session) return;
		const handlers: [MediaSessionAction, MediaSessionActionHandler][] = [
			['play', () => this.paused && this.toggle()],
			['pause', () => this.#audio?.pause()],
			['nexttrack', () => this.next()],
			['previoustrack', () => this.previous()],
			['seekto', (details) => details.seekTime !== undefined && this.seek(details.seekTime)]
		];
		for (const [action, handler] of handlers) {
			try {
				navigator.mediaSession.setActionHandler(action, on ? handler : null);
			} catch {
				// An action this browser does not know.
			}
		}
	}

	#playing(paused: boolean) {
		this.paused = paused;
		if (this.#session) navigator.mediaSession.playbackState = this.track ? (paused ? 'paused' : 'playing') : 'none';
	}

	/** Pause and let go of what it fetched and decoded at once, rather than whenever it is collected. */
	#release() {
		const audio = this.#audio;
		if (!audio) return;
		audio.pause();
		audio.removeAttribute('src');
		audio.load();
	}

	#metadata(track: QueuedTrack | null) {
		if (!this.#session || typeof MediaMetadata === 'undefined') return;
		try {
			navigator.mediaSession.metadata = track
				? new MediaMetadata({ title: track.title || 'Untitled', artist: track.subtitle ?? '', artwork: track.art ? [{ src: track.art.src }] : [] })
				: null;
		} catch {
			// Artwork it cannot read: what plays matters more than its picture.
			navigator.mediaSession.metadata = null;
		}
	}

	/** The first playable track after `from`, or before it going back. */
	#step(from: number, by: 1 | -1): number | null {
		for (let i = from + by; i >= 0 && i < this.queue.length; i += by) if (this.queue[i].src !== null) return i;
		return null;
	}

	/** Play the queue's track `i`, from where it is if it is the one loaded. */
	async #start(i: number) {
		const audio = this.#audio;
		const track = this.queue[i];
		if (!audio || track?.src == null) return;
		this.error = null;
		if (this.index !== i || audio.getAttribute('src') !== track.src) {
			if (this.index === null) this.#handle(true);
			this.index = i;
			this.time = 0;
			this.#length = 0;
			audio.src = track.src;
			this.#metadata(track);
		}
		try {
			await audio.play();
		} catch (cause) {
			if (!(cause instanceof DOMException && cause.name === 'AbortError')) this.error = 'This track could not be played.';
		}
	}

	play(queue: readonly Track[], index: number, origin: unknown) {
		if (queue[index]?.src == null) return;
		const same = this.origin === origin && this.track?.src === queue[index].src && this.index === index;
		this.queue = queued(queue);
		this.origin = origin;
		if (!same) this.index = null;
		void this.#start(index);
	}

	extend(queue: readonly Track[], origin: unknown) {
		if (origin === this.origin && queue.length > this.queue.length && startsWith(queue, this.queue)) this.queue = queued(queue);
	}

	toggle() {
		if (this.index === null) {
			const first = this.#step(-1, 1);
			if (first !== null) void this.#start(first);
		} else if (this.paused) void this.#start(this.index);
		else this.#audio?.pause();
	}

	next() {
		const i = this.#step(this.index ?? -1, 1);
		if (i !== null) void this.#start(i);
	}

	previous() {
		if (this.#audio && this.index !== null && this.time > RESTART) {
			this.#audio.currentTime = 0;
			return;
		}
		const i = this.#step(this.index ?? this.queue.length, -1);
		if (i !== null) void this.#start(i);
	}

	seek(to: number) {
		if (this.#audio && this.track) this.#audio.currentTime = Math.min(Math.max(to, 0), this.duration || to);
	}

	clear() {
		this.#release();
		if (this.index !== null) this.#handle(false);
		this.queue = [];
		this.index = null;
		this.origin = null;
		this.time = 0;
		this.#length = 0;
		this.error = null;
		this.#playing(true);
		this.#metadata(null);
	}
}