The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { msg, T, useGT, useMessages } from "gt-react"; |
| 2 | import { useEffect, useImperativeHandle, useRef, useState, type RefObject } from "react"; |
| 3 | import { m } from "~/i18n/messages"; |
| 4 | import { parseDelimitedPreview } from "@t3tools/shared/delimitedPreview"; |
| 5 | import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; |
| 6 | import { useClientSettings } from "~/hooks/useSettings"; |
| 7 | import { FileSurfaceFailure, FileSurfaceLoading, FileSurfaceNotice } from "./fileSurfaceChrome"; |
| 8 | import { PREVIEW_PAGE_ROWS, type TextPreviewResult } from "./largeTextProtocol"; |
| 9 | import { previewFailureText } from "./previewFailureMessages"; |
| 10 | import VirtualTablePreview from "./VirtualTablePreview"; |
| 11 | |
| 12 | const FIRST_SCREEN_BYTES = 16 * 1024; |
| 13 | |
| 14 | function firstScreen(text: string, delimiter: "," | "\t" | null, complete: boolean) { |
| 15 | if (!text || text.includes("\0")) return []; |
| 16 | const rows = delimiter |
| 17 | ? parseDelimitedPreview(text, delimiter, { |
| 18 | maxRows: PREVIEW_PAGE_ROWS * 2 + 1, |
| 19 | maxColumns: 1024, |
| 20 | maxCellLength: FIRST_SCREEN_BYTES, |
| 21 | }).rows |
| 22 | : text |
| 23 | .replace(/\r?\n$|\r$/, "") |
| 24 | .split(/\r\n|\n|\r/) |
| 25 | .slice(0, PREVIEW_PAGE_ROWS * 2 + 1) |
| 26 | .map((line) => [line]); |
| 27 | // A byte range can end inside a quoted record or a UTF-8 character. |
| 28 | if (!complete) rows.pop(); |
| 29 | return rows.slice(0, PREVIEW_PAGE_ROWS * 2); |
| 30 | } |
| 31 | |
| 32 | export default function LargeTextViewer(props: { |
| 33 | readonly name: string; |
| 34 | readonly src?: string; |
| 35 | readonly text?: string; |
| 36 | readonly sizeBytes?: number; |
| 37 | readonly onRetry?: () => void; |
| 38 | readonly copyContents?: RefObject<(() => Promise<string>) | null>; |
| 39 | readonly delimiter: "," | "\t" | null; |
| 40 | readonly revealLine?: number | null; |
| 41 | readonly revealRequestId?: number; |
| 42 | /** A preview's own wrap toggle; omitted follows the word wrap setting. */ |
| 43 | readonly wordWrap?: boolean; |
| 44 | }) { |
| 45 | const gt = useGT(); |
| 46 | const messages = useMessages(); |
| 47 | const [meta, setMeta] = useState<Extract<TextPreviewResult, { type: "meta" }> | null>(null); |
| 48 | const [pages, setPages] = useState(new Map<number, string[][]>()); |
| 49 | const [error, setError] = useState<string | null>(null); |
| 50 | const worker = useRef<Worker | null>(null); |
| 51 | const copyPending = useRef<{ |
| 52 | resolve: (text: string) => void; |
| 53 | reject: (cause: Error) => void; |
| 54 | } | null>(null); |
| 55 | const pending = useRef(new Set<number>()); |
| 56 | const defaultWordWrap = useClientSettings((settings) => settings.wordWrap); |
| 57 | const wordWrap = props.wordWrap ?? defaultWordWrap; |
| 58 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Own the prefix fetch and indexing worker, cancelling requests and pending copies when the source changes or unmounts. |
| 59 | useEffect(() => { |
| 60 | // oxlint-disable-next-line react/set-state-in-effect -- A replacement source must discard the previous worker's error and pages. |
| 61 | setError(null); |
| 62 | setMeta(null); |
| 63 | setPages(new Map()); |
| 64 | const controller = new AbortController(); |
| 65 | let indexed = false; |
| 66 | let prefetched = false; |
| 67 | const paintFirstScreen = (text: string, complete: boolean) => { |
| 68 | if (indexed || controller.signal.aborted) return; |
| 69 | const rows = firstScreen(text, props.delimiter, complete); |
| 70 | if (!rows.length) return; |
| 71 | prefetched = true; |
| 72 | setPages( |
| 73 | new Map( |
| 74 | [0, PREVIEW_PAGE_ROWS] |
| 75 | .filter((start) => start < rows.length) |
| 76 | .map((start) => [ |
| 77 | start / PREVIEW_PAGE_ROWS, |
| 78 | rows.slice(start, start + PREVIEW_PAGE_ROWS), |
| 79 | ]), |
| 80 | ), |
| 81 | ); |
| 82 | setMeta({ |
| 83 | type: "meta", |
| 84 | count: rows.length, |
| 85 | columns: rows.reduce((max, row) => Math.max(max, row.length), 1), |
| 86 | complete: false, |
| 87 | }); |
| 88 | }; |
| 89 | const startWorker = () => { |
| 90 | if (controller.signal.aborted) return; |
| 91 | const engine = new Worker(new URL("./largeText.worker.ts", import.meta.url), { |
| 92 | type: "module", |
| 93 | }); |
| 94 | worker.current = engine; |
| 95 | engine.addEventListener("message", (event: MessageEvent<TextPreviewResult>) => { |
| 96 | const result = event.data; |
| 97 | if (result.type === "copy") { |
| 98 | copyPending.current?.resolve(result.text); |
| 99 | copyPending.current = null; |
| 100 | } else if (result.type === "error") { |
| 101 | copyPending.current?.reject(new Error(previewFailureText(result))); |
| 102 | copyPending.current = null; |
| 103 | if (result.operation !== "copy") setError(previewFailureText(result)); |
| 104 | } else if (result.type === "meta") { |
| 105 | indexed = true; |
| 106 | if (prefetched) { |
| 107 | setPages(new Map()); |
| 108 | pending.current.clear(); |
| 109 | prefetched = false; |
| 110 | } |
| 111 | setMeta(result); |
| 112 | } else if (result.type === "page") { |
| 113 | pending.current.delete(result.index); |
| 114 | setPages((old) => { |
| 115 | const previous = old.get(result.index); |
| 116 | if ( |
| 117 | previous?.length === result.rows.length && |
| 118 | previous.every( |
| 119 | (row, index) => |
| 120 | row.length === result.rows[index]!.length && |
| 121 | row.every((cell, column) => cell === result.rows[index]![column]), |
| 122 | ) |
| 123 | ) |
| 124 | return old; |
| 125 | const next = new Map(old); |
| 126 | next.delete(result.index); |
| 127 | next.set(result.index, result.rows); |
| 128 | if (next.size > 12) next.delete([...next.keys()].find((key) => key !== 0)!); |
| 129 | return next; |
| 130 | }); |
| 131 | } |
| 132 | }); |
| 133 | engine.addEventListener("error", () => { |
| 134 | copyPending.current?.reject(new Error(m(msg("The text viewer stopped.")))); |
| 135 | copyPending.current = null; |
| 136 | setError(m(msg("Could not load the text viewer. Close the file and try again."))); |
| 137 | }); |
| 138 | engine.postMessage( |
| 139 | { |
| 140 | type: "open", |
| 141 | src: props.src, |
| 142 | text: props.text, |
| 143 | sizeBytes: props.sizeBytes, |
| 144 | delimiter: props.delimiter, |
| 145 | }, |
| 146 | [], |
| 147 | ); |
| 148 | }; |
| 149 | const scheduleWorker = () => { |
| 150 | if (prefetched) requestAnimationFrame(() => requestAnimationFrame(startWorker)); |
| 151 | else startWorker(); |
| 152 | }; |
| 153 | // Only this bounded prefix is parsed on the main thread. Indexing the full |
| 154 | // file and fetching later pages remain in the worker. |
| 155 | if (props.sizeBytes === 0) { |
| 156 | startWorker(); |
| 157 | } else if (props.text !== undefined) { |
| 158 | paintFirstScreen( |
| 159 | props.text.slice(0, FIRST_SCREEN_BYTES), |
| 160 | props.text.length <= FIRST_SCREEN_BYTES, |
| 161 | ); |
| 162 | scheduleWorker(); |
| 163 | } else if (props.src) { |
| 164 | void fetch(props.src, { |
| 165 | headers: { Range: `bytes=0-${FIRST_SCREEN_BYTES - 1}` }, |
| 166 | cache: "no-store", |
| 167 | signal: controller.signal, |
| 168 | }) |
| 169 | .then(async (response) => { |
| 170 | if ( |
| 171 | !response.ok || |
| 172 | Number(response.headers.get("content-length")) > FIRST_SCREEN_BYTES || |
| 173 | response.status !== 206 |
| 174 | ) { |
| 175 | await response.body?.cancel(); |
| 176 | return; |
| 177 | } |
| 178 | const total = Number(response.headers.get("content-range")?.split("/")[1]); |
| 179 | paintFirstScreen(await response.text(), total <= FIRST_SCREEN_BYTES); |
| 180 | }) |
| 181 | .catch(() => { |
| 182 | // The worker reports authorization, network and format failures. |
| 183 | }) |
| 184 | .finally(scheduleWorker); |
| 185 | } else startWorker(); |
| 186 | return () => { |
| 187 | controller.abort(); |
| 188 | copyPending.current?.reject(new Error(m(msg("Preview closed.")))); |
| 189 | copyPending.current = null; |
| 190 | worker.current?.terminate(); |
| 191 | worker.current = null; |
| 192 | pending.current.clear(); |
| 193 | }; |
| 194 | }, [props.src, props.text, props.delimiter, props.sizeBytes]); |
| 195 | useImperativeHandle( |
| 196 | props.copyContents, |
| 197 | () => () => |
| 198 | new Promise<string>((resolve, reject) => { |
| 199 | if (!worker.current) { |
| 200 | reject(new Error(m(msg("The file is unavailable.")))); |
| 201 | return; |
| 202 | } |
| 203 | if (copyPending.current) { |
| 204 | reject(new Error(m(msg("Another copy is in progress.")))); |
| 205 | return; |
| 206 | } |
| 207 | copyPending.current = { resolve, reject }; |
| 208 | worker.current.postMessage({ type: "copy" }, []); |
| 209 | }), |
| 210 | [], |
| 211 | ); |
| 212 | if (error) |
| 213 | return ( |
| 214 | <FileSurfaceFailure message={error} {...(props.onRetry ? { onRetry: props.onRetry } : {})} /> |
| 215 | ); |
| 216 | if (!meta || (meta.count > 0 && !pages.has(0))) return <FileSurfaceLoading />; |
| 217 | const header = props.delimiter ? pages.get(0)?.[0] : undefined; |
| 218 | const rowCount = Math.max(0, meta.count - 1); |
| 219 | const columnCount = meta.count ? meta.columns : 0; |
| 220 | return ( |
| 221 | <div className="relative flex min-h-0 flex-1 flex-col"> |
| 222 | <div |
| 223 | 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" |
| 224 | role="status" |
| 225 | > |
| 226 | {props.delimiter |
| 227 | ? `${gt("{count, plural, one {{formatted} row} other {{formatted} rows}}", { |
| 228 | count: rowCount, |
| 229 | formatted: rowCount.toLocaleString(), |
| 230 | })} · ${gt("{count, plural, one {{formatted} column} other {{formatted} columns}}", { |
| 231 | count: columnCount, |
| 232 | formatted: columnCount.toLocaleString(), |
| 233 | })}` |
| 234 | : gt("{count, plural, one {{formatted} line} other {{formatted} lines}}", { |
| 235 | count: meta.count, |
| 236 | formatted: meta.count.toLocaleString(), |
| 237 | })} |
| 238 | {meta.complete && meta.sizeBytes !== undefined |
| 239 | ? ` · ${meta.sizeBytes === 0 ? gt("0 bytes") : formatAttachmentSize(meta.sizeBytes, messages)}` |
| 240 | : ` · ${gt("Indexing…")}`} |
| 241 | </div> |
| 242 | {!meta.complete ? ( |
| 243 | <div className="pointer-events-none absolute inset-x-0 bottom-0 z-20"> |
| 244 | <FileSurfaceNotice> |
| 245 | <T>Loading the rest of the file…</T> |
| 246 | </FileSurfaceNotice> |
| 247 | </div> |
| 248 | ) : null} |
| 249 | {meta.columns === 1024 ? ( |
| 250 | <FileSurfaceNotice> |
| 251 | <T>Showing the first 1,024 columns. Source and Save retain every column.</T> |
| 252 | </FileSurfaceNotice> |
| 253 | ) : null} |
| 254 | {meta.count > 0 ? ( |
| 255 | <VirtualTablePreview |
| 256 | name={props.name} |
| 257 | count={meta.count} |
| 258 | columns={meta.columns} |
| 259 | header={header} |
| 260 | source={!props.delimiter} |
| 261 | wrap={wordWrap} |
| 262 | revealLine={meta.complete ? (props.revealLine ?? null) : null} |
| 263 | revealRequestId={props.revealRequestId ?? 0} |
| 264 | getRows={(page) => pages.get(page)} |
| 265 | loadPage={(page) => { |
| 266 | if (pending.current.has(page)) return; |
| 267 | pending.current.add(page); |
| 268 | worker.current?.postMessage({ type: "page", index: page }); |
| 269 | }} |
| 270 | /> |
| 271 | ) : ( |
| 272 | <div className="flex flex-1 items-center justify-center p-6 text-xs text-muted-foreground"> |
| 273 | <T>This file is empty.</T> |
| 274 | </div> |
| 275 | )} |
| 276 | </div> |
| 277 | ); |
| 278 | } |