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