273 lines
9.7 KiB
TypeScript
273 lines
9.7 KiB
TypeScript
import { AmbientLoop, Music } from '../engine/audio';
|
|
import { Loop } from '../engine/Loop';
|
|
import { PixelCanvas } from '../engine/PixelCanvas';
|
|
import type { Meditation, Scene } from '../meditations/types';
|
|
import type { View } from './Menu';
|
|
|
|
export interface PlayerOptions {
|
|
onExit: () => void;
|
|
/** Dev only: start at this time (seconds). */
|
|
startAt?: number;
|
|
/** Dev only: playback speed multiplier. */
|
|
speed?: number;
|
|
}
|
|
|
|
const IDLE_MS = 3000;
|
|
|
|
const ICONS = {
|
|
back: '<svg viewBox="0 0 10 10" fill="currentColor"><path d="M4 1h1v1H4zM3 2h1v1H3zM2 3h1v1H2zM1 4h8v2H1zM2 6h1v1H2zM3 7h1v1H3zM4 8h1v1H4z"/></svg>',
|
|
pause: '<svg viewBox="0 0 10 10" fill="currentColor"><path d="M2 1h2v8H2zM6 1h2v8H6z"/></svg>',
|
|
play: '<svg viewBox="0 0 10 10" fill="currentColor"><path d="M2 1h1v8H2zM3 2h1v6H3zM4 3h1v4H4zM5 4h2v2H5zM5 3h1v1H5zM5 6h1v1H5z"/></svg>',
|
|
fullscreen:
|
|
'<svg viewBox="0 0 10 10" fill="currentColor"><path d="M1 1h3v1H2v2H1zM6 1h3v3H8V2H6zM1 6h1v2h2v1H1zM8 6h1v3H6V8h2z"/></svg>',
|
|
};
|
|
|
|
/** Music plus any looping ambiences, driven together from the meditation clock. */
|
|
class Soundtrack {
|
|
private readonly music: Music;
|
|
private readonly ambience: AmbientLoop[];
|
|
|
|
constructor(m: Meditation, enabled: boolean) {
|
|
this.music = new Music(enabled ? m.music : undefined, 0.75);
|
|
const list = enabled && m.ambience ? [m.ambience].flat() : [];
|
|
this.ambience = list.map((a) => new AmbientLoop(a.src, a.volume, a.fadeIn, a.fadeOut, a.from, a.until));
|
|
}
|
|
|
|
play(t: number): void {
|
|
this.music.seek(t);
|
|
this.music.play();
|
|
for (const a of this.ambience) a.start(t);
|
|
}
|
|
|
|
pause(): void {
|
|
this.music.pause();
|
|
for (const a of this.ambience) a.pause();
|
|
}
|
|
|
|
seek(t: number): void {
|
|
this.music.seek(t);
|
|
for (const a of this.ambience) a.seek(t);
|
|
}
|
|
|
|
update(t: number, duration: number): void {
|
|
this.music.update(t, duration);
|
|
for (const a of this.ambience) a.update(t, duration);
|
|
}
|
|
|
|
destroy(): void {
|
|
this.music.destroy();
|
|
for (const a of this.ambience) a.destroy();
|
|
}
|
|
}
|
|
|
|
function formatTime(s: number): string {
|
|
const v = Math.max(0, Math.ceil(s));
|
|
return `${Math.floor(v / 60)}:${String(v % 60).padStart(2, '0')}`;
|
|
}
|
|
|
|
type State = 'ready' | 'playing' | 'paused' | 'ended';
|
|
|
|
/** Hosts one meditation: begin screen, playback with auto-hiding controls, and a gentle ending. */
|
|
export class Player implements View {
|
|
private readonly root: HTMLElement;
|
|
private readonly view: PixelCanvas;
|
|
private readonly loop: Loop;
|
|
private readonly sound: Soundtrack;
|
|
private readonly scene: Scene;
|
|
private t: number;
|
|
private state: State = 'ready';
|
|
private idleTimer = 0;
|
|
|
|
private readonly begin: HTMLElement;
|
|
private readonly end: HTMLElement;
|
|
private readonly controls: HTMLElement;
|
|
private readonly bar: HTMLElement;
|
|
private readonly time: HTMLElement;
|
|
private readonly playBtn: HTMLButtonElement;
|
|
private readonly pausedLabel: HTMLElement;
|
|
private readonly devTime?: HTMLElement;
|
|
|
|
constructor(
|
|
parent: HTMLElement,
|
|
private readonly m: Meditation,
|
|
private readonly opts: PlayerOptions,
|
|
) {
|
|
this.root = document.createElement('div');
|
|
this.root.className = 'player';
|
|
parent.appendChild(this.root);
|
|
this.view = new PixelCanvas(this.root);
|
|
this.scene = m.createScene();
|
|
// Sound can't follow a dev fast-forward, so it stays off then.
|
|
this.sound = new Soundtrack(m, (opts.speed ?? 1) === 1);
|
|
this.t = opts.startAt ?? 0;
|
|
|
|
this.begin = this.overlay(`
|
|
<h2></h2>
|
|
<p class="desc"></p>
|
|
<p class="hint">Settle in, soften your gaze, and breathe slowly. ${Math.round(m.duration / 60)} minutes.</p>
|
|
<div class="row"><button class="btn primary" data-act="begin">Begin</button><button class="btn" data-act="exit">Back</button></div>
|
|
<p class="hint">Space pauses · F toggles fullscreen · Esc returns to the menu</p>`);
|
|
this.begin.querySelector('h2')!.textContent = m.title;
|
|
this.begin.querySelector('.desc')!.textContent = m.description;
|
|
|
|
this.end = this.overlay(`
|
|
<h2>Be well</h2>
|
|
<p>Carry a little of this stillness with you.</p>
|
|
<div class="row"><button class="btn primary" data-act="again">Experience again</button><button class="btn" data-act="exit">Return to menu</button></div>`);
|
|
this.end.classList.add('hidden');
|
|
|
|
this.controls = document.createElement('div');
|
|
this.controls.className = 'controls hidden';
|
|
this.controls.innerHTML = `
|
|
<button class="icon-btn" data-act="exit" aria-label="Return to menu">${ICONS.back}</button>
|
|
<button class="icon-btn" data-act="toggle" aria-label="Pause">${ICONS.pause}</button>
|
|
<div class="progress" role="progressbar" aria-label="Progress"><div></div></div>
|
|
<span class="time"></span>
|
|
<button class="icon-btn" data-act="fullscreen" aria-label="Toggle fullscreen">${ICONS.fullscreen}</button>`;
|
|
this.root.appendChild(this.controls);
|
|
this.bar = this.controls.querySelector('.progress > div')!;
|
|
this.time = this.controls.querySelector('.time')!;
|
|
this.playBtn = this.controls.querySelector('[data-act="toggle"]')!;
|
|
|
|
this.pausedLabel = document.createElement('div');
|
|
this.pausedLabel.className = 'paused-label';
|
|
this.pausedLabel.textContent = 'PAUSED';
|
|
this.pausedLabel.style.opacity = '0';
|
|
this.root.appendChild(this.pausedLabel);
|
|
|
|
if (import.meta.env.DEV) {
|
|
this.devTime = document.createElement('div');
|
|
this.devTime.className = 'dev-time';
|
|
this.root.appendChild(this.devTime);
|
|
}
|
|
|
|
this.root.addEventListener('click', this.onClick);
|
|
this.root.addEventListener('mousemove', this.wake);
|
|
this.root.addEventListener('touchstart', this.wake, { passive: true });
|
|
window.addEventListener('keydown', this.onKey);
|
|
document.addEventListener('visibilitychange', this.onVisibility);
|
|
|
|
this.loop = new Loop(this.tick);
|
|
this.render();
|
|
this.loop.start();
|
|
(this.begin.querySelector('[data-act="begin"]') as HTMLElement).focus();
|
|
}
|
|
|
|
private overlay(html: string): HTMLElement {
|
|
const el = document.createElement('div');
|
|
el.className = 'overlay';
|
|
el.innerHTML = `<div class="overlay-box">${html}</div>`;
|
|
this.root.appendChild(el);
|
|
return el;
|
|
}
|
|
|
|
private tick = (dt: number): void => {
|
|
if (this.state === 'playing') {
|
|
this.t += dt * (this.opts.speed ?? 1);
|
|
if (this.t >= this.m.duration) {
|
|
this.t = this.m.duration;
|
|
this.finish();
|
|
}
|
|
}
|
|
this.sound.update(this.t, this.m.duration);
|
|
this.render();
|
|
};
|
|
|
|
private render(): void {
|
|
this.scene.render(this.view.surface, this.t);
|
|
this.view.present();
|
|
this.bar.style.width = `${(this.t / this.m.duration) * 100}%`;
|
|
this.time.textContent = formatTime(this.m.duration - this.t);
|
|
if (this.devTime) this.devTime.textContent = `t=${this.t.toFixed(1)}s [ / ] skip`;
|
|
}
|
|
|
|
private start(): void {
|
|
this.state = 'playing';
|
|
this.begin.classList.add('hidden');
|
|
this.end.classList.add('hidden');
|
|
this.controls.classList.remove('hidden');
|
|
this.sound.play(this.t);
|
|
this.wake();
|
|
}
|
|
|
|
private finish(): void {
|
|
this.state = 'ended';
|
|
this.sound.pause();
|
|
this.controls.classList.add('hidden');
|
|
this.root.classList.remove('idle');
|
|
this.end.classList.remove('hidden');
|
|
(this.end.querySelector('[data-act="again"]') as HTMLElement).focus();
|
|
}
|
|
|
|
private setPaused(paused: boolean): void {
|
|
if (this.state !== 'playing' && this.state !== 'paused') return;
|
|
this.state = paused ? 'paused' : 'playing';
|
|
if (paused) this.sound.pause();
|
|
else this.sound.play(this.t);
|
|
this.playBtn.innerHTML = paused ? ICONS.play : ICONS.pause;
|
|
this.playBtn.setAttribute('aria-label', paused ? 'Play' : 'Pause');
|
|
this.pausedLabel.style.opacity = paused ? '1' : '0';
|
|
this.wake();
|
|
}
|
|
|
|
private toggleFullscreen(): void {
|
|
if (document.fullscreenElement) void document.exitFullscreen();
|
|
else void this.root.requestFullscreen?.().catch(() => {});
|
|
}
|
|
|
|
/** Show the controls and cursor; they fade away again after a few still seconds. */
|
|
private wake = (): void => {
|
|
this.root.classList.remove('idle');
|
|
clearTimeout(this.idleTimer);
|
|
if (this.state !== 'playing') return;
|
|
this.idleTimer = window.setTimeout(() => {
|
|
if (this.state === 'playing') this.root.classList.add('idle');
|
|
}, IDLE_MS);
|
|
};
|
|
|
|
private onClick = (e: MouseEvent): void => {
|
|
const act = (e.target as HTMLElement).closest<HTMLElement>('[data-act]')?.dataset.act;
|
|
switch (act) {
|
|
case 'begin':
|
|
return this.start();
|
|
case 'again':
|
|
this.t = 0;
|
|
return this.start();
|
|
case 'exit':
|
|
return this.opts.onExit();
|
|
case 'toggle':
|
|
return this.setPaused(this.state === 'playing');
|
|
case 'fullscreen':
|
|
return this.toggleFullscreen();
|
|
}
|
|
};
|
|
|
|
private onKey = (e: KeyboardEvent): void => {
|
|
if (e.key === 'Escape' && !document.fullscreenElement) return this.opts.onExit();
|
|
if (e.key === 'f' || e.key === 'F') return this.toggleFullscreen();
|
|
if (e.key === ' ' && (this.state === 'playing' || this.state === 'paused')) {
|
|
e.preventDefault();
|
|
return this.setPaused(this.state === 'playing');
|
|
}
|
|
if (import.meta.env.DEV && (e.key === '[' || e.key === ']')) {
|
|
this.t = Math.max(0, Math.min(this.m.duration - 0.01, this.t + (e.key === ']' ? 10 : -10)));
|
|
this.sound.seek(this.t);
|
|
}
|
|
};
|
|
|
|
private onVisibility = (): void => {
|
|
if (document.hidden && this.state === 'playing') this.setPaused(true);
|
|
};
|
|
|
|
destroy(): void {
|
|
this.loop.stop();
|
|
this.sound.destroy();
|
|
clearTimeout(this.idleTimer);
|
|
window.removeEventListener('keydown', this.onKey);
|
|
document.removeEventListener('visibilitychange', this.onVisibility);
|
|
if (document.fullscreenElement) void document.exitFullscreen().catch(() => {});
|
|
this.view.destroy();
|
|
this.root.remove();
|
|
}
|
|
}
|