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

OpenXmlOfficeViewer.tsx

171 lines6.4 KB

1import { FilePasswordPrompt } from "./FilePasswordPrompt";
2import { useStableCallback } from "~/hooks/useStableCallback";
3import type { OfficePreviewKind } from "@t3tools/shared/filePreview";
4import { msg, T, useGT } from "gt-react";
5import { lazy, Suspense, useEffect, useRef, useState } from "react";
6import { m } from "~/i18n/messages";
7import {
8 FileSurfaceLoading,
9 FileSurfaceNotice,
10 FILE_SURFACE_SUBHEADER_CLASS,
11} from "./fileSurfaceChrome";
12import { OFFICE_PREVIEW_MAX_BYTES, type OfficeWorkerResult } from "./officePreviewProtocol";
13import { previewErrorText, previewFailureText } from "./previewFailureMessages";
14const WordDocument = lazy(() => import("./office/WordDocument"));
15const Spreadsheet = lazy(() => import("./office/Spreadsheet"));
16const Presentation = lazy(() => import("./office/Presentation"));
17async function readOfficeFile(src: string, signal: AbortSignal) {
18 const response = await fetch(src, { signal });
19 if (!response.ok)
20 throw new Error(m(msg("The file could not be loaded. Close it and try again.")));
21 if (Number(response.headers.get("content-length")) > OFFICE_PREVIEW_MAX_BYTES)
22 throw new Error(m(msg("Preview limited to files under 50 MB.")));
23 const reader = response.body?.getReader();
24 if (!reader) throw new Error(m(msg("The file is unavailable.")));
25 const chunks: Uint8Array<ArrayBuffer>[] = [];
26 let size = 0;
27 try {
28 while (true) {
29 const { value, done } = await reader.read();
30 if (done) break;
31 size += value.length;
32 if (size > OFFICE_PREVIEW_MAX_BYTES)
33 throw new Error(m(msg("Preview limited to files under 50 MB.")));
34 chunks.push(value);
35 }
36 } finally {
37 await reader.cancel();
38 }
39 return new Blob(chunks).arrayBuffer();
41​
42export default function OfficeViewer(props: {
43 readonly src: string;
44 readonly name: string;
45 readonly kind: Extract<OfficePreviewKind, "docx" | "xlsx" | "pptx">;
46 readonly sizeBytes?: number;
47}) {
48 const gt = useGT();
49 const [incorrectPassword, setIncorrectPassword] = useState<boolean | null>(null);
50 const [error, setError] = useState<string | null>(null);
51 const [prepared, setPrepared] = useState<Extract<OfficeWorkerResult, { bytes: ArrayBuffer }>>();
52 const submitPassword = useRef<((password: string) => void) | null>(null);
53 const [details, setDetails] = useState("");
54 const fail = useStableCallback((cause: unknown) =>
55 setError(previewErrorText(cause, m(msg("Could not render this Office document.")))),
56 );
57 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Own the Open XML fetch, preparation worker, and timeout for this source and release them on cleanup.
58 useEffect(() => {
59 if ((props.sizeBytes ?? 0) > OFFICE_PREVIEW_MAX_BYTES) {
60 // Metadata bounds are checked before fetching or starting an engine.
61 // oxlint-disable-next-line react/set-state-in-effect
62 setError(m(msg("Preview limited to files under 50 MB.")));
63 return;
64 }
65 const controller = new AbortController();
66 const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
67 type: "module",
68 });
69 const failure = (cause: unknown) => {
70 if (!controller.signal.aborted) fail(cause);
71 controller.abort();
72 worker.terminate();
73 };
74 const startTimeout = () =>
75 setTimeout(
76 () =>
77 failure(
78 new Error(m(msg("This document took too long to preview. Open it in another app."))),
79 ),
80 30_000,
81 );
82 let timer = startTimeout();
83 submitPassword.current = (password) => {
84 timer = startTimeout();
85 worker.postMessage({ type: "unlock", password }, []);
86 };
87 worker.addEventListener("error", () =>
88 failure(new Error(m(msg("Could not load the Office viewer.")))),
89 );
90 worker.addEventListener("messageerror", () =>
91 failure(new Error(m(msg("Could not read the Office viewer response.")))),
92 );
93 worker.addEventListener("message", (event: MessageEvent<OfficeWorkerResult>) => {
94 if (controller.signal.aborted) return;
95 clearTimeout(timer);
96 if (event.data.type === "password") setIncorrectPassword(event.data.incorrect);
97 else if (event.data.type === "error") failure(new Error(previewFailureText(event.data)));
98 else if ("bytes" in event.data) {
99 setPrepared(event.data);
100 worker.terminate();
101 }
102 });
103 void readOfficeFile(props.src, controller.signal)
104 .then((bytes) => {
105 if (!controller.signal.aborted)
106 worker.postMessage({ type: "open", kind: props.kind, bytes }, [bytes]);
107 })
108 .catch(failure);
109 return () => {
110 submitPassword.current = null;
111 controller.abort();
112 worker.terminate();
113 clearTimeout(timer);
114 };
115 }, [props.src, props.kind, props.sizeBytes, fail]);
116 if (error)
117 return (
118 <div
119 role="alert"
120 className="flex min-h-0 flex-1 flex-col items-center justify-center gap-1 px-6 text-center"
121 >
122 <p className="text-sm font-medium">
123 <T>No preview for this file</T>
124 </p>
125 <p className="max-w-sm text-xs leading-relaxed text-muted-foreground">
126 {gt`${{ error }} Save it or open it in another app.`}
127 </p>
128 </div>
129 );
130 if (incorrectPassword !== null)
131 return (
132 <FilePasswordPrompt
133 incorrect={incorrectPassword}
134 onSubmit={(password) => {
135 setIncorrectPassword(null);
136 submitPassword.current?.(password);
137 }}
138 />
139 );
140 if (!prepared) return <FileSurfaceLoading />;
141 const Viewer = props.kind === "docx" ? WordDocument : Presentation;
142 return (
143 <div className="flex min-h-0 flex-1 flex-col">
144 {details ? (
145 <div className={FILE_SURFACE_SUBHEADER_CLASS}>
146 <span className="text-xs text-muted-foreground" aria-live="polite">
147 {details}
148 {props.kind !== "xlsx" ? ` · ${gt`Fit to width`}` : ""}
149 </span>
150 </div>
151 ) : null}
152 {prepared.truncated ? (
153 <FileSurfaceNotice>
154 <T>Preview limited. Save it or open it in another app to read the full document.</T>
155 </FileSurfaceNotice>
156 ) : null}
157 <Suspense fallback={<FileSurfaceLoading />}>
158 {prepared.view ? (
159 <Spreadsheet
160 bytes={prepared.bytes}
161 view={prepared.view}
162 onDetails={setDetails}
163 onError={fail}
164 />
165 ) : (
166 <Viewer bytes={prepared.bytes} onDetails={setDetails} onError={fail} />
167 )}
168 </Suspense>
169 </div>
170 );