Open History to see the last commit
1/* oxlint-disable react/no-array-index-key -- Read-only cells retain their database row and column positions. */
2import { decodeFilePreviewText, filePreviewKind } from "@t3tools/shared/filePreview";
3import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
4import { ChevronLeftIcon, ChevronRightIcon, FileIcon, FolderIcon } from "lucide-react";
5import { msg, T, useGT, useMessages } from "gt-react";
6import { lazy, Suspense, useEffect, useRef, useState } from "react";
7import { m } from "~/i18n/messages";
8
9import {
10 Select,
11 SelectTrigger,
12 SelectValue,
13 SelectPopup,
14 SelectItem,
15} from "~/components/ui/select";
16
17import {
18 FileSurfaceAction,
19 FileSurfaceFailure,
20 FileSurfaceLoading,
21 FileSurfaceNotice,
22} from "./fileSurfaceChrome";
23import {
24 SQLITE_PAGE_SIZE,
25 type BinaryWorkerRequest,
26 type BinaryWorkerResult,
27} from "./binaryPreviewProtocol";
28import { archiveImageUrl } from "./archiveImageUrl";
29import { PreviewImage } from "./PreviewImage";
30import { readBinaryPreview } from "./readBinaryPreview";
31import { previewErrorText, previewFailureText } from "./previewFailureMessages";
32
33const SourcePreview = lazy(() => import("./ReadOnlySourcePreview"));
34type Archive = Extract<BinaryWorkerResult, { type: "archive" }>;
35type Database = Extract<BinaryWorkerResult, { type: "sqlite" }>;
36type Rows = Extract<BinaryWorkerResult, { type: "rows" }>;
37
38const rowsLabel = (count: number, gt: ReturnType<typeof useGT>) =>
39 gt("{count, plural, one {{formatted} row} other {{formatted} rows}}", {
40 count,
41 formatted: count.toLocaleString(),
42 });
43const columnsLabel = (count: number, gt: ReturnType<typeof useGT>) =>
44 gt("{count, plural, one {{formatted} column} other {{formatted} columns}}", {
45 count,
46 formatted: count.toLocaleString(),
47 });
48const entriesLabel = (count: number, gt: ReturnType<typeof useGT>) =>
49 gt("{count, plural, one {{formatted} entry} other {{formatted} entries}}", {
50 count,
51 formatted: count.toLocaleString(),
52 });
53
54function ArchiveFile(props: { readonly path: string; readonly bytes: Uint8Array<ArrayBuffer> }) {
55 const gt = useGT();
56 const [url, setUrl] = useState<string | null>(null);
57 const kind = filePreviewKind({ name: props.path });
58 const text = (() => {
59 if (!["text", "markdown", "html", "mermaid"].includes(kind)) return null;
60 try {
61 return decodeFilePreviewText(props.bytes);
62 } catch {
63 return null;
64 }
65 })();
66 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Create an object URL for the extracted image and revoke it when the entry changes or unmounts.
67 useEffect(() => {
68 if (kind !== "image") return;
69 const image = archiveImageUrl(props.path, props.bytes);
70 // oxlint-disable-next-line react/set-state-in-effect -- Publish a Blob URL only after registering its cleanup.
71 setUrl(image.url);
72 return image.revoke;
73 }, [props.bytes, props.path, kind]);
74 if (kind === "image")
75 return url ? <PreviewImage key={url} src={url} name={props.path} /> : <FileSurfaceLoading />;
76 if (!text)
77 return (
78 <FileSurfaceFailure
79 message={gt("Only UTF-8 text and images can be opened inside an archive.")}
80 />
81 );
82 return (
83 <>
84 {text.truncated ? (
85 <FileSurfaceNotice>
86 <T>Preview limited to the first 1 MB.</T>
87 </FileSurfaceNotice>
88 ) : null}
89 <Suspense fallback={<FileSurfaceLoading />}>
90 <SourcePreview name={props.path} text={text.text} />
91 </Suspense>
92 </>
93 );
94}
95
96export default function BinaryViewer(props: {
97 readonly src: string;
98 readonly name: string;
99 readonly kind: "archive" | "sqlite";
100 readonly onRetry?: () => void;
101}) {
102 const gt = useGT();
103 const messages = useMessages();
104 const [sizeBytes, setSizeBytes] = useState<number | null>(null);
105 const [archive, setArchive] = useState<Archive | null>(null);
106 const [database, setDatabase] = useState<Database | null>(null);
107 const [rows, setRows] = useState<Rows | null>(null);
108 const [entry, setEntry] = useState<Extract<BinaryWorkerResult, { type: "entry" }> | null>(null);
109 const [folder, setFolder] = useState("");
110 const [selectedPath, setSelectedPath] = useState<string | null>(null);
111 const [selectedTable, setSelectedTable] = useState("");
112 const [page, setPage] = useState(0);
113 const [busy, setBusy] = useState(true);
114 const [error, setError] = useState<string | null>(null);
115 const workerRef = useRef<Worker | null>(null);
116 const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
117 const send = (request: BinaryWorkerRequest) => {
118 setBusy(true);
119 setError(null);
120 if (timerRef.current) clearTimeout(timerRef.current);
121 timerRef.current = setTimeout(() => {
122 setError(m(msg("This file took too long to preview. Close it and try again.")));
123 setBusy(false);
124 workerRef.current?.terminate();
125 workerRef.current = null;
126 }, 15_000);
127 workerRef.current?.postMessage(request);
128 };
129 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Own the binary fetch, archive or database worker, message subscription, and request timeout for this file.
130 useEffect(() => {
131 const controller = new AbortController();
132 const worker = new Worker(new URL("./binaryPreview.worker.ts", import.meta.url), {
133 type: "module",
134 });
135 workerRef.current = worker;
136 const fail = (message: string) => {
137 if (controller.signal.aborted) return;
138 setError(message);
139 setBusy(false);
140 controller.abort();
141 worker.terminate();
142 workerRef.current = null;
143 if (timerRef.current) clearTimeout(timerRef.current);
144 };
145 timerRef.current = setTimeout(
146 () => fail(m(msg("This file took too long to preview. Close it and try again."))),
147 30_000,
148 );
149 worker.addEventListener("error", () =>
150 fail(m(msg("Could not load the file viewer. Close it and try again."))),
151 );
152 worker.addEventListener("message", (event: MessageEvent<BinaryWorkerResult>) => {
153 if (controller.signal.aborted) return;
154 if (timerRef.current) clearTimeout(timerRef.current);
155 const result = event.data;
156 setBusy(false);
157 if (result.type === "error") setError(previewFailureText(result));
158 else if (result.type === "archive") setArchive(result);
159 else if (result.type === "entry") setEntry(result);
160 else if (result.type === "rows") setRows(result);
161 else {
162 setDatabase(result);
163 const table = result.tables[0];
164 if (table) {
165 setSelectedTable(table.name);
166 send({ type: "rows", table: table.name, page: 0 });
167 }
168 }
169 });
170 void readBinaryPreview(props.src, controller.signal)
171 .then((bytes) => {
172 if (!controller.signal.aborted) {
173 setSizeBytes(bytes.byteLength);
174 worker.postMessage({ type: "open", name: props.name, kind: props.kind, bytes }, [bytes]);
175 }
176 })
177 .catch((cause: unknown) =>
178 fail(previewErrorText(cause, m(msg("Could not read this file.")))),
179 );
180 return () => {
181 controller.abort();
182 worker.terminate();
183 workerRef.current = null;
184 if (timerRef.current) clearTimeout(timerRef.current);
185 };
186 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- One worker owns this keyed file and its message stream.
187 }, [props.src, props.kind, props.name]);
188 const table = database?.tables.find((item) => item.name === selectedTable);
189 const selectPage = (next: number, name = selectedTable) => {
190 setSelectedTable(name);
191 setPage(next);
192 setRows(null);
193 send({ type: "rows", table: name, page: next });
194 };
195 const children = new Map<
196 string,
197 { path: string; entryPath: string; directory: boolean; size: number; modified: string | null }
198 >();
199 for (const item of archive?.entries ?? []) {
200 const name = item.path.replace(/^\/+|\/+$/g, "").replace(/\/{2,}/g, "/");
201 if (!name.startsWith(folder)) continue;
202 const rest = name.slice(folder.length);
203 if (!rest) continue;
204 const slash = rest.indexOf("/");
205 const path = slash < 0 ? name : `${folder}${rest.slice(0, slash)}`;
206 const directory = slash >= 0 || item.directory;
207 // Files stay keyed by their raw name so `/a.txt` and `a.txt` remain two openable rows.
208 const key = directory ? `d:${path}` : `f:${item.path}`;
209 const previous = children.get(key);
210 if (previous && directory) previous.size += item.size;
211 else
212 children.set(key, {
213 path,
214 entryPath: item.path,
215 directory,
216 size: item.size,
217 modified: item.modified,
218 });
219 }
220 return (
221 <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
222 {archive ? (
223 <div className="flex h-10 shrink-0 items-center gap-2 border-b border-border/60 px-3 text-xs">
224 <FileSurfaceAction
225 label={selectedPath ? gt("Back to archive") : gt("Parent folder")}
226 disabled={!selectedPath && !folder}
227 onPress={() => {
228 setError(null);
229 setEntry(null);
230 if (selectedPath) setSelectedPath(null);
231 else setFolder(folder.replace(/(?:[^/]+)?\/$/, ""));
232 }}
233 >
234 <ChevronLeftIcon className="size-3.5" />
235 </FileSurfaceAction>
236 <span className="min-w-0 flex-1 truncate">
237 {selectedPath ?? (folder || gt("Archive contents"))}
238 </span>
239 <span className="shrink-0 text-muted-foreground">
240 {entriesLabel(archive.entries.length, gt)}
241 {sizeBytes !== null ? ` · ${formatAttachmentSize(sizeBytes, messages)}` : ""}
242 </span>
243 </div>
244 ) : null}
245 {database && table ? (
246 <>
247 <div className="flex min-h-10 shrink-0 flex-wrap items-center gap-2 border-b border-border/60 px-3 py-1 text-xs">
248 <div className="min-w-32 flex-1">
249 <Select
250 value={selectedTable}
251 onValueChange={(value) => {
252 if (!busy && value !== null) selectPage(0, value);
253 }}
254 >
255 <SelectTrigger
256 aria-label={gt("Table", { $context: "noun, database table picker" })}
257 aria-disabled={busy}
258 aria-busy={busy}
259 size="xs"
260 >
261 <SelectValue>
262 {table.name} ({rowsLabel(table.count, gt)})
263 </SelectValue>
264 </SelectTrigger>
265 <SelectPopup>
266 {database.tables.map((item) => (
267 <SelectItem key={item.name} value={item.name}>
268 {item.name} ({rowsLabel(item.count, gt)})
269 </SelectItem>
270 ))}
271 </SelectPopup>
272 </Select>
273 </div>
274 <FileSurfaceAction
275 label={gt("Previous rows")}
276 disabled={busy || page === 0}
277 onPress={() => selectPage(page - 1)}
278 >
279 <ChevronLeftIcon className="size-3.5" />
280 </FileSurfaceAction>
281 <span className="shrink-0 tabular-nums" aria-live="polite">
282 {table.count === 0
283 ? gt("0 rows")
284 : gt("{start}–{end} of {total}", {
285 start: String(page * SQLITE_PAGE_SIZE + 1),
286 end: String(Math.min(table.count, (page + 1) * SQLITE_PAGE_SIZE)),
287 total: table.count.toLocaleString(),
288 })}
289 </span>
290 <FileSurfaceAction
291 label={gt("Next rows")}
292 disabled={busy || (page + 1) * SQLITE_PAGE_SIZE >= table.count}
293 onPress={() => selectPage(page + 1)}
294 >
295 <ChevronRightIcon className="size-3.5" />
296 </FileSurfaceAction>
297 </div>
298 <div
299 className="border-b border-border/60 px-3 py-2 text-xs text-muted-foreground tabular-nums"
300 role="status"
301 >
302 {rowsLabel(table.count, gt)} ·{" "}
303 {rows ? columnsLabel(rows.columns.length, gt) : gt("… columns")}
304 {sizeBytes !== null ? ` · ${formatAttachmentSize(sizeBytes, messages)}` : ""}
305 </div>
306 <FileSurfaceNotice>
307 <T>
308 Read-only. Up to 50 columns and 1,024 characters per cell. Blob contents are omitted.
309 </T>
310 </FileSurfaceNotice>
311 </>
312 ) : null}
313 {error ? (
314 <FileSurfaceFailure
315 message={error}
316 {...(props.onRetry ? { onRetry: props.onRetry } : {})}
317 />
318 ) : busy ? (
319 <FileSurfaceLoading />
320 ) : selectedPath ? (
321 entry ? (
322 <ArchiveFile key={entry.path} path={entry.path} bytes={entry.bytes} />
323 ) : null
324 ) : archive ? (
325 <div className="scrollbar-gutter-both min-h-0 flex-1 overflow-auto">
326 <table
327 aria-label={gt("Archive entries")}
328 className="w-full border-separate border-spacing-0 text-xs"
329 >
330 <thead className="sticky top-0 bg-background text-muted-foreground">
331 <tr>
332 <th scope="col" className="px-3 py-2 text-left font-normal">
333 <T $context="column header, file name">Name</T>
334 </th>
335 <th scope="col" className="px-3 py-2 text-right font-normal">
336 <T $context="column header, file size">Size</T>
337 </th>
338 <th scope="col" className="px-3 py-2 text-right font-normal">
339 <T $context="column header, last modified date">Modified</T>
340 </th>
341 </tr>
342 </thead>
343 <tbody>
344 {[...children.values()]
345 .sort(
346 (a, b) =>
347 Number(b.directory) - Number(a.directory) || a.path.localeCompare(b.path),
348 )
349 .map((item) => (
350 <tr
351 key={item.directory ? `d:${item.path}` : `f:${item.entryPath}`}
352 className="hover:bg-muted/40"
353 >
354 <td className="max-w-0 border-b border-border/60">
355 <button
356 type="button"
357 className="flex w-full items-center gap-2 px-3 py-2 text-left hover:text-primary focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
358 onClick={() => {
359 if (item.directory) setFolder(`${item.path}/`);
360 else {
361 setSelectedPath(item.path);
362 setEntry(null);
363 send({ type: "entry", path: item.entryPath });
364 }
365 }}
366 >
367 {item.directory ? (
368 <FolderIcon className="size-4 shrink-0 text-muted-foreground" />
369 ) : (
370 <FileIcon className="size-4 shrink-0 text-muted-foreground" />
371 )}
372 <span className="truncate">{item.path.slice(folder.length)}</span>
373 </button>
374 </td>
375 <td className="w-20 border-b border-border/60 px-3 py-2 text-right whitespace-nowrap text-muted-foreground tabular-nums">
376 {formatAttachmentSize(item.size, messages)}
377 </td>
378 <td className="w-28 border-b border-border/60 px-3 py-2 text-right whitespace-nowrap text-muted-foreground">
379 {item.modified ? new Date(item.modified).toLocaleDateString() : "-"}
380 </td>
381 </tr>
382 ))}
383 </tbody>
384 </table>
385 {children.size === 0 ? (
386 <p className="p-6 text-xs text-muted-foreground">
387 <T>This folder is empty.</T>
388 </p>
389 ) : null}
390 </div>
391 ) : rows ? (
392 <div className="scrollbar-gutter-both min-h-0 flex-1 overflow-auto">
393 <table
394 aria-label={`${props.name}: ${rows.table}`}
395 className="min-w-full border-separate border-spacing-0 text-xs"
396 >
397 <thead className="sticky top-0 bg-background">
398 <tr>
399 {rows.columns.map((name) => (
400 <th
401 key={name}
402 scope="col"
403 className="border-r border-b border-border/60 px-3 py-2 text-left font-medium whitespace-nowrap"
404 >
405 {name}
406 </th>
407 ))}
408 </tr>
409 </thead>
410 <tbody>
411 {rows.rows.map((row, index) => (
412 <tr key={index} className="even:bg-muted/30">
413 {row.map((cell, column) => (
414 <td
415 key={column}
416 className="max-w-80 min-w-32 border-r border-b border-border/60 px-3 py-1.5 align-top whitespace-pre-wrap break-words tabular-nums"
417 >
418 {cell}
419 </td>
420 ))}
421 </tr>
422 ))}
423 </tbody>
424 </table>
425 {rows.rows.length === 0 ? (
426 <p className="p-6 text-xs text-muted-foreground">
427 <T>This table is empty.</T>
428 </p>
429 ) : null}
430 </div>
431 ) : (
432 <p className="p-6 text-xs text-muted-foreground">
433 <T>This database has no readable tables.</T>
434 </p>
435 )}
436 </div>
437 );
438}