forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

audio-player.tsx491 lines, 17.5 KiBHistoryRawDownload
1import { Show, createEffect, createSignal, onCleanup, onMount, type JSX } from "solid-js";
2import {
3 IconPause,
4 IconPlay,
5 IconSkipBack,
6 IconSkipForward,
7 IconVolume,
8 IconVolumeLow,
9 IconVolumeMute,
10} from "@/components/ui/icons";
11import { cn } from "@/lib/cn";
12import { formatDurationClock } from "@/lib/format";
13import { useT } from "@/stores/preferences-context";
14
15const SKIP_SECS = 15;
16const RATES = [0.75, 1, 1.25, 1.5, 2] as const;
17const RATE_KEY = "hezarfen.audio.rate";
18const VOLUME_KEY = "hezarfen.audio.volume";
19
20// One episode plays at a time: starting a player pauses whichever other one
21// was playing, so a history list never talks over itself.
22const players = new Set<HTMLAudioElement>();
23
24function readStored(key: string, fallback: number, valid: (value: number) => boolean): number {
25 if (typeof localStorage === "undefined") return fallback;
26 const value = Number(localStorage.getItem(key));
27 return localStorage.getItem(key) != null && Number.isFinite(value) && valid(value) ? value : fallback;
28}
29
30function store(key: string, value: number) {
31 if (typeof localStorage !== "undefined") localStorage.setItem(key, String(value));
32}
33
34/** What a caller can drive from outside — the transcript seeks through it. */
35export type AudioPlayerController = {
36 seek: (secs: number) => void;
37 play: () => void;
38};
39
40export type AudioPlayerProps = {
41 src: string;
42 title?: string;
43 subtitle?: string;
44 /**
45 * The server's own running time, shown until the file's metadata arrives —
46 * and kept when a chunked stream never reports a finite duration.
47 */
48 durationHint?: number | null;
49 autoplay?: boolean;
50 /** Trailing controls on the title row (download, …). */
51 actions?: JSX.Element;
52 /** Extra controls at the end of the transport row (transcript toggle, …). */
53 extra?: JSX.Element;
54 /**
55 * Loads the whole file. Given, a seek the stream cannot serve (a server
56 * that ignores `Range` leaves `seekable` empty) switches the player to a
57 * local copy of it instead of snapping back to 0:00.
58 */
59 loadBlob?: (signal: AbortSignal) => Promise<Blob>;
60 onTimeUpdate?: (secs: number) => void;
61 controller?: (controller: AudioPlayerController) => void;
62 class?: string;
63};
64
65/**
66 * The app's audio player: one play/pause, ±15 s skips, a draggable seek bar,
67 * playback speed and volume — in place of the browser's own `controls` strip,
68 * which looks different in every browser and offers no speed or skip.
69 *
70 * The seek bar and volume are native range inputs laid over a drawn track, so
71 * keyboard and screen-reader behaviour comes from the platform. Speed and
72 * volume are remembered across episodes on this device.
73 */
74export function AudioPlayer(props: AudioPlayerProps) {
75 const t = useT();
76 let audio!: HTMLAudioElement;
77 const [playing, setPlaying] = createSignal(false);
78 const [buffering, setBuffering] = createSignal(false);
79 const [current, setCurrent] = createSignal(0);
80 const [mediaDuration, setMediaDuration] = createSignal<number | null>(null);
81 const [buffered, setBuffered] = createSignal(0);
82 const [rate, setRate] = createSignal(readStored(RATE_KEY, 1, (v) => (RATES as readonly number[]).includes(v)));
83 const [volume, setVolume] = createSignal(readStored(VOLUME_KEY, 1, (v) => v >= 0 && v <= 1));
84 const [muted, setMuted] = createSignal(false);
85 const [failed, setFailed] = createSignal(false);
86 // Seeking waits on the local copy; the seek bar already shows the target.
87 const [seeking, setSeeking] = createSignal(false);
88 // No src until the element is in the live document. A <Suspense> boundary
89 // renders its children detached first, and Chromium refuses a media load
90 // that starts off-document ("Media load rejected by URL safety check").
91 const [source, setSource] = createSignal<string | undefined>();
92 let connected = false;
93 let retriedLoad = false;
94 let disposed = false;
95
96 // The local copy of the file, loaded once per `src` on first play or on the
97 // first seek the stream cannot serve.
98 let objectUrl: string | null = null;
99 let localLoad: Promise<string | null> | null = null;
100 let abort: AbortController | null = null;
101 let pendingSeek: number | null = null;
102 let resumeAfterSeek = false;
103 let seekToken = 0;
104 let afterLoad: (() => void) | null = null;
105
106 const dropLocal = () => {
107 abort?.abort();
108 abort = null;
109 localLoad = null;
110 if (objectUrl) URL.revokeObjectURL(objectUrl);
111 objectUrl = null;
112 };
113 const loadLocal = (): Promise<string | null> => {
114 const load = props.loadBlob;
115 if (!load) return Promise.resolve(null);
116 if (!localLoad) {
117 const controller = new AbortController();
118 abort = controller;
119 localLoad = load(controller.signal).then(
120 (blob) => {
121 if (controller.signal.aborted) return null;
122 objectUrl = URL.createObjectURL(blob);
123 return objectUrl;
124 },
125 () => {
126 if (abort === controller) localLoad = null;
127 return null;
128 },
129 );
130 }
131 return localLoad;
132 };
133 // A seek is instant only where the audio is actually here: the local copy,
134 // or a range the stream has already buffered. `seekable` is not trusted —
135 // Safari reports the whole file as seekable on a stream that ignores Range,
136 // then keeps playing from the old spot.
137 const canSeekTo = (secs: number) => {
138 if (objectUrl && source() === objectUrl) return true;
139 const ranges = audio.buffered;
140 for (let i = 0; i < ranges.length; i += 1) {
141 if (secs >= ranges.start(i) && secs <= ranges.end(i) - 0.5) return true;
142 }
143 return false;
144 };
145
146 const duration = () => mediaDuration() ?? (props.durationHint && props.durationHint > 0 ? props.durationHint : null);
147 const fraction = (value: number) => {
148 const total = duration();
149 return total ? Math.min(1, Math.max(0, value / total)) : 0;
150 };
151
152 const seek = (secs: number) => {
153 const total = duration();
154 const next = Math.max(0, total ? Math.min(total, secs) : secs);
155 setCurrent(next);
156 if (!props.loadBlob || canSeekTo(next)) {
157 audio.currentTime = next;
158 return;
159 }
160 // The stream cannot go there: hold the target, pause the stream at its
161 // wrong position, and resume from the target on the local copy.
162 const token = ++seekToken;
163 pendingSeek = next;
164 resumeAfterSeek ||= !audio.paused;
165 audio.pause();
166 setSeeking(true);
167 void loadLocal().then((url) => {
168 if (token !== seekToken) return;
169 const at = pendingSeek ?? next;
170 const resume = resumeAfterSeek;
171 pendingSeek = null;
172 resumeAfterSeek = false;
173 if (!url) {
174 setSeeking(false);
175 setCurrent(audio.currentTime);
176 setFailed(true);
177 return;
178 }
179 afterLoad = () => {
180 audio.currentTime = at;
181 setCurrent(at);
182 setSeeking(false);
183 if (resume) play();
184 };
185 if (source() === url) {
186 const run = afterLoad;
187 afterLoad = null;
188 run();
189 } else {
190 setSource(url);
191 }
192 });
193 };
194 const play = () => {
195 if (pendingSeek != null) {
196 resumeAfterSeek = true;
197 return;
198 }
199 setFailed(false);
200 void audio.play().catch(() => {
201 // A refused autoplay or an aborted load is not a broken file; the
202 // `error` event reports the latter on its own.
203 setPlaying(false);
204 });
205 };
206 const toggle = () => {
207 if (pendingSeek != null) resumeAfterSeek = !resumeAfterSeek;
208 else if (audio.paused) play();
209 else audio.pause();
210 };
211 // Skips stack on a pending seek's target, not on the stalled stream.
212 const skip = (delta: number) => seek((pendingSeek ?? audio.currentTime) + delta);
213 const cycleRate = () => {
214 const index = RATES.indexOf(rate() as (typeof RATES)[number]);
215 setRate(RATES[(index + 1) % RATES.length]);
216 };
217 const toggleMute = () => {
218 if (muted() || volume() === 0) {
219 setMuted(false);
220 if (volume() === 0) setVolume(1);
221 } else {
222 setMuted(true);
223 }
224 };
225
226 onMount(() => {
227 const attach = () => {
228 if (disposed) return;
229 if (!audio.isConnected) {
230 requestAnimationFrame(attach);
231 return;
232 }
233 connected = true;
234 setSource(objectUrl ?? props.src);
235 };
236 attach();
237 players.add(audio);
238 props.controller?.({ seek, play });
239 });
240 onCleanup(() => {
241 disposed = true;
242 players.delete(audio);
243 audio?.pause();
244 dropLocal();
245 });
246
247 createEffect(() => {
248 audio.playbackRate = rate();
249 store(RATE_KEY, rate());
250 });
251 createEffect(() => {
252 audio.volume = volume();
253 audio.muted = muted();
254 store(VOLUME_KEY, volume());
255 });
256 // A new episode in the same player starts from its own beginning.
257 createEffect(() => {
258 const src = props.src;
259 dropLocal();
260 seekToken += 1;
261 pendingSeek = null;
262 resumeAfterSeek = false;
263 afterLoad = null;
264 setSeeking(false);
265 retriedLoad = false;
266 if (connected) setSource(src);
267 setCurrent(0);
268 setMediaDuration(null);
269 setBuffered(0);
270 setFailed(false);
271 });
272
273 const onKeyDown = (event: KeyboardEvent) => {
274 if (event.altKey || event.ctrlKey || event.metaKey) return;
275 const target = event.target as HTMLElement;
276 if (target.tagName === "INPUT" && (target as HTMLInputElement).type !== "range") return;
277 const key = event.key.toLowerCase();
278 if (key === "k" || (key === " " && target.tagName !== "BUTTON")) {
279 event.preventDefault();
280 toggle();
281 } else if (key === "j") {
282 skip(-SKIP_SECS);
283 } else if (key === "l") {
284 skip(SKIP_SECS);
285 } else if (key === "m") {
286 toggleMute();
287 }
288 };
289
290 const syncDuration = () => {
291 const value = audio.duration;
292 setMediaDuration(Number.isFinite(value) && value > 0 ? value : null);
293 };
294 const syncBuffered = () => {
295 const ranges = audio.buffered;
296 setBuffered(ranges.length ? ranges.end(ranges.length - 1) : 0);
297 };
298
299 const volumeIcon = () => {
300 if (muted() || volume() === 0) return <IconVolumeMute class="h-4 w-4" />;
301 if (volume() < 0.5) return <IconVolumeLow class="h-4 w-4" />;
302 return <IconVolume class="h-4 w-4" />;
303 };
304 const rateLabel = () => `${rate().toLocaleString(undefined, { maximumFractionDigits: 2 })}×`;
305 const ghostButton =
306 "inline-flex h-8 items-center justify-center gap-1 rounded-md px-2 text-xs font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50";
307
308 return (
309 <div
310 role="group"
311 aria-label={props.title ? t("audio.playerFor", { title: props.title }) : t("audio.player")}
312 class={cn("rounded-xl border border-border-hairline bg-surface-overlay/40 p-3", props.class)}
313 onKeyDown={onKeyDown}
314 >
315 <audio
316 ref={audio}
317 src={source()}
318 preload="metadata"
319 autoplay={props.autoplay}
320 onPlay={() => {
321 for (const other of players) if (other !== audio) other.pause();
322 setPlaying(true);
323 // Fetched while the stream plays, so later skips are instant.
324 void loadLocal();
325 }}
326 onPause={() => setPlaying(false)}
327 onEnded={() => setPlaying(false)}
328 onWaiting={() => setBuffering(true)}
329 onPlaying={() => setBuffering(false)}
330 onCanPlay={() => setBuffering(false)}
331 onLoadedMetadata={() => {
332 syncDuration();
333 const run = afterLoad;
334 afterLoad = null;
335 run?.();
336 }}
337 onDurationChange={syncDuration}
338 onProgress={syncBuffered}
339 onTimeUpdate={() => {
340 if (pendingSeek != null) return;
341 setCurrent(audio.currentTime);
342 props.onTimeUpdate?.(audio.currentTime);
343 }}
344 onError={() => {
345 // One quiet retry for a load that raced the element's attachment;
346 // a real failure (bad file, gone episode) fails again and shows.
347 if (!retriedLoad && audio.isConnected && source()) {
348 retriedLoad = true;
349 audio.load();
350 return;
351 }
352 setFailed(true);
353 setPlaying(false);
354 setBuffering(false);
355 }}
356 />
357
358 <div class="flex items-center gap-3">
359 <button
360 type="button"
361 class={cn(
362 "relative flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground transition-colors hover:bg-primary/90 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
363 (seeking() || (buffering() && playing())) && "animate-pulse",
364 )}
365 aria-label={playing() || seeking() ? t("audio.pause") : t("audio.play")}
366 onClick={toggle}
367 >
368 <Show when={playing() || seeking()} fallback={<IconPlay class="ml-0.5 h-5 w-5" />}>
369 <IconPause class="h-5 w-5" />
370 </Show>
371 </button>
372 <div class="min-w-0 flex-1">
373 <Show when={props.title}>
374 <p class="truncate text-sm font-medium text-foreground">{props.title}</p>
375 </Show>
376 <Show when={props.subtitle}>
377 <p class="truncate text-xs text-muted-foreground">{props.subtitle}</p>
378 </Show>
379 </div>
380 <Show when={props.actions}>
381 <div class="flex shrink-0 items-center gap-2">{props.actions}</div>
382 </Show>
383 </div>
384
385 <div class="mt-3">
386 <div class="group relative flex h-4 items-center">
387 <input
388 type="range"
389 class="peer absolute inset-0 z-10 h-full w-full cursor-pointer opacity-0 disabled:cursor-default"
390 min="0"
391 max={duration() ?? 0}
392 step="0.1"
393 value={current()}
394 disabled={!duration()}
395 aria-label={t("audio.seek")}
396 aria-valuetext={t("audio.position", {
397 current: formatDurationClock(current() * 1000),
398 total: formatDurationClock(duration() == null ? null : duration()! * 1000),
399 })}
400 onInput={(event) => seek(Number(event.currentTarget.value))}
401 />
402 <div class="relative h-1.5 w-full overflow-hidden rounded-full bg-muted">
403 <div class="absolute inset-y-0 left-0 bg-foreground/15" style={{ width: `${fraction(buffered()) * 100}%` }} />
404 <div class="absolute inset-y-0 left-0 bg-primary" style={{ width: `${fraction(current()) * 100}%` }} />
405 </div>
406 <div
407 aria-hidden="true"
408 class={cn(
409 "pointer-events-none absolute top-1/2 h-3.5 w-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 transition-transform peer-focus-visible:ring-2 peer-focus-visible:ring-ring",
410 // While the target loads the thumb turns into a spinner right
411 // where playback will resume.
412 seeking() ? "scale-125 animate-spin border-primary border-t-transparent bg-background" : "border-primary bg-background",
413 seeking() || playing() || current() > 0 ? "" : "scale-0 group-hover:scale-100 peer-focus-visible:scale-100",
414 )}
415 style={{ left: `${fraction(current()) * 100}%` }}
416 />
417 </div>
418 <div class="mt-1 flex justify-between text-[11px] tabular-nums text-muted-foreground">
419 <span class="flex items-center gap-1.5">
420 {formatDurationClock(current() * 1000)}
421 <Show when={seeking()}>
422 <span class="text-primary-text" role="status">{t("audio.loadingPosition")}</span>
423 </Show>
424 </span>
425 <span>{formatDurationClock(duration() == null ? null : duration()! * 1000)}</span>
426 </div>
427 </div>
428
429 <div class="mt-1 flex flex-wrap items-center gap-1">
430 <button type="button" class={ghostButton} aria-label={t("audio.back", { secs: SKIP_SECS })} onClick={() => skip(-SKIP_SECS)}>
431 <IconSkipBack class="h-4 w-4" />
432 <span aria-hidden="true">{SKIP_SECS}</span>
433 </button>
434 <button type="button" class={ghostButton} aria-label={t("audio.forward", { secs: SKIP_SECS })} onClick={() => skip(SKIP_SECS)}>
435 <IconSkipForward class="h-4 w-4" />
436 <span aria-hidden="true">{SKIP_SECS}</span>
437 </button>
438 <button
439 type="button"
440 class={cn(ghostButton, "min-w-12 tabular-nums", rate() !== 1 && "text-primary-text")}
441 aria-label={t("audio.speed", { rate: rateLabel() })}
442 onClick={cycleRate}
443 >
444 {rateLabel()}
445 </button>
446
447 <div class="ml-auto flex items-center gap-1">
448 <button
449 type="button"
450 class={ghostButton}
451 aria-label={muted() || volume() === 0 ? t("audio.unmute") : t("audio.mute")}
452 aria-pressed={muted()}
453 onClick={toggleMute}
454 >
455 {volumeIcon()}
456 </button>
457 <input
458 type="range"
459 class="hidden h-1 w-20 cursor-pointer accent-primary sm:block"
460 min="0"
461 max="1"
462 step="0.05"
463 value={muted() ? 0 : volume()}
464 aria-label={t("audio.volume")}
465 onInput={(event) => {
466 setVolume(Number(event.currentTarget.value));
467 setMuted(false);
468 }}
469 />
470 {props.extra}
471 </div>
472 </div>
473
474 <Show when={failed()}>
475 <p role="alert" class="mt-2 text-xs text-destructive-text">
476 {t("audio.loadFailed")}{" "}
477 <button
478 type="button"
479 class="font-medium underline underline-offset-2"
480 onClick={() => {
481 setFailed(false);
482 audio.load();
483 }}
484 >
485 {t("common.tryAgain")}
486 </button>
487 </p>
488 </Show>
489 </div>
490 );
491}