Open History to see the last commit
1import { memo, useLayoutEffect, useState, type ReactNode } from "react";
2
3import { cn } from "~/lib/utils";
4
5import {
6 createComposerImageThumbnail,
7 isHeicImageFile,
8 MAX_COMPRESSIBLE_SOURCE_BYTES,
9 readComposerImageThumbnail,
10} from "../../lib/imageCompression";
11
12export const ComposerImageThumbnail = memo(function ComposerImageThumbnail({
13 file,
14 alt,
15 className,
16 fallback,
17}: {
18 file: File;
19 alt: string;
20 className: string;
21 fallback: ReactNode;
22}) {
23 const [preview, setPreview] = useState(() => ({
24 file,
25 src: readComposerImageThumbnail(file),
26 }));
27 const [loadedSrc, setLoadedSrc] = useState<string | null>(null);
28 const [failedSrc, setFailedSrc] = useState<string | null>(null);
29 const src = preview.file === file ? preview.src : readComposerImageThumbnail(file);
30
31 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- owns the local blob URL and decodes its replacement before swapping the visible image
32 useLayoutEffect(() => {
33 let disposed = false;
34 let localUrl: string | undefined;
35 const cached = readComposerImageThumbnail(file);
36 if (file.size <= MAX_COMPRESSIBLE_SOURCE_BYTES && !isHeicImageFile(file) && !cached) {
37 localUrl = URL.createObjectURL(file);
38 setPreview({ file, src: localUrl });
39 }
40 if (cached === undefined) {
41 void createComposerImageThumbnail(file).then(async (thumbnail) => {
42 if (disposed) return;
43 if (!thumbnail) {
44 if (!localUrl) setPreview({ file, src: null });
45 return;
46 }
47 const image = new Image();
48 image.src = thumbnail;
49 try {
50 await image.decode();
51 if (!disposed) setPreview({ file, src: thumbnail });
52 } catch {
53 // Keep the local preview if the thumbnail cannot be decoded.
54 }
55 });
56 }
57 return () => {
58 disposed = true;
59 if (localUrl) URL.revokeObjectURL(localUrl);
60 };
61 }, [file]);
62
63 return src && failedSrc !== src ? (
64 <span className="relative block size-full">
65 {loadedSrc !== src && fallback}
66 <img
67 ref={(image) => {
68 if (image?.complete && image.naturalWidth > 0) setLoadedSrc(src);
69 }}
70 src={src}
71 alt={alt}
72 onLoad={() => setLoadedSrc(src)}
73 onError={() => setFailedSrc(src)}
74 className={cn(className, loadedSrc !== src && "invisible absolute inset-0")}
75 />
76 </span>
77 ) : (
78 fallback
79 );
80});