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: '', pause: '', play: '', fullscreen: '', }; /** 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(`

Settle in, soften your gaze, and breathe slowly. ${Math.round(m.duration / 60)} minutes.

Space pauses · F toggles fullscreen · Esc returns to the menu

`); this.begin.querySelector('h2')!.textContent = m.title; this.begin.querySelector('.desc')!.textContent = m.description; this.end = this.overlay(`

Be well

Carry a little of this stillness with you.

`); this.end.classList.add('hidden'); this.controls = document.createElement('div'); this.controls.className = 'controls hidden'; this.controls.innerHTML = `
`; 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 = `
${html}
`; 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('[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(); } }