Open History to see the last commit
1import { FilePasswordPrompt } from "./FilePasswordPrompt";
2import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
3/* oxlint-disable react/no-array-index-key -- Spreadsheet rows and columns retain their source positions. */
4import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
5import type { OfficePreviewKind } from "@t3tools/shared/filePreview";
6import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
7import { msg, T, useGT, useMessages, plural, part } from "gt-react";
8import { lazy, Suspense, useContext, useEffect, useRef, useState } from "react";
9import { m } from "~/i18n/messages";
10import { useStableCallback } from "~/hooks/useStableCallback";
11
12import VirtualTablePreview from "./VirtualTablePreview";
13import { PreviewPositionKey } from "./previewPosition";
14
15import {
16 Select,
17 SelectItem,
18 SelectPopup,
19 SelectTrigger,
20 SelectValue,
21} from "~/components/ui/select";
22
23import { FileSurfaceAction, FileSurfaceLoading, FileSurfaceNotice } from "./fileSurfaceChrome";
24import { OFFICE_PREVIEW_MAX_BYTES, type OfficeWorkerResult } from "./officePreviewProtocol";
25import { previewFailureText } from "./previewFailureMessages";
26
27const EpubViewer = lazy(() => import("./EpubViewer"));
28const DocumentPages = lazy(() => import("./DocumentPages"));
29const NotebookPreview = lazy(() => import("./NotebookPreview"));
30
31type Workbook = Extract<OfficeWorkerResult, { type: "ods" }>;
32
33const OpenXmlOfficeViewer = lazy(() => import("./OpenXmlOfficeViewer"));
34
35async function readOfficeFile(src: string, signal: AbortSignal) {
36 const response = await fetch(src, { signal });
37 if (!response.ok)
38 throw new Error(m(msg("The file could not be loaded. Close it and try again.")));
39 if (Number(response.headers.get("content-length")) > OFFICE_PREVIEW_MAX_BYTES)
40 throw new Error(m(msg("Preview limited to files under 50 MB.")));
41 const reader = response.body?.getReader();
42 if (!reader) throw new Error(m(msg("The file is unavailable.")));
43 const chunks: Uint8Array<ArrayBuffer>[] = [];
44 let size = 0;
45 try {
46 while (true) {
47 const { value, done } = await reader.read();
48 if (done) break;
49 size += value.length;
50 if (size > OFFICE_PREVIEW_MAX_BYTES)
51 throw new Error(m(msg("Preview limited to files under 50 MB.")));
52 chunks.push(value);
53 }
54 } finally {
55 await reader.cancel();
56 }
57 return new Blob(chunks).arrayBuffer();
58}
59
60export default function OfficeViewer(props: {
61 readonly src: string;
62 readonly name: string;
63 readonly kind: OfficePreviewKind;
64 readonly sizeBytes?: number;
65}) {
66 if (props.kind === "docx" || props.kind === "xlsx" || props.kind === "pptx")
67 return (
68 <Suspense fallback={<FileSurfaceLoading />}>
69 <OpenXmlOfficeViewer {...props} kind={props.kind} />
70 </Suspense>
71 );
72 return <ExtendedOfficeViewer {...props} />;
73}
74
75function ExtendedOfficeViewer(props: {
76 readonly src: string;
77 readonly name: string;
78 readonly kind: OfficePreviewKind;
79 readonly sizeBytes?: number;
80}) {
81 const gt = useGT();
82 const messages = useMessages();
83 const [epub, setEpub] = useState<Extract<OfficeWorkerResult, { type: "epub" }> | null>(null);
84 const [epubPage, setEpubPage] = useState<Extract<
85 OfficeWorkerResult,
86 { type: "epub-page" }
87 > | null>(null);
88 const [incorrectPassword, setIncorrectPassword] = useState<boolean | null>(null);
89 const [error, setError] = useState<string | null>(null);
90 const [sheetPages, setSheetPages] = useState(new Map<string, string[][]>());
91 const pendingPages = useRef(new Set<string>());
92 const [previewDocument, setDocument] = useState<Extract<
93 OfficeWorkerResult,
94 { type: "document" }
95 > | null>(null);
96 const [notebook, setNotebook] = useState<Extract<
97 OfficeWorkerResult,
98 { type: "notebook" }
99 > | null>(null);
100 const [sheetCopy, setSheetCopy] = useState<Extract<
101 OfficeWorkerResult,
102 { type: "sheet-copy" }
103 > | null>(null);
104 const [workbook, setWorkbook] = useState<Workbook | null>(null);
105 const [count, setCount] = useState(0);
106 const [fileSize, setFileSize] = useState(props.sizeBytes);
107 const [page, setPage] = useState(0);
108 const filePositionKey = useContext(PreviewPositionKey);
109 const workerRef = useRef<Worker | null>(null);
110 const selectedSheet = useRef(0);
111 const submitPassword = useRef<((password: string) => void) | null>(null);
112 const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
113 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Own the Office fetch, preparation worker, and timeout for this source and release them on cleanup.
114 useEffect(() => {
115 const controller = new AbortController();
116 if ((props.sizeBytes ?? 0) > OFFICE_PREVIEW_MAX_BYTES) {
117 // oxlint-disable-next-line react/set-state-in-effect -- The file metadata can reject the preview before loading bytes or engines.
118 setError(m(msg("Preview limited to files under 50 MB.")));
119 return;
120 }
121 const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
122 type: "module",
123 });
124 workerRef.current = worker;
125 const fail = (message: string) => {
126 if (!controller.signal.aborted) setError(message);
127 controller.abort();
128 worker.terminate();
129 if (timerRef.current) clearTimeout(timerRef.current);
130 };
131 const startTimeout = () =>
132 setTimeout(
133 () => fail(m(msg("This document took too long to preview. Open it in another app."))),
134 30_000,
135 );
136 timerRef.current = startTimeout();
137 submitPassword.current = (password) => {
138 timerRef.current = startTimeout();
139 worker.postMessage({ type: "unlock", password }, []);
140 };
141 worker.addEventListener("error", () =>
142 fail(m(msg("Could not load the Office viewer. Close the file and try again."))),
143 );
144 worker.addEventListener("message", (event: MessageEvent<OfficeWorkerResult>) => {
145 if (controller.signal.aborted) return;
146 const result = event.data;
147 if (result.type === "password") {
148 if (timerRef.current) clearTimeout(timerRef.current);
149 setIncorrectPassword(result.incorrect);
150 } else if (result.type === "error") fail(previewFailureText(result));
151 else if (result.type === "epub") {
152 if (timerRef.current) clearTimeout(timerRef.current);
153 setEpub(result);
154 } else if (result.type === "epub-page") {
155 setEpubPage(result);
156 } else if (result.type === "document") {
157 if (timerRef.current) clearTimeout(timerRef.current);
158 setDocument(result);
159 setCount(result.pages.length > 1 ? result.pages.length : 0);
160 } else if (result.type === "notebook") {
161 if (timerRef.current) clearTimeout(timerRef.current);
162 setNotebook(result);
163 } else if (result.type === "ods") {
164 if (timerRef.current) clearTimeout(timerRef.current);
165 setWorkbook(result);
166 setCount(result.sheets.length);
167 worker.postMessage({ type: "sheet-copy", sheet: selectedSheet.current });
168 } else if (result.type === "sheet-copy") {
169 setSheetCopy(result);
170 } else if (result.type === "sheet-page") {
171 const key = `${result.sheet}:${result.index}`;
172 pendingPages.current.delete(key);
173 setSheetPages((old) => {
174 const next = new Map(old);
175 next.set(key, result.rows);
176 if (next.size > 12) next.delete(next.keys().next().value!);
177 return next;
178 });
179 }
180 });
181 void readOfficeFile(props.src, controller.signal)
182 .then((bytes) => {
183 if (!controller.signal.aborted) {
184 setFileSize(bytes.byteLength);
185 worker.postMessage({ type: "open", kind: props.kind, bytes }, [bytes]);
186 }
187 })
188 .catch((cause: unknown) =>
189 fail(thrownErrorMessage(cause, m) ?? m(msg("Could not read this file."))),
190 );
191 return () => {
192 submitPassword.current = null;
193 controller.abort();
194 worker.terminate();
195 workerRef.current = null;
196 if (timerRef.current) clearTimeout(timerRef.current);
197 };
198 }, [props.src, props.kind, props.sizeBytes]);
199 const selectPage = (index: number) => {
200 if (workbook && index !== selectedSheet.current) {
201 selectedSheet.current = index;
202 workerRef.current?.postMessage({ type: "sheet-copy", sheet: index });
203 }
204 setPage(index);
205 };
206 const loadEpubPage = useStableCallback((index: number) =>
207 workerRef.current?.postMessage({ type: "epub-page", index }),
208 );
209 if (error)
210 return (
211 <div
212 role="alert"
213 className="flex min-h-0 flex-1 flex-col items-center justify-center gap-1 px-6 text-center"
214 >
215 <p className="text-sm font-medium">
216 <T>No preview for this file</T>
217 </p>
218 <p className="max-w-sm text-xs leading-relaxed text-muted-foreground">
219 {gt`${{ error }} Save it or open it in another app.`}
220 </p>
221 </div>
222 );
223 if (incorrectPassword !== null)
224 return (
225 <FilePasswordPrompt
226 incorrect={incorrectPassword}
227 onSubmit={(password) => {
228 setIncorrectPassword(null);
229 submitPassword.current?.(password);
230 }}
231 />
232 );
233 if (notebook)
234 return (
235 <Suspense fallback={<FileSurfaceLoading />}>
236 <NotebookPreview notebook={notebook} sizeBytes={fileSize} />
237 </Suspense>
238 );
239 if (epub)
240 return (
241 <Suspense fallback={<FileSurfaceLoading />}>
242 <EpubViewer
243 name={props.name}
244 book={epub}
245 response={epubPage}
246 sizeBytes={fileSize}
247 loadPage={loadEpubPage}
248 />
249 </Suspense>
250 );
251 const sheet = workbook?.sheets[page];
252 const copyText = sheetCopy?.sheet === page ? sheetCopy.text : undefined;
253 const documentPage = previewDocument?.pages[page];
254 const navigation = workbook ? "sheet" : (previewDocument?.navigation ?? "slide");
255 const documentCount = previewDocument?.pages.length ?? 0;
256 const sheetName = (index: number) =>
257 workbook?.sheets[index]?.name ?? gt`Sheet ${{ number: String(index + 1) }}`;
258 const pageTitle = (index: number) =>
259 previewDocument?.pages[index]?.title ?? gt`Page ${{ number: String(index + 1) }}`;
260 const documentDetails =
261 navigation === "slide"
262 ? gt`${plural(
263 { count: documentCount },
264 {
265 one: part`${{ count: documentCount }} slide`,
266 other: part`${{ count: documentCount }} slides`,
267 },
268 )}`
269 : gt`${plural(
270 { count: documentCount },
271 {
272 one: part`${{ count: documentCount }} page`,
273 other: part`${{ count: documentCount }} pages`,
274 },
275 )}`;
276 const previousLabel = {
277 sheet: gt`Previous sheet`,
278 page: gt`Previous page`,
279 slide: gt`Previous slide`,
280 }[navigation];
281 const nextLabel = {
282 sheet: gt`Next sheet`,
283 page: gt`Next page`,
284 slide: gt`Next slide`,
285 }[navigation];
286 const sizeDetails =
287 fileSize !== undefined
288 ? ` · ${fileSize === 0 ? gt`0 bytes` : formatAttachmentSize(fileSize, messages)}`
289 : "";
290 return (
291 <div className="flex min-h-0 flex-1 flex-col">
292 {count > 0 ? (
293 <div className="flex h-10 shrink-0 items-center gap-2 border-b border-border/60 px-3 text-xs">
294 <FileSurfaceAction
295 label={previousLabel}
296 disabled={page === 0}
297 onPress={() => selectPage(page - 1)}
298 >
299 <ChevronLeftIcon className="size-3.5" />
300 </FileSurfaceAction>
301 {workbook ? (
302 <div className="min-w-0 flex-1">
303 <Select
304 value={page}
305 onValueChange={(value) => {
306 if (value !== null) selectPage(value);
307 }}
308 >
309 <SelectTrigger
310 aria-label={gt({ context: "noun, spreadsheet sheet picker" })`Sheet`}
311 size="xs"
312 >
313 <SelectValue>{sheet ? sheetName(page) : undefined}</SelectValue>
314 </SelectTrigger>
315 <SelectPopup>
316 {workbook.sheets.map((item, index) => (
317 <SelectItem key={index} value={index}>
318 {item.name ?? sheetName(index)}
319 </SelectItem>
320 ))}
321 </SelectPopup>
322 </Select>
323 </div>
324 ) : (
325 <span className="flex-1 text-center tabular-nums" aria-live="polite">
326 {navigation === "slide"
327 ? gt`Slide ${{ page: String(page + 1) }} of ${{ count: String(count) }}`
328 : gt`Page ${{ page: String(page + 1) }} of ${{ count: String(count) }}`}
329 </span>
330 )}
331 <FileSurfaceAction
332 label={nextLabel}
333 disabled={page + 1 === count}
334 onPress={() => selectPage(page + 1)}
335 >
336 <ChevronRightIcon className="size-3.5" />
337 </FileSurfaceAction>
338 </div>
339 ) : null}
340 {props.kind === "ods" && sheet ? (
341 <div
342 className="flex min-h-10 shrink-0 flex-wrap items-center gap-x-1 border-b border-border/60 px-3 py-2 text-xs text-muted-foreground tabular-nums"
343 role="status"
344 >
345 {gt`Sheet ${{ page: String(page + 1) }} of ${{ count: String(count) }}`} ·{" "}
346 {gt`${plural(
347 { count: sheet.rowCount },
348 {
349 one: part`${{ formatted: sheet.rowCount.toLocaleString() }} row`,
350 other: part`${{ formatted: sheet.rowCount.toLocaleString() }} rows`,
351 },
352 )}`}{" "}
353 ·{" "}
354 {gt`${plural(
355 { count: sheet.columns },
356 {
357 one: part`${{ formatted: sheet.columns.toLocaleString() }} column`,
358 other: part`${{ formatted: sheet.columns.toLocaleString() }} columns`,
359 },
360 )}`}
361 {sizeDetails}
362 </div>
363 ) : null}
364 {documentPage ? (
365 <>
366 <FileSurfaceNotice>
367 <T>Text and images. Layout and embedded objects may differ from the original.</T>
368 </FileSurfaceNotice>
369 <Suspense fallback={<FileSurfaceLoading />}>
370 <DocumentPages
371 html={documentPage.html}
372 name={`${props.name}: ${pageTitle(page)}`}
373 details={`${documentDetails}${sizeDetails}`}
374 />
375 </Suspense>
376 </>
377 ) : sheet ? (
378 <>
379 <FileSurfaceNotice>
380 {sheet.truncated
381 ? props.kind === "ods"
382 ? gt`Cell values only. Charts, images, and formatting are not shown. Limited to 500 rows and 50 columns.`
383 : gt`Cell values only. Charts, images, and formatting are not shown. Preview limited to 250,000 rows, 1,024 columns, and bounded cell text.`
384 : gt`Cell values only. Charts, images, and formatting are not shown.`}
385 </FileSurfaceNotice>
386 {sheet.rowCount === 0 ? (
387 <p className="p-6 text-xs text-muted-foreground">
388 <T>This sheet is empty.</T>
389 </p>
390 ) : (
391 <PreviewPositionKey
392 value={filePositionKey === null ? null : `${filePositionKey}:${page}`}
393 >
394 <VirtualTablePreview
395 key={page}
396 name={`${props.name}: ${sheetName(page)}`}
397 count={sheet.rowCount}
398 columns={sheet.columns}
399 rowIndexes={sheet.rowIndexes}
400 columnIndexes={sheet.columnIndexes}
401 {...(copyText === undefined
402 ? {}
403 : { onCopyAll: (clipboard) => clipboard.setData("text/plain", copyText) })}
404 getRows={(index) => (index === 0 ? sheet.rows : sheetPages.get(`${page}:${index}`))}
405 loadPage={(index) => {
406 const key = `${page}:${index}`;
407 if (pendingPages.current.has(key)) return;
408 pendingPages.current.add(key);
409 workerRef.current?.postMessage({ type: "sheet-page", sheet: page, index });
410 }}
411 />
412 </PreviewPositionKey>
413 )}
414 </>
415 ) : (
416 <FileSurfaceLoading />
417 )}
418 </div>
419 );
420}