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

LargeTextViewer.tsx

403 lines16.0 KB

1import { msg, T, useGT, useMessages, plural, part } from "gt-react";
2import { useEffect, useImperativeHandle, useRef, useState, type RefObject } from "react";
3import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
4import { toastManager } from "~/components/ui/toast";
5import { m } from "~/i18n/messages";
6import { useFormattingLocale } from "~/i18n/I18nProvider";
7import { Spinner } from "~/components/ui/spinner";
8import { parseDelimitedPreview } from "@t3tools/shared/delimitedPreview";
9import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
10import { useClientSettings } from "~/hooks/useSettings";
11import { FileSurfaceFailure, FileSurfaceLoading, FileSurfaceNotice } from "./fileSurfaceChrome";
12import {
13 LARGE_TEXT_MAX_COLUMNS,
14 PREVIEW_PAGE_ROWS,
15 type TextPreviewResult,
16} from "./largeTextProtocol";
17import { previewFailureText } from "./previewFailureMessages";
18import VirtualTablePreview from "./VirtualTablePreview";
19​
20const FIRST_SCREEN_BYTES = 16 * 1024;
21const PREFIX_WAIT_MS = 1_000;
22​
23function firstScreen(text: string, delimiter: "," | "\t" | null, complete: boolean) {
24 if (!text || text.includes("\0")) return [];
25 const rows = delimiter
26 ? parseDelimitedPreview(text, delimiter, {
27 maxRows: PREVIEW_PAGE_ROWS * 2 + 1,
28 maxColumns: LARGE_TEXT_MAX_COLUMNS + 1,
29 maxCellLength: FIRST_SCREEN_BYTES,
30 inputComplete: complete,
31 }).rows
32 : text
33 .replace(/\r?\n$|\r$/, "")
34 .split(/\r\n|\n|\r/)
35 .slice(0, PREVIEW_PAGE_ROWS * 2 + 1)
36 .map((line) => [line]);
37 // A byte range can end inside a quoted record or a UTF-8 character.
38 if (!complete) rows.pop();
39 return rows.slice(0, PREVIEW_PAGE_ROWS * 2);
41​
42type Meta = Extract<TextPreviewResult, { type: "meta" }>;
43​
44function firstScreenState(text: string, delimiter: "," | "\t" | null, complete: boolean) {
45 const rows = firstScreen(text, delimiter, complete);
46 if (!rows.length) return null;
47 const widest = rows.reduce((max, row) => Math.max(max, row.length), 1);
48 return {
49 pages: new Map(
50 [0, PREVIEW_PAGE_ROWS]
51 .filter((start) => start < rows.length)
52 .map((start) => [start / PREVIEW_PAGE_ROWS, rows.slice(start, start + PREVIEW_PAGE_ROWS)]),
53 ),
54 meta: {
55 type: "meta",
56 count: rows.length,
57 columns: Math.min(LARGE_TEXT_MAX_COLUMNS, widest),
58 columnsTruncated: widest > LARGE_TEXT_MAX_COLUMNS,
59 complete: false,
60 } satisfies Meta as Meta,
61 };
63​
64// Reopening a recent file paints its first screen at once while the worker indexes it again.
65const recentFirstScreens = new Map<string, { text: string; complete: boolean }>();
66​
67function rememberFirstScreen(src: string, text: string, complete: boolean) {
68 recentFirstScreens.delete(src);
69 recentFirstScreens.set(src, { text, complete });
70 if (recentFirstScreens.size > 32)
71 recentFirstScreens.delete(recentFirstScreens.keys().next().value!);
73​
74export default function LargeTextViewer(props: {
75 readonly name: string;
76 readonly src?: string;
77 readonly text?: string;
78 readonly truncated?: boolean;
79 readonly sizeBytes?: number;
80 readonly onRetry?: () => void;
81 readonly copyContents?: RefObject<(() => Promise<string>) | null>;
82 readonly delimiter: "," | "\t" | null;
83 readonly revealLine?: number | null;
84 readonly revealRequestId?: number;
85 /** A preview's own wrap toggle; omitted follows the word wrap setting. */
86 readonly wordWrap?: boolean;
87}) {
88 const gt = useGT();
89 const locale = useFormattingLocale();
90 const countFormat = new Intl.NumberFormat(locale);
91 const messages = useMessages();
92 const [initial] = useState(() => {
93 const cached = props.src === undefined ? undefined : recentFirstScreens.get(props.src);
94 return cached ? firstScreenState(cached.text, props.delimiter, cached.complete) : null;
95 });
96 const [meta, setMeta] = useState<Meta | null>(initial?.meta ?? null);
97 const [pages, setPages] = useState(initial?.pages ?? new Map<number, string[][]>());
98 const [error, setError] = useState<string | null>(null);
99 const worker = useRef<Worker | null>(null);
100 const workerReady = useRef(false);
101 const clipboardSession = useRef<{ writing: boolean; staged?: string }>({ writing: false });
102 const copyPending = useRef<{
103 waitingForIndex: boolean;
104 resolve: (text: string) => void;
105 reject: (cause: Error) => void;
106 } | null>(null);
107 const pending = useRef(new Set<number>());
108 const defaultWordWrap = useClientSettings((settings) => settings.wordWrap);
109 const wordWrap = props.wordWrap ?? defaultWordWrap;
110 // 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.
111 useEffect(() => {
112 // oxlint-disable-next-line react/set-state-in-effect -- A replacement source must discard the previous worker's error and pages.
113 setError(null);
114 setMeta(null);
115 setPages(new Map());
116 const controller = new AbortController();
117 let indexed = false;
118 let prefetched = false;
119 const paintFirstScreen = (text: string, complete: boolean) => {
120 if (indexed || controller.signal.aborted) return;
121 const screen = firstScreenState(text, props.delimiter, complete);
122 if (!screen) return;
123 prefetched = true;
124 setPages(screen.pages);
125 setMeta(screen.meta);
126 };
127 let workerStarted = false;
128 let prefixTimer: ReturnType<typeof setTimeout> | undefined;
129 const startWorker = () => {
130 clearTimeout(prefixTimer);
131 if (workerStarted || controller.signal.aborted) return;
132 workerStarted = true;
133 const engine = new Worker(new URL("./largeText.worker.ts", import.meta.url), {
134 type: "module",
135 });
136 worker.current = engine;
137 engine.addEventListener("message", (event: MessageEvent<TextPreviewResult>) => {
138 if (controller.signal.aborted) return;
139 const result = event.data;
140 if (result.type === "copy") {
141 copyPending.current?.resolve(result.text);
142 copyPending.current = null;
143 } else if (result.type === "error") {
144 copyPending.current?.reject(new Error(previewFailureText(result)));
145 copyPending.current = null;
146 if (result.operation !== "copy") setError(previewFailureText(result));
147 } else if (result.type === "meta") {
148 indexed = true;
149 if (result.complete && !workerReady.current) {
150 workerReady.current = true;
151 if (copyPending.current?.waitingForIndex) engine.postMessage({ type: "copy" }, []);
152 }
153 if (prefetched) {
154 // Keeps the painted first screen until the worker's own pages replace it.
155 prefetched = false;
156 pending.current.clear();
157 for (const index of [0, 1]) {
158 if (index * PREVIEW_PAGE_ROWS >= result.count) break;
159 pending.current.add(index);
160 engine.postMessage({ type: "page", index }, []);
161 }
162 }
163 setMeta(result);
164 } else if (result.type === "page") {
165 pending.current.delete(result.index);
166 setPages((old) => {
167 const previous = old.get(result.index);
168 if (
169 previous?.length === result.rows.length &&
170 previous.every(
171 (row, index) =>
172 row.length === result.rows[index]!.length &&
173 row.every((cell, column) => cell === result.rows[index]![column]),
174 )
175 )
176 return old;
177 const next = new Map(old);
178 next.delete(result.index);
179 next.set(result.index, result.rows);
180 if (next.size > 12) next.delete([...next.keys()].find((key) => key !== 0)!);
181 return next;
182 });
183 }
184 });
185 engine.addEventListener("error", () => {
186 if (controller.signal.aborted) return;
187 copyPending.current?.reject(new Error(m(msg("The text viewer stopped."))));
188 copyPending.current = null;
189 setError(m(msg("Could not load the text viewer. Close the file and try again.")));
190 });
191 engine.postMessage(
192 {
193 type: "open",
194 src: props.src,
195 text: props.text,
196 truncated: props.truncated,
197 sizeBytes: props.sizeBytes,
198 delimiter: props.delimiter,
199 },
200 [],
201 );
202 };
203 const scheduleWorker = () => {
204 if (prefetched) requestAnimationFrame(() => requestAnimationFrame(startWorker));
205 else startWorker();
206 };
207 // Only this bounded prefix is parsed on the main thread. Indexing the full
208 // file and fetching later pages remain in the worker.
209 const cached = props.src === undefined ? undefined : recentFirstScreens.get(props.src);
210 if (props.sizeBytes === 0) {
211 startWorker();
212 } else if (cached) {
213 paintFirstScreen(cached.text, cached.complete);
214 scheduleWorker();
215 } else if (props.text !== undefined) {
216 paintFirstScreen(
217 props.text.slice(0, FIRST_SCREEN_BYTES),
218 !props.truncated && props.text.length <= FIRST_SCREEN_BYTES,
219 );
220 scheduleWorker();
221 } else if (props.src) {
222 const src = props.src;
223 // A stalled prefix must neither hold back the worker nor keep its connection busy.
224 const prefix = new AbortController();
225 controller.signal.addEventListener("abort", () => prefix.abort(), { once: true });
226 prefixTimer = setTimeout(() => {
227 prefix.abort();
228 startWorker();
229 }, PREFIX_WAIT_MS);
230 void fetch(src, {
231 headers: { Range: `bytes=0-${FIRST_SCREEN_BYTES - 1}` },
232 cache: "no-store",
233 signal: prefix.signal,
234 })
235 .then(async (response) => {
236 if (
237 !response.ok ||
238 Number(response.headers.get("content-length")) > FIRST_SCREEN_BYTES ||
239 response.status !== 206
240 ) {
241 await response.body?.cancel();
242 return;
243 }
244 const total = Number(response.headers.get("content-range")?.split("/")[1]);
245 const text = await response.text();
246 rememberFirstScreen(src, text, total <= FIRST_SCREEN_BYTES);
247 paintFirstScreen(text, total <= FIRST_SCREEN_BYTES);
248 })
249 .catch(() => {
250 // The worker reports authorization, network and format failures.
251 })
252 .finally(scheduleWorker);
253 } else startWorker();
254 return () => {
255 controller.abort();
256 clearTimeout(prefixTimer);
257 copyPending.current?.reject(new Error(m(msg("Preview closed."))));
258 copyPending.current = null;
259 worker.current?.terminate();
260 worker.current = null;
261 workerReady.current = false;
262 clipboardSession.current = { writing: false };
263 pending.current.clear();
264 };
265 }, [props.src, props.text, props.truncated, props.delimiter, props.sizeBytes]);
266 const readContents = (waitForIndex: boolean) =>
267 new Promise<string>((resolve, reject) => {
268 if (!worker.current && !waitForIndex) {
269 reject(new Error(m(msg("The file is unavailable."))));
270 return;
271 }
272 if (copyPending.current) {
273 reject(new Error(m(msg("Another copy is in progress."))));
274 return;
275 }
276 const waitingForIndex = waitForIndex && !workerReady.current;
277 copyPending.current = { resolve, reject, waitingForIndex };
278 if (!waitingForIndex) worker.current?.postMessage({ type: "copy" }, []);
279 });
280 useImperativeHandle(props.copyContents, () => () => readContents(false), [readContents]);
281 const copyAll = async (clipboard: DataTransfer) => {
282 const session = clipboardSession.current;
283 const available = props.text ?? session.staged;
284 if (available !== undefined) {
285 clipboard.setData("text/plain", available);
286 delete session.staged;
287 return;
288 }
289 if (session.writing || copyPending.current) {
290 toastManager.add({ type: "info", title: m(msg("Another copy is in progress.")) });
291 return;
292 }
293​
294 session.writing = true;
295 try {
296 const text = readContents(true);
297 if (navigator.clipboard?.write && typeof ClipboardItem !== "undefined") {
298 // Start the write within the copy gesture while the worker reads the full file.
299 const data = text.then((value) => new Blob([value], { type: "text/plain" }));
300 void data.catch(() => undefined);
301 try {
302 await navigator.clipboard.write([new ClipboardItem({ "text/plain": data })]);
303 session.writing = false;
304 return;
305 } catch {
306 // A fresh native copy gesture can write the text if this async write is rejected.
307 }
308 }
309 const staged = await text;
310 if (clipboardSession.current === session) {
311 session.staged = staged;
312 toastManager.add({ type: "info", title: gt`File ready to copy. Press Copy again.` });
313 }
314 } catch (cause) {
315 if (clipboardSession.current === session) {
316 toastManager.add({
317 type: "error",
318 title: gt`Could not copy file`,
319 description: thrownErrorMessage(cause, m) ?? gt`Try again.`,
320 });
321 }
322 }
323 session.writing = false;
324 };
325 if (error)
326 return (
327 <FileSurfaceFailure message={error} {...(props.onRetry ? { onRetry: props.onRetry } : {})} />
328 );
329 if (!meta || (meta.count > 0 && !pages.has(0))) return <FileSurfaceLoading />;
330 const header = props.delimiter ? pages.get(0)?.[0] : undefined;
331 const rowCount = Math.max(0, meta.count - 1);
332 const columnCount = meta.count ? meta.columns : 0;
333 return (
334 <div className="relative flex min-h-0 flex-1 flex-col">
335 <div
336 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"
337 role="status"
338 >
339 {/* Counts appear once indexing ends; the prefix count alone would understate the file. */}
340 {!meta.complete
341 ? null
342 : props.delimiter
343 ? `${gt`${plural(
344 { count: rowCount },
345 {
346 one: part`${{ formatted: countFormat.format(rowCount) }} row`,
347 other: part`${{ formatted: countFormat.format(rowCount) }} rows`,
348 },
349 )}`} · ${gt`${plural(
350 { count: columnCount },
351 {
352 one: part`${{ formatted: countFormat.format(columnCount) }} column`,
353 other: part`${{ formatted: countFormat.format(columnCount) }} columns`,
354 },
355 )}`}`
356 : gt`${plural(
357 { count: meta.count },
358 {
359 one: part`${{ formatted: countFormat.format(meta.count) }} line`,
360 other: part`${{ formatted: countFormat.format(meta.count) }} lines`,
361 },
362 )}`}
363 {meta.complete && meta.sizeBytes !== undefined
364 ? ` · ${meta.sizeBytes === 0 ? gt`0 bytes` : formatAttachmentSize(meta.sizeBytes, messages, locale)}`
365 : null}
366 </div>
367 {!meta.complete ? (
368 <div className="pointer-events-none absolute right-4 bottom-3 z-20">
369 <Spinner size="md" tone="muted" />
370 </div>
371 ) : null}
372 {meta.columnsTruncated ? (
373 <FileSurfaceNotice>
374 <T>Showing the first 1,024 columns. Source and Save retain every column.</T>
375 </FileSurfaceNotice>
376 ) : null}
377 {meta.count > 0 ? (
378 <VirtualTablePreview
379 name={props.name}
380 count={meta.count}
381 indexing={!meta.complete}
382 onCopyAll={copyAll}
383 columns={meta.columns}
384 header={header}
385 source={!props.delimiter}
386 wrap={wordWrap}
387 revealLine={meta.complete ? (props.revealLine ?? null) : null}
388 revealRequestId={props.revealRequestId ?? 0}
389 getRows={(page) => pages.get(page)}
390 loadPage={(page) => {
391 if (pending.current.has(page)) return;
392 pending.current.add(page);
393 worker.current?.postMessage({ type: "page", index: page });
394 }}
395 />
396 ) : (
397 <div className="flex flex-1 items-center justify-center p-6 text-xs text-muted-foreground">
398 <T>This file is empty.</T>
399 </div>
400 )}
401 </div>
402 );