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