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

PreviewImageContent.tsx

148 lines5.6 KB

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