The best way to control Claude Code, Codex and more from any computer or phone

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