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

LargeTextViewer.tsx

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