Open History to see the last commit
1import { useGT } from "gt-react";
2import { useLayoutEffect, useRef, useState } from "react";
3import { MaximizeIcon, MinusIcon, PlusIcon, ScanIcon } from "lucide-react";
4import { ExpandedImageDialog } from "~/components/chat/ExpandedImageDialog";
5import { observeResize } from "~/lib/observeResize";
6import { AttachmentImage } from "../media/AttachmentImage";
7import { FileSurfaceAction, FileSurfaceFailure } from "./fileSurfaceChrome";
8
9export default function PreviewImageContent(props: {
10 readonly src: string;
11 readonly name: string;
12 readonly mimeType?: string;
13 readonly onError?: () => void;
14}) {
15 const gt = useGT();
16 const [failed, setFailed] = useState(false);
17 const [expanded, setExpanded] = useState(false);
18 const [natural, setNatural] = useState({ width: 0, height: 0 });
19 const [viewport, setViewport] = useState({ width: 0, height: 0 });
20 const [zoom, setZoom] = useState<number | null>(null);
21 const ref = useRef<HTMLDivElement>(null);
22 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Measure the image viewport before paint and observe resizes to keep fit-to-view scaling accurate.
23 useLayoutEffect(() => {
24 const node = ref.current;
25 if (!node) return;
26 // clientWidth rounds a fractional pane size up, and an image fitted to it overflows the pane.
27 // The computed size keeps the fraction; it reads "auto" while an ancestor is display:none.
28 const update = () => {
29 const size = getComputedStyle(node);
30 setViewport({
31 width: Math.floor(Number.parseFloat(size.width) || 0),
32 height: Math.floor(Number.parseFloat(size.height) || 0),
33 });
34 };
35 update();
36 return observeResize(node, update);
37 }, []);
38 const fit = natural.width
39 ? Math.min(
40 1,
41 Math.max(1, viewport.width - 32) / natural.width,
42 Math.max(1, viewport.height - 32) / natural.height,
43 )
44 : 1;
45 const scale = zoom ?? fit;
46 const changeZoom = (factor: number) => setZoom(Math.max(0.05, Math.min(8, scale * factor)));
47 if (failed) return <FileSurfaceFailure message={gt("Unable to load image.")} />;
48 return (
49 <>
50 <div className="flex min-h-10 shrink-0 flex-wrap items-center justify-between gap-2 border-b border-border/60 px-3 py-1 text-xs text-muted-foreground">
51 <span className="tabular-nums">
52 {natural.width
53 ? `${natural.width.toLocaleString()} × ${natural.height.toLocaleString()}`
54 : gt("Loading image…")}
55 </span>
56 <div className="flex items-center gap-1">
57 <FileSurfaceAction
58 label={gt("Zoom out")}
59 disabled={!natural.width || scale <= 0.05}
60 onPress={() => changeZoom(1 / 1.25)}
61 >
62 <MinusIcon className="size-3.5" />
63 </FileSurfaceAction>
64 <span className="min-w-10 text-center tabular-nums">{Math.round(scale * 100)}%</span>
65 <FileSurfaceAction
66 label={gt("Zoom in")}
67 disabled={!natural.width || scale >= 8}
68 onPress={() => changeZoom(1.25)}
69 >
70 <PlusIcon className="size-3.5" />
71 </FileSurfaceAction>
72 <FileSurfaceAction
73 label={gt("Fit image")}
74 pressed={zoom === null}
75 onPress={() => setZoom(null)}
76 >
77 <ScanIcon className="size-3.5" />
78 </FileSurfaceAction>
79 <FileSurfaceAction
80 label={gt("Actual image size")}
81 pressed={zoom === 1}
82 onPress={() => setZoom(1)}
83 >
84 <MaximizeIcon className="size-3.5" />
85 </FileSurfaceAction>
86 </div>
87 </div>
88 <div ref={ref} className="min-h-0 flex-1 overflow-auto">
89 <div
90 className="flex min-h-full min-w-full items-center justify-center p-4"
91 style={{
92 width: natural.width ? natural.width * scale + 32 : undefined,
93 height: natural.height ? natural.height * scale + 32 : undefined,
94 }}
95 >
96 <button
97 type="button"
98 aria-label={gt("Zoom {name}", { name: props.name })}
99 className="shrink-0 cursor-zoom-in"
100 onClick={() => setExpanded(true)}
101 >
102 <AttachmentImage
103 name={props.name}
104 mimeType={props.mimeType}
105 src={props.src}
106 alt={props.name}
107 className="block max-w-none"
108 // A cached image has its natural size before onLoad runs, so it stays at 0x0 until the
109 // fit scale is known instead of painting at full size for a frame.
110 style={
111 natural.width
112 ? { width: natural.width * scale, height: natural.height * scale }
113 : { width: 0, height: 0 }
114 }
115 onLoad={(event) =>
116 setNatural({
117 width: event.currentTarget.naturalWidth,
118 height: event.currentTarget.naturalHeight,
119 })
120 }
121 onError={() => {
122 setFailed(true);
123 props.onError?.();
124 }}
125 />
126 </button>
127 </div>
128 </div>
129 {expanded ? (
130 <ExpandedImageDialog
131 preview={{
132 images: [
133 {
134 src: props.src,
135 name: props.name,
136 ...(props.mimeType ? { mimeType: props.mimeType } : {}),
137 },
138 ],
139 index: 0,
140 }}
141 onClose={() => setExpanded(false)}
142 />
143 ) : null}
144 </>
145 );
146}