Open History to see the last commit
1import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
2import {
3 ChevronLeftIcon,
4 ChevronRightIcon,
5 MinusIcon,
6 PlusIcon,
7 RotateCcwIcon,
8} from "lucide-react";
9import { T, useGT, useMessages } from "gt-react";
10import { useEffect, useRef, useState } from "react";
11import {
12 Select,
13 SelectItem,
14 SelectPopup,
15 SelectTrigger,
16 SelectValue,
17} from "~/components/ui/select";
18import { observeResize } from "~/lib/observeResize";
19import { externalUrl } from "./office/links";
20import { useTheme } from "~/hooks/useTheme";
21import { FileSurfaceAction, FileSurfaceLoading } from "./fileSurfaceChrome";
22import type { EpubLocation, EpubPage, OfficeWorkerResult } from "./officePreviewProtocol";
23import { epubSource, prepareEpubDocument } from "./epubSource";
24import { EpubNarration } from "./EpubNarration";
25import { EpubMediaDialog } from "./EpubMediaDialog";
26import { Button } from "~/components/ui/button";
27import { previewFailureText } from "./previewFailureMessages";
28
29type Book = Extract<OfficeWorkerResult, { type: "epub" }>;
30type PageResponse = Extract<OfficeWorkerResult, { type: "epub-page" }>;
31
32function goToAnchor(doc: Document, anchor: string | undefined) {
33 if (anchor) (doc.getElementById(anchor) ?? doc.getElementsByName(anchor)[0])?.scrollIntoView();
34 else doc.defaultView?.scrollTo(0, 0);
35}
36
37function ReadingFrame(props: {
38 readonly page: EpubPage;
39 readonly name: string;
40 readonly location: EpubLocation;
41 readonly zoom: number;
42 readonly navigate: (location: EpubLocation) => void;
43}) {
44 const gt = useGT();
45 const { resolvedTheme } = useTheme();
46 const container = useRef<HTMLDivElement>(null);
47 const frame = useRef<HTMLIFrameElement>(null);
48 const fixed = props.page.fixed;
49 const [size, setSize] = useState({ width: 0, height: 0 });
50 const [media, setMedia] = useState<readonly HTMLMediaElement[]>([]);
51 const [openMedia, setOpenMedia] = useState<HTMLMediaElement | null>(null);
52 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Fit the authored viewport to its container as the preview resizes.
53 useEffect(() => {
54 const element = container.current;
55 if (!element || !fixed) return;
56 const measure = () => setSize({ width: element.clientWidth, height: element.clientHeight });
57 measure();
58 return observeResize(element, measure);
59 }, [fixed]);
60 const scale = fixed
61 ? Math.min(size.width / fixed.width, size.height / fixed.height) * props.zoom
62 : 1;
63 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Change the sandboxed document's reading size without reloading or losing position.
64 useEffect(() => {
65 if (!fixed)
66 frame.current?.contentDocument?.documentElement?.style.setProperty(
67 "zoom",
68 String(props.zoom),
69 "important",
70 );
71 }, [fixed, props.zoom]);
72 const anchor = props.location.anchor;
73 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- A table-of-contents entry can change the anchor within the current document.
74 useEffect(() => {
75 const doc = frame.current?.contentDocument;
76 if (doc?.body) goToAnchor(doc, anchor);
77 }, [anchor]);
78 const darkPage = resolvedTheme === "dark" && !props.page.styles?.length && !fixed;
79 const srcDoc = epubSource(props.page, darkPage);
80 return (
81 <>
82 {props.page.narration?.length && !openMedia ? (
83 <EpubNarration cues={props.page.narration} frame={frame} />
84 ) : null}
85 {media.length > 0 ? (
86 <div className="flex shrink-0 gap-2 overflow-x-auto border-b border-border/60 px-3 py-1">
87 {media.map((item, index) => (
88 <Button
89 // oxlint-disable-next-line react/no-array-index-key -- The authored media order is fixed within a chapter.
90 key={`${item.localName}:${index}`}
91 variant="outline"
92 size="sm-touch"
93 onClick={() => {
94 for (const element of media) element.pause();
95 setOpenMedia(item);
96 }}
97 >
98 {item.title ||
99 item.getAttribute("aria-label") ||
100 (item.localName === "video" ? gt`Video preview` : gt`Audio preview`)}
101 </Button>
102 ))}
103 </div>
104 ) : null}
105 {openMedia ? <EpubMediaDialog media={openMedia} onClose={() => setOpenMedia(null)} /> : null}
106 <div ref={container} className="min-h-0 flex-1 overflow-auto scrollbar-gutter-both">
107 <div
108 className={fixed ? "mx-auto" : "size-full"}
109 style={
110 fixed
111 ? { width: fixed.width * scale, height: fixed.height * scale, overflow: "hidden" }
112 : undefined
113 }
114 >
115 <iframe
116 ref={frame}
117 title={props.name}
118 srcDoc={srcDoc}
119 sandbox="allow-same-origin"
120 className={`block border-0 ${fixed ? "origin-top-left" : "size-full"} ${darkPage ? "" : "bg-white"}`}
121 style={
122 fixed
123 ? { width: fixed.width, height: fixed.height, transform: `scale(${scale})` }
124 : undefined
125 }
126 onLoad={(event) => {
127 const doc = event.currentTarget.contentDocument;
128 if (!doc?.body) return;
129 prepareEpubDocument(doc);
130 // WKWebView can only start media from controls in the parent of this sandbox.
131 if ("ReactNativeWebView" in window && "webkit" in window) {
132 setMedia(
133 Array.from(
134 doc.querySelectorAll<HTMLMediaElement>(
135 "audio[src],video[src],audio:has(source[src]),video:has(source[src])",
136 ),
137 ),
138 );
139 }
140 if (!fixed)
141 doc.documentElement.style.setProperty("zoom", String(props.zoom), "important");
142 goToAnchor(doc, props.location.anchor);
143 doc.onclick = (click) => {
144 const target = click.target;
145 if (!(target instanceof doc.defaultView!.Element)) return;
146 const link = target.closest("a[href]");
147 if (!link) return;
148 click.preventDefault();
149 const href = link.getAttribute("data-epub-external");
150 if (href !== null) {
151 const url = externalUrl(href);
152 if (url && click.isTrusted) window.open(url, "_blank", "noopener,noreferrer");
153 return;
154 }
155 const linkIndex = link.getAttribute("data-epub-index");
156 if (linkIndex === null) return;
157 const index = Number(linkIndex);
158 const anchor = link.getAttribute("data-epub-anchor") ?? undefined;
159 if (index === props.location.index) goToAnchor(doc, anchor);
160 props.navigate({ index, ...(anchor ? { anchor } : {}) });
161 };
162 }}
163 />
164 </div>
165 </div>
166 </>
167 );
168}
169
170export default function EpubViewer(props: {
171 readonly name: string;
172 readonly book: Book;
173 readonly response: PageResponse | null;
174 readonly sizeBytes: number | undefined;
175 readonly loadPage: (index: number) => void;
176}) {
177 const gt = useGT();
178 const messages = useMessages();
179 const [location, setLocation] = useState<EpubLocation>({ index: props.book.first });
180 const [zoom, setZoom] = useState(1);
181 const { index, anchor } = location;
182 const loadPage = props.loadPage;
183 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Request the selected section from the EPUB worker.
184 useEffect(() => loadPage(index), [index, loadPage]);
185 const result = props.response?.index === index ? props.response.result : undefined;
186 const page = result && "html" in result ? result : undefined;
187 const chapterLabel = (i: number) =>
188 props.book.chapters[i]?.title ??
189 (i === index ? page?.title : undefined) ??
190 gt`Chapter ${{ number: String(i + 1) }}`;
191 const named = new Set(props.book.contents.map((item) => item.index));
192 const options: (EpubLocation & { title: string })[] = [
193 ...props.book.contents,
194 ...props.book.chapters.flatMap((_, i) =>
195 named.has(i) ? [] : [{ index: i, title: chapterLabel(i) }],
196 ),
197 ].sort((a, b) => a.index - b.index);
198 const selected = options.findIndex(
199 (option) => option.index === index && option.anchor === anchor,
200 );
201 const previous = props.book.chapters.findLastIndex((chapter, i) => i < index && chapter.linear);
202 const next = props.book.chapters.findIndex((chapter, i) => i > index && chapter.linear);
203 return (
204 <div className="flex min-h-0 flex-1 flex-col">
205 {props.book.chapters.length > 1 || props.book.contents.length > 1 ? (
206 <div
207 className="flex min-h-10 shrink-0 items-center gap-2 border-b border-border/60 px-3 text-xs max-sm:py-1 max-sm:[&_button]:min-h-11 max-sm:[&_button]:min-w-11"
208 dir={props.book.rtl ? "rtl" : "ltr"}
209 >
210 <FileSurfaceAction
211 label={gt`Previous chapter`}
212 disabled={previous < 0}
213 onPress={() => setLocation({ index: previous })}
214 >
215 {props.book.rtl ? (
216 <ChevronRightIcon className="size-3.5" />
217 ) : (
218 <ChevronLeftIcon className="size-3.5" />
219 )}
220 </FileSurfaceAction>
221 <div className="min-w-0 flex-1">
222 <Select
223 value={selected < 0 ? null : selected}
224 onValueChange={(value) => {
225 if (value !== null && options[value]) setLocation(options[value]);
226 }}
227 >
228 <SelectTrigger
229 aria-label={gt({ context: "noun, book chapter picker" })`Chapter`}
230 size="xs"
231 >
232 <SelectValue>{options[selected]?.title ?? chapterLabel(index)}</SelectValue>
233 </SelectTrigger>
234 <SelectPopup>
235 {options.map((option, i) => (
236 <SelectItem key={`${option.index}:${option.anchor ?? ""}`} value={i}>
237 {option.title}
238 </SelectItem>
239 ))}
240 </SelectPopup>
241 </Select>
242 </div>
243 <FileSurfaceAction
244 label={gt`Next chapter`}
245 disabled={next < 0}
246 onPress={() => setLocation({ index: next })}
247 >
248 {props.book.rtl ? (
249 <ChevronLeftIcon className="size-3.5" />
250 ) : (
251 <ChevronRightIcon className="size-3.5" />
252 )}
253 </FileSurfaceAction>
254 </div>
255 ) : null}
256 <div className="flex min-h-10 shrink-0 flex-wrap items-center gap-1 border-b border-border/60 px-3 py-1 text-xs text-muted-foreground max-sm:[&_button]:min-h-11 max-sm:[&_button]:min-w-11">
257 <span className="min-w-0 flex-1 tabular-nums" role="status">
258 {gt`Chapter ${{ page: String(index + 1) }} of ${{ count: String(props.book.chapters.length) }}`}
259 {props.sizeBytes ? ` · ${formatAttachmentSize(props.sizeBytes, messages)}` : ""}
260 </span>
261 <FileSurfaceAction
262 label={gt`Decrease reading size`}
263 disabled={zoom <= 0.5}
264 onPress={() => setZoom(zoom - 0.25)}
265 >
266 <MinusIcon className="size-3.5" />
267 </FileSurfaceAction>
268 <span className="min-w-10 text-center tabular-nums">{Math.round(zoom * 100)}%</span>
269 <FileSurfaceAction
270 label={gt`Increase reading size`}
271 disabled={zoom >= 2}
272 onPress={() => setZoom(zoom + 0.25)}
273 >
274 <PlusIcon className="size-3.5" />
275 </FileSurfaceAction>
276 <FileSurfaceAction
277 label={gt`Reset reading size`}
278 disabled={zoom === 1}
279 onPress={() => setZoom(1)}
280 >
281 <RotateCcwIcon className="size-3.5" />
282 </FileSurfaceAction>
283 </div>
284 {page ? (
285 <ReadingFrame
286 key={index}
287 page={page}
288 name={`${props.name}: ${chapterLabel(index)}`}
289 location={location}
290 zoom={zoom}
291 navigate={setLocation}
292 />
293 ) : result && "message" in result ? (
294 <div
295 role="alert"
296 className="flex flex-1 flex-col items-center justify-center gap-1 px-6 text-center"
297 >
298 <p className="text-sm font-medium">
299 <T>No preview for this file</T>
300 </p>
301 <p className="max-w-sm text-xs text-muted-foreground">
302 {previewFailureText(result, messages)}
303 </p>
304 </div>
305 ) : (
306 <FileSurfaceLoading />
307 )}
308 </div>
309 );
310}