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

LargeTextViewer.tsx

260 lines9.8 KB

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