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 (
37 file.size <= MAX_COMPRESSIBLE_SOURCE_BYTES &&
38 !isHeicImageFile(file) &&
39 cached === undefined
40 ) {
41 localUrl = URL.createObjectURL(file);
42 // oxlint-disable-next-line react/set-state-in-effect -- the blob URL is created and revoked by this effect
43 setPreview({ file, src: localUrl });
44 }
45 if (cached === undefined) {
46 void createComposerImageThumbnail(file).then(async (thumbnail) => {
47 if (disposed) return;
48 if (!thumbnail) {
49 if (!localUrl) setPreview({ file, src: null });
50 return;
51 }
52 const image = new Image();
53 image.src = thumbnail;
54 try {
55 await image.decode();
56 if (!disposed) setPreview({ file, src: thumbnail });
57 } catch {
58 // Keep the local preview if the thumbnail cannot be decoded.
59 }
60 });
61 }
62 return () => {
63 disposed = true;
64 if (localUrl) URL.revokeObjectURL(localUrl);
65 };
66 }, [file]);
67
68 return src && failedSrc !== src ? (
69 <img
70 ref={(image) => {
71 if (image?.complete && image.naturalWidth > 0) setLoadedSrc(src);
72 }}
73 src={src}
74 alt={alt}
75 onLoad={() => setLoadedSrc(src)}
76 onError={() => setFailedSrc(src)}
77 className={cn(className, loadedSrc !== src && "invisible")}
78 />
79 ) : src === undefined ? null : (
80 fallback
81 );
82});