Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

EpubNarration.tsx

156 lines4.9 KB

1import { useGT } from "gt-react";
2import { HeadphonesIcon, PauseIcon } from "lucide-react";
3import { useEffect, useEffectEvent, useRef, useState, type RefObject } from "react";
4import { Button } from "~/components/ui/button";
5import type { EpubNarrationCue } from "./officePreviewProtocol";
6​
7export function EpubNarration(props: {
8 readonly cues: readonly EpubNarrationCue[];
9 readonly frame: RefObject<HTMLIFrameElement | null>;
10}) {
11 const gt = useGT();
12 const audio = useRef<HTMLAudioElement>(null);
13 const [playing, setPlaying] = useState(false);
14 const [failed, setFailed] = useState(false);
15 const active = useRef(false);
16 const index = useRef(0);
17 const request = useRef(0);
18 const highlight = useRef<Element | null>(null);
19​
20 function mark(cue: EpubNarrationCue | undefined) {
21 const doc = props.frame.current?.contentDocument;
22 const target = cue?.anchor ? doc?.getElementById(cue.anchor) : null;
23 if (target === highlight.current) return;
24 highlight.current?.classList.remove("t3-epub-narration-active");
25 highlight.current = target ?? null;
26 if (!target || !doc?.defaultView) return;
27 target.classList.add("t3-epub-narration-active");
28 const rect = target.getBoundingClientRect();
29 if (rect.top < 0 || rect.bottom > doc.defaultView.innerHeight)
30 target.scrollIntoView({ block: "nearest", inline: "nearest" });
31 }
32​
33 function pause() {
34 active.current = false;
35 request.current++;
36 audio.current?.pause();
37 setPlaying(false);
38 }
39​
40 function finish() {
41 pause();
42 index.current = 0;
43 if (audio.current) audio.current.removeAttribute("src");
44 mark(undefined);
45 }
46​
47 function fail() {
48 finish();
49 setFailed(true);
50 }
51​
52 function play(cue: EpubNarrationCue, resume: boolean) {
53 const player = audio.current;
54 if (!player) return;
55 const command = ++request.current;
56 const sameSource = player.getAttribute("src") === cue.src;
57 const reload = sameSource && player.error !== null;
58 const start = resume && sameSource ? player.currentTime : cue.begin;
59 if (!sameSource) player.src = cue.src;
60 else if (reload) player.load();
61 if (!resume || !sameSource || reload) player.currentTime = start;
62 void player.play().catch(() => {
63 if (command !== request.current) return;
64 fail();
65 });
66 }
67​
68 function advance() {
69 const previous = props.cues[index.current];
70 const next = props.cues[++index.current];
71 if (!next) return finish();
72 const player = audio.current;
73 if (
74 !player ||
75 player.ended ||
76 previous?.src !== next.src ||
77 previous.end === undefined ||
78 Math.abs(next.begin - previous.end) > 0.02
79 ) {
80 play(next, false);
81 }
82 }
83​
84 function synchronize() {
85 const player = audio.current;
86 const cue = props.cues[index.current];
87 if (!active.current || !player || !cue) return;
88 if (!player.seeking && cue.end !== undefined && player.currentTime >= cue.end) {
89 advance();
90 }
91 if (active.current) mark(props.cues[index.current]);
92 }
93​
94 const synchronizeWhilePlaying = useEffectEvent(synchronize);
95​
96 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Cancel narration callbacks when the chapter is replaced.
97 useEffect(() => {
98 const player = audio.current;
99 if (!player) return;
100 let timer: number | undefined;
101 const stop = () => window.clearInterval(timer);
102 const start = () => {
103 stop();
104 synchronizeWhilePlaying();
105 timer = window.setInterval(() => synchronizeWhilePlaying(), 50);
106 };
107 player.addEventListener("playing", start);
108 player.addEventListener("pause", stop);
109 return () => {
110 active.current = false;
111 request.current++;
112 stop();
113 player.removeEventListener("playing", start);
114 player.removeEventListener("pause", stop);
115 player.pause();
116 highlight.current?.classList.remove("t3-epub-narration-active");
117 };
118 }, []);
119​
120 const toggle = () => {
121 if (active.current) return pause();
122 const cue = props.cues[index.current];
123 if (!cue) return;
124 setFailed(false);
125 setPlaying(true);
126 active.current = true;
127 play(cue, true);
128 };
129​
130 return (
131 <div className="flex min-h-11 shrink-0 flex-wrap items-center gap-2 border-b border-border/60 px-3 py-1">
132 <Button size="sm-touch" variant="outline" onClick={toggle}>
133 {playing ? <PauseIcon /> : <HeadphonesIcon />}
134 {playing ? gt`Pause narration` : gt`Read aloud`}
135 </Button>
136 {failed ? (
137 <span role="status" className="text-xs">
138 {gt`Could not play narration.`}
139 </span>
140 ) : null}
141 <audio
142 ref={audio}
143 preload="none"
144 onTimeUpdate={synchronize}
145 onError={({ currentTarget: player }) => {
146 if (!active.current || !player.error) return;
147 fail();
148 }}
149 onEnded={() => {
150 if (!active.current || !audio.current?.ended) return;
151 advance();
152 }}
153 />
154 </div>
155 );