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

AttachmentFilePreview.tsx

579 lines21.4 KB

1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import { filePreviewDelimiter } from "@t3tools/shared/delimitedPreview";
3import type { AssetResource, EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
4import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
5import { readFilePreviewResponse } from "@t3tools/client-runtime/file-preview";
6import { settlePromise } from "@t3tools/client-runtime/state/runtime";
7import * as AsyncResult from "effect/reactivity/AsyncResult";
8import * as Cause from "effect/Cause";
9import {
10 filePreviewKind,
11 officePreviewKind,
12 FILE_TEXT_PREVIEW_MAX_BYTES,
13} from "@t3tools/shared/filePreview";
14import {
15 ChevronRightIcon,
16 DownloadIcon,
17 FolderOpenIcon,
18 Trash2Icon,
19 WrapTextIcon,
20 XIcon,
21 CheckIcon,
22 Code2Icon,
23 CopyIcon,
24 EyeIcon,
25 Table2Icon,
26} from "lucide-react";
27import { msg, T, useGT, useMessages, Var } from "gt-react";
28import { lazy, Suspense, useEffect, useRef, useState } from "react";
29import { createPortal } from "react-dom";
30import { m, type MessageResolver } from "~/i18n/messages";
31import { useFormattingLocale } from "~/i18n/I18nProvider";
32​
33import { useAssetUrlRefresh } from "~/assets/assetUrls";
34import ChatMarkdown from "~/components/ChatMarkdown";
35import { maskMarkdownFrontmatter } from "@t3tools/shared/markdownFrontmatter";
36import { Button } from "~/components/ui/button";
37import { ScrollArea } from "~/components/ui/scroll-area";
38import { toastManager } from "~/components/ui/toast";
39import { namedClipboardTarget, useCopyToClipboard } from "~/hooks/useCopyToClipboard";
40import { useClientSettings } from "~/hooks/useSettings";
41import { useFileContextMenu } from "~/fileContextMenu";
42import { cn } from "~/lib/utils";
43​
44import { BinaryFilePreview } from "./BinaryFilePreview";
45import { PreviewImage } from "./PreviewImage";
46import { AudioPreview, browserCanPlayAudio } from "./AudioPreview";
47import { BrowserDocumentFrame } from "./BrowserDocumentFrame";
48import { DelimitedTablePreview } from "./DelimitedTablePreview";
49import {
50 FILE_SURFACE_SUBHEADER_CLASS,
51 FileSurfaceAction,
52 FileSurfaceFailure,
53 FileSurfaceLoading,
54 FileSurfaceNotice,
55 selectRenderedContentOnSelectAll,
56} from "./fileSurfaceChrome";
57​
58const LargeTextViewer = lazy(() => import("./LargeTextViewer"));
59​
60const OfficeFilePreview = lazy(() =>
61 import("./OfficeFilePreview").then((module) => ({ default: module.OfficeFilePreview })),
62);
63​
64const FontFilePreview = lazy(() =>
65 import("./FontFilePreview").then((module) => ({ default: module.FontFilePreview })),
66);
67​
68const MermaidFilePreview = lazy(() =>
69 import("./MermaidFilePreview").then((module) => ({ default: module.MermaidFilePreview })),
70);
71​
72const SourcePreview = lazy(() => import("./ReadOnlySourcePreview"));
73​
74const STALE_URL_MS = 5 * 60_000;
75​
76const blobKeys = new WeakMap<Blob, string>();
77let nextBlobKey = 0;
78​
79function blobKey(blob: Blob) {
80 const key = blobKeys.get(blob) ?? `blob:${nextBlobKey++}`;
81 blobKeys.set(blob, key);
82 return key;
84​
85export function ReadOnlySourcePreview(props: { name: string; text: string; wordWrap?: boolean }) {
86 return (
87 <Suspense fallback={<FileSurfaceLoading className="p-4" />}>
88 <SourcePreview {...props} />
89 </Suspense>
90 );
92​
93function renderedToggleLabel(
94 mode: "markdown" | "mermaid" | "html" | "table",
95 rendered: boolean,
96 resolve: MessageResolver,
97): string {
98 if (mode === "mermaid")
99 return rendered ? resolve(msg("Show Mermaid source")) : resolve(msg("Show rendered diagram"));
100 if (mode === "markdown")
101 return rendered ? resolve(msg("Show markdown source")) : resolve(msg("Show rendered markdown"));
102 if (mode === "table") return rendered ? resolve(msg("Show source")) : resolve(msg("Show table"));
103 return rendered ? resolve(msg("Show HTML source")) : resolve(msg("Show rendered page"));
105​
106export function AttachmentFilePreview(props: {
107 name: string;
108 mimeType: string;
109 sizeBytes: number;
110 file?: Blob | null;
111 asset?:
112 | { environmentId: EnvironmentId; attachmentId: string }
113 | {
114 environmentId: EnvironmentId;
115 resource: Extract<AssetResource, { _tag: "media-file" | "draft-workspace-file" }>;
116 };
117 htmlRender?: boolean;
118 threadRef?: ScopedThreadRef;
119 origin?: string;
120 onRemove?: () => void;
121 onClose?: () => void;
122 /**
123 * Set when a host header already names the file: the preview drops its own breadcrumb row and
124 * renders its actions into this element. `null` while the host's slot is mounting.
125 */
126 actionsTarget?: HTMLElement | null | undefined;
127}) {
128 const embedded = props.actionsTarget !== undefined;
129 const kind = filePreviewKind(props);
130 const officeKind = officePreviewKind(props);
131 const delimiter = filePreviewDelimiter(props);
132 const renderedMode =
133 kind === "mermaid"
134 ? "mermaid"
135 : kind === "markdown"
136 ? "markdown"
137 : kind === "html"
138 ? "html"
139 : delimiter
140 ? "table"
141 : null;
142 const attachmentId =
143 props.asset && "attachmentId" in props.asset ? props.asset.attachmentId : undefined;
144 const gt = useGT();
145 const locale = useFormattingLocale();
146 const sizeFormat = new Intl.NumberFormat(locale);
147 const messages = useMessages();
148 const fileContextMenu = useFileContextMenu(props.asset?.environmentId ?? null);
149 // Files read from the host can be shown in its file manager when that host is this machine.
150 const hostPath = props.asset && "resource" in props.asset ? props.asset.resource.path : undefined;
151 const revealLabel = hostPath ? fileContextMenu.capabilities.revealLabel : undefined;
152 const reveal = () => {
153 if (!hostPath || !props.asset) return;
154 // The resolver needs a root to accept an absolute path, so split off the parent folder.
155 // A backslash separates folders only in Windows paths; on POSIX it is part of a name.
156 const windows = /^(?:[a-zA-Z]:[\\/]|\\\\)/.test(hostPath);
157 const separator = windows
158 ? Math.max(hostPath.lastIndexOf("/"), hostPath.lastIndexOf("\\"))
159 : hostPath.lastIndexOf("/");
160 void fileContextMenu.activate("reveal-in-folder", {
161 environmentId: props.asset.environmentId,
162 filePath: hostPath.slice(separator + 1),
163 workspaceRoot: hostPath.slice(0, separator) || hostPath.slice(0, separator + 1),
164 });
165 };
166 const { copyToClipboard, isCopied } = useCopyToClipboard({
167 target: namedClipboardTarget(props.name),
168 });
169 // useAssetUrlRefresh keys its callback on these objects, so they must stay cached. Parents
170 // rebuild `asset` on every render, so the attachment resource derives only from its fields.
171 const assetResource = props.asset && "resource" in props.asset ? props.asset.resource : null;
172 const attachmentResource = attachmentId
173 ? {
174 _tag: "attachment" as const,
175 attachmentId,
176 fileName: props.name,
177 mimeType: props.mimeType,
178 disposition: "inline" as const,
179 }
180 : null;
181 const resource = assetResource ?? attachmentResource;
182 const downloadResource = resource
183 ? resource._tag === "draft-workspace-file"
184 ? resource
185 : { ...resource, disposition: "attachment" as const }
186 : null;
187 const refresh = useAssetUrlRefresh(
188 props.file ? null : (props.asset?.environmentId ?? null),
189 props.file ? null : resource,
190 );
191 const prepareDownload = useAssetUrlRefresh(props.asset?.environmentId ?? null, downloadResource);
192 const [saving, setSaving] = useState(false);
193 const [localUrl, setLocalUrl] = useState<string | null>(null);
194 const [remoteUrl, setRemoteUrl] = useState<string | null>(null);
195 const [rendered, setRendered] = useState(true);
196 const [revision, setRevision] = useState(0);
197 const [content, setContent] = useState<{ text: string; truncated: boolean } | null>(null);
198 const [error, setError] = useState<string | null>(null);
199 const [contentError, setContentError] = useState<string | null>(null);
200 const copyContents = useRef<(() => Promise<string>) | null>(null);
201 const authorizedAt = useRef(0);
202 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- creates an object URL for the local file and revokes it on cleanup
203 useEffect(() => {
204 if (!props.file) return;
205 const url = URL.createObjectURL(props.file);
206 // oxlint-disable-next-line react/set-state-in-effect -- Publish an object URL only after its cleanup is registered for this Blob.
207 setLocalUrl(url);
208 return () => URL.revokeObjectURL(url);
209 }, [props.file]);
210 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- authorizes a remote attachment URL from the server and ignores the result after cleanup
211 useEffect(() => {
212 if (props.file) return;
213 let cancelled = false;
214 // oxlint-disable-next-line react/set-state-in-effect -- A new preview request clears its previous URL and error.
215 setRemoteUrl(null);
216 setError(null);
217 void refresh()
218 .then((url) => {
219 if (cancelled) return;
220 if (!url) throw new Error(m(msg("Reconnect to the environment and try again.")));
221 authorizedAt.current = Date.now();
222 setRemoteUrl(url);
223 })
224 .catch((cause: unknown) => {
225 if (!cancelled)
226 setError(thrownErrorMessage(cause, m) ?? m(msg("The attachment is unavailable.")));
227 });
228 return () => {
229 cancelled = true;
230 };
231 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reauthorize the remote file.
232 }, [props.file, refresh, revision]);
233 const url = props.file ? localUrl : remoteUrl;
234 const streamsText =
235 kind === "text" &&
236 (props.sizeBytes > FILE_TEXT_PREVIEW_MAX_BYTES ||
237 (props.sizeBytes === 0 && (!resource || resource._tag === "attachment")));
238 const needsText =
239 kind === "text" || kind === "markdown" || kind === "mermaid" || (kind === "html" && !rendered);
240 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- fetches the file's text from its URL or Blob stream and aborts the request on cleanup
241 useEffect(() => {
242 if (!needsText || streamsText || !url) return;
243 const controller = new AbortController();
244 // oxlint-disable-next-line react/set-state-in-effect -- A new external resource must clear the previous response before loading.
245 setContent(null);
246 setContentError(null);
247 const file = props.file;
248 void (async () => {
249 if (!file && Date.now() - authorizedAt.current > STALE_URL_MS) {
250 const target = await refresh();
251 if (controller.signal.aborted) return;
252 if (!target) throw new Error(m(msg("Reconnect to the environment and try again.")));
253 authorizedAt.current = Date.now();
254 if (target !== url) {
255 setRemoteUrl(target);
256 return;
257 }
258 }
259 const response = file
260 ? { ok: true, body: file.stream() }
261 : await fetch(url, {
262 signal: controller.signal,
263 ...(props.sizeBytes > 0
264 ? { headers: { Range: `bytes=0-${FILE_TEXT_PREVIEW_MAX_BYTES}` } }
265 : {}),
266 cache: revision === 0 ? "default" : "reload",
267 });
268 const result = await readFilePreviewResponse(response, controller.signal);
269 if (!controller.signal.aborted) setContent(result);
270 })().catch((cause: unknown) => {
271 if (!controller.signal.aborted)
272 setContentError(thrownErrorMessage(cause, m) ?? m(msg("Could not load this file.")));
273 });
274 return () => controller.abort();
275 }, [url, needsText, streamsText, revision, props.sizeBytes, props.file, refresh]);
276 const failure = error ?? (needsText ? contentError : null);
277 const defaultWordWrap = useClientSettings((settings) => settings.wordWrap);
278 const [wordWrapOverride, setWordWrapOverride] = useState<boolean | null>(null);
279 const wordWrap = wordWrapOverride ?? defaultWordWrap;
280 const showsRawText =
281 failure === null &&
282 needsText &&
283 (content !== null || streamsText) &&
284 !(delimiter && rendered) &&
285 !((kind === "markdown" || kind === "mermaid") && rendered);
286​
287 const save = () => {
288 setSaving(true);
289 void settlePromise(async () => {
290 let file = props.file;
291 if (!file) {
292 const target = await prepareDownload();
293 if (!target) throw new Error(gt`Reconnect to the environment and try again.`);
294 const response = await fetch(target);
295 if (!response.ok) throw new Error(gt`The file could not be loaded. Try again.`);
296 file = await response.blob();
297 }
298 // Blob downloads keep desktop's custom app scheme from navigating to an external browser.
299 const downloadUrl = URL.createObjectURL(file);
300 // Scheduled before the click so the URL is revoked even if the click throws.
301 setTimeout(() => URL.revokeObjectURL(downloadUrl), 30_000);
302 const anchor = document.createElement("a");
303 anchor.href = downloadUrl;
304 anchor.download = props.name;
305 anchor.click();
306 }).then((result) => {
307 if (!AsyncResult.isSuccess(result)) {
308 const cause = Cause.squash(result.cause);
309 toastManager.add({
310 type: "error",
311 title: gt`Could not save file`,
312 description: thrownErrorMessage(cause, m) ?? gt`Please try again.`,
313 });
314 }
315 setSaving(false);
316 });
317 };
318​
319 const basename = props.name.split(/[\\/]/).at(-1) ?? "";
320 const dotIndex = basename.lastIndexOf(".");
321 const extension =
322 dotIndex > 0 && dotIndex < basename.length - 1 ? basename.slice(dotIndex + 1) : null;
323​
324 const body = failure ? (
325 <FileSurfaceFailure
326 message={failure}
327 onRetry={() => {
328 setError(null);
329 setRevision((value) => value + 1);
330 }}
331 />
332 ) : streamsText && url ? (
333 <Suspense fallback={<FileSurfaceLoading />}>
334 <LargeTextViewer
335 key={`${url}:${rendered}:${revision}`}
336 name={props.name}
337 src={url}
338 sizeBytes={props.sizeBytes}
339 onRetry={() => setRevision((value) => value + 1)}
340 delimiter={rendered ? delimiter : null}
341 copyContents={copyContents}
342 wordWrap={wordWrap}
343 />
344 </Suspense>
345 ) : !url || (needsText && !content) ? (
346 <FileSurfaceLoading />
347 ) : needsText && content ? (
348 delimiter && rendered ? (
349 <DelimitedTablePreview
350 name={props.name}
351 text={content.text}
352 truncated={content.truncated}
353 delimiter={delimiter}
354 />
355 ) : kind === "mermaid" && rendered ? (
356 <Suspense fallback={<FileSurfaceLoading />}>
357 <MermaidFilePreview text={content.text} />
358 </Suspense>
359 ) : kind === "markdown" && rendered ? (
360 <ScrollArea className="min-h-0 flex-1" onKeyDown={selectRenderedContentOnSelectAll}>
361 <ChatMarkdown
362 text={maskMarkdownFrontmatter(content.text)}
363 cwd={undefined}
364 className="mx-auto max-w-4xl px-6 py-5"
365 />
366 </ScrollArea>
367 ) : (
368 <ReadOnlySourcePreview name={props.name} text={content.text} wordWrap={wordWrap} />
369 )
370 ) : kind === "archive" || kind === "sqlite" ? (
371 <BinaryFilePreview
372 key={revision}
373 src={url}
374 name={props.name}
375 kind={kind}
376 onRetry={() => setRevision((value) => value + 1)}
377 />
378 ) : kind === "font" ? (
379 <Suspense fallback={<FileSurfaceLoading />}>
380 <FontFilePreview src={url} name={props.name} />
381 </Suspense>
382 ) : officeKind ? (
383 <Suspense fallback={<FileSurfaceLoading />}>
384 <OfficeFilePreview
385 src={url}
386 name={props.name}
387 kind={officeKind}
388 sizeBytes={props.sizeBytes}
389 />
390 </Suspense>
391 ) : kind === "pdf" || kind === "html" ? (
392 <BrowserDocumentFrame
393 src={url}
394 title={props.name}
395 pdf={kind === "pdf"}
396 htmlRender={props.htmlRender === true}
397 threadRef={props.threadRef}
398 // Each mount signs or creates a new URL, so the URL cannot identify the file across visits.
399 // A draft keeps its Blob key after upload, so finishing the upload does not reload the PDF.
400 documentKey={
401 kind !== "pdf"
402 ? undefined
403 : props.file
404 ? blobKey(props.file)
405 : props.asset && "attachmentId" in props.asset
406 ? `${props.asset.environmentId}:${props.asset.attachmentId}`
407 : undefined
408 }
409 />
410 ) : kind === "audio" && browserCanPlayAudio(props) ? (
411 <AudioPreview src={url} name={props.name} onError={() => setError(gt`Unable to load audio.`)} />
412 ) : kind === "video" ? (
413 <div className="flex min-h-0 flex-1 items-center justify-center bg-black">
414 <video
415 controls
416 playsInline
417 src={url}
418 aria-label={props.name}
419 className="max-h-full max-w-full"
420 onError={() => setError(gt`Unable to load video.`)}
421 />
422 </div>
423 ) : kind === "image" ? (
424 <PreviewImage
425 key={url}
426 src={url}
427 name={props.name}
428 mimeType={props.mimeType}
429 onError={() => setError(gt`Unable to load image.`)}
430 />
431 ) : (
432 <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-1 px-6 text-center">
433 <p className="text-sm font-medium">
434 <T>No preview for this file</T>
435 </p>
436 <p className="max-w-sm text-xs leading-relaxed text-muted-foreground">
437 {extension ? (
438 <T>
439 Save it to open in an app that supports <Var>{extension}</Var> files.
440 </T>
441 ) : (
442 <T>Save it to open in an app that supports this format.</T>
443 )}
444 </p>
445 {revealLabel ? (
446 <Button variant="outline" size="sm" className="mt-3" onClick={reveal}>
447 <FolderOpenIcon />
448 {revealLabel}
449 </Button>
450 ) : null}
451 </div>
452 );
453​
454 const breadcrumb = (
455 <div className="flex min-w-0 flex-1 items-center text-xs">
456 <span className="shrink-0 px-0.5 text-muted-foreground">
457 {props.origin ?? gt`Attachment`}
458 </span>
459 <ChevronRightIcon className="mx-1 size-3.5 shrink-0 text-muted-foreground/60" />
460 <span aria-current="page" className="min-w-0 truncate px-0.5 font-medium text-foreground">
461 {props.name}
462 </span>
463 {props.sizeBytes > 0 ? (
464 <span className="ml-2 shrink-0 text-muted-foreground">
465 {formatAttachmentSize(props.sizeBytes, messages, locale)}
466 </span>
467 ) : null}
468 </div>
469 );
470 const actions = (
471 <>
472 {renderedMode ? (
473 <FileSurfaceAction
474 label={renderedToggleLabel(renderedMode, rendered, messages)}
475 pressed={rendered}
476 onPress={() => setRendered((value) => !value)}
477 >
478 {rendered ? (
479 <Code2Icon className="size-3.5" />
480 ) : renderedMode === "table" ? (
481 <Table2Icon className="size-3.5" />
482 ) : (
483 <EyeIcon className="size-3.5" />
484 )}
485 </FileSurfaceAction>
486 ) : null}
487 {showsRawText ? (
488 <FileSurfaceAction
489 label={wordWrap ? gt`Disable word wrap` : gt`Enable word wrap`}
490 pressed={wordWrap}
491 onPress={() => setWordWrapOverride(!wordWrap)}
492 >
493 <WrapTextIcon className="size-3.5" />
494 </FileSurfaceAction>
495 ) : null}
496 {failure === null && (content || streamsText) ? (
497 <FileSurfaceAction
498 label={isCopied ? gt`Copied` : content?.truncated ? gt`Copy preview` : gt`Copy contents`}
499 onPress={() => {
500 if (content) {
501 void copyToClipboard(content.text, undefined);
502 return;
503 }
504 const copy = copyContents.current;
505 if (!copy) {
506 toastManager.add({
507 type: "error",
508 title: gt`Could not copy file`,
509 description: gt`Wait for the file to finish loading before copying.`,
510 });
511 return;
512 }
513 void copy()
514 .then((text) => copyToClipboard(text, undefined))
515 .catch((cause: unknown) =>
516 toastManager.add({
517 type: "error",
518 title: gt`Could not copy file`,
519 description: thrownErrorMessage(cause, m) ?? gt`Try again.`,
520 }),
521 );
522 }}
523 >
524 {isCopied ? <CheckIcon className="size-3.5" /> : <CopyIcon className="size-3.5" />}
525 </FileSurfaceAction>
526 ) : null}
527 {revealLabel && !embedded ? (
528 <FileSurfaceAction label={revealLabel} onPress={reveal}>
529 <FolderOpenIcon className="size-3.5" />
530 </FileSurfaceAction>
531 ) : null}
532 {url ? (
533 <FileSurfaceAction
534 label={saving ? gt`Preparing file…` : gt`Save file`}
535 disabled={saving}
536 onPress={save}
537 >
538 <DownloadIcon className="size-3.5" />
539 </FileSurfaceAction>
540 ) : null}
541 {props.onRemove ? (
542 <FileSurfaceAction label={gt`Remove from draft`} onPress={props.onRemove}>
543 <Trash2Icon className="size-3.5" />
544 </FileSurfaceAction>
545 ) : null}
546 {props.onClose ? (
547 <FileSurfaceAction
548 label={gt({ context: "button, closes the file preview" })`Close`}
549 onPress={props.onClose}
550 >
551 <XIcon className="size-3.5" />
552 </FileSurfaceAction>
553 ) : null}
554 </>
555 );
556​
557 return (
558 <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-background">
559 {embedded ? (
560 props.actionsTarget ? (
561 createPortal(actions, props.actionsTarget)
562 ) : null
563 ) : (
564 <div className={cn(FILE_SURFACE_SUBHEADER_CLASS)} data-surface-subheader>
565 {breadcrumb}
566 {actions}
567 </div>
568 )}
569 {content?.truncated ? (
570 <FileSurfaceNotice>
571 {props.sizeBytes > 0
572 ? gt`Preview limited to the first 1 MB of a ${{ size: sizeFormat.format(props.sizeBytes) }} byte file. Save the file to read it in full.`
573 : gt`Preview limited to the first 1 MB. Save the file to read it in full.`}
574 </FileSurfaceNotice>
575 ) : null}
576 {body}
577 </div>
578 );