@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 63 lines 2.39 KB
Raw
1 import { useEffect, useRef, useState, type ComponentProps, type SyntheticEvent } from "react";
2 import { isHeicImageFile } from "../../lib/imageCompression";
3
4 type AttachmentImageProps = ComponentProps<"img"> & { name: string; mimeType?: string | undefined };
5
6 // Keep import expressions outside hooks until React Compiler supports them.
7 const loadImageDecoder = () => import("../files/decodeImagePreview");
8
9 export function AttachmentImage({ name, mimeType, ...props }: AttachmentImageProps) {
10 const fallback =
11 isHeicImageFile({ name, type: mimeType ?? "" }) ||
12 /\.tiff?$/i.test(name) ||
13 /^image\/tiff$/i.test(mimeType ?? "");
14 return fallback ? (
15 <DecodedImage key={props.src} {...props} name={name} mimeType={mimeType} />
16 ) : (
17 <img {...props} />
18 );
19 }
20
21 type DecodeAttempt = { readonly controller: AbortController; objectUrl?: string };
22
23 function DecodedImage({ name, mimeType, src, onError, ...props }: AttachmentImageProps) {
24 const [previewUrl, setPreviewUrl] = useState<string>();
25 // One decode per mount; the parent keys this component by src.
26 const decodeRef = useRef<DecodeAttempt | null>(null);
27
28 // The browser cannot show HEIC or TIFF itself, so its load error starts the decode.
29 const decode = (event: SyntheticEvent<HTMLImageElement>) => {
30 if (decodeRef.current !== null || !src) return onError?.(event);
31 const attempt: DecodeAttempt = { controller: new AbortController() };
32 decodeRef.current = attempt;
33 const { signal } = attempt.controller;
34 void loadImageDecoder()
35 .then(async ({ decodeImagePreview }) => {
36 if (signal.aborted) return;
37 const blob = await decodeImagePreview(
38 src,
39 /\.hei[cf]$/i.test(name) || /^image\/hei[cf]$/i.test(mimeType ?? ""),
40 signal,
41 );
42 if (signal.aborted) return;
43 attempt.objectUrl = URL.createObjectURL(blob);
44 setPreviewUrl(attempt.objectUrl);
45 })
46 .catch(() => {
47 if (!signal.aborted) onError?.(event);
48 });
49 };
50
51 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the async decode and its blob URL live as long as this component
52 useEffect(
53 () => () => {
54 const attempt = decodeRef.current;
55 if (attempt === null) return;
56 attempt.controller.abort();
57 if (attempt.objectUrl) URL.revokeObjectURL(attempt.objectUrl);
58 },
59 [],
60 );
61
62 return <img {...props} src={previewUrl ?? src} onError={decode} />;
63 }