Bin
2025-12-17 2b99d77d73ba568beff0a549534017caaad8a6de
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import { useState, useRef, useEffect, type CSSProperties, useCallback } from "react";
import { observer } from "mobx-react";
import styles from "./GridPreview.module.scss";
import { cn } from "@humansignal/ui";
 
const MAX_ZOOM = 20;
const ZOOM_FACTOR = 0.01;
 
type Task = {
  id: number;
  data: Record<string, string>;
};
 
type ImagePreviewProps = {
  task: Task;
  field: string;
};
 
// @todo constrain the position of the image to the container
const ImagePreview = observer(({ task, field }: ImagePreviewProps) => {
  const src = task.data?.[field] ?? "";
 
  const containerRef = useRef<HTMLDivElement>(null);
  const imageRef = useRef<HTMLImageElement>(null);
 
  const [imageLoaded, setImageLoaded] = useState(false);
  // visible container size
  const [containerSize, setContainerSize] = useState({ width: 0, height: 0 });
  // scaled image size
  const [imageSize, setImageSize] = useState({ width: 0, height: 0 });
 
  // Zoom and position state
  const [scale, setScale] = useState(1);
  const [offset, setOffset] = useState({ x: 0, y: 0 });
 
  const [isDragging, setIsDragging] = useState(false);
 
  const dragParams = useRef({
    dragAnchor: { x: 0, y: 0 },
    startOffset: { x: 0, y: 0 },
  });
 
  // Reset on task change
  // biome-ignore lint/correctness/useExhaustiveDependencies: those are setStates, not values
  useEffect(() => {
    setScale(1);
    setIsDragging(false);
  }, [task, src]);
 
  const constrainOffset = useCallback(
    (newOffset: { x: number; y: number }) => {
      const { x, y } = newOffset;
      const { width, height } = imageSize;
      const { width: containerWidth, height: containerHeight } = containerSize;
 
      // to preserve paddings and make it less weird
      const minX = (containerWidth - width) / 2;
      const minY = (containerHeight - height) / 2;
      // the far edges should be behind container edges
      const maxX = Math.max(width * scale - containerWidth, 0);
      const maxY = Math.max(height * scale - containerHeight, 0);
 
      return {
        x: Math.min(Math.max(x, -maxX), minX),
        y: Math.min(Math.max(y, -maxY), minY),
      };
    },
    [imageSize, containerSize, scale],
  );
 
  const handleImageLoad = useCallback((e: React.SyntheticEvent<HTMLImageElement>) => {
    if (containerRef.current) {
      const img = e.currentTarget;
      const containerRect = containerRef.current.getBoundingClientRect();
 
      setContainerSize({
        width: containerRect.width,
        height: containerRect.height,
      });
 
      const coverScaleX = containerRect.width / img.naturalWidth;
      const coverScaleY = containerRect.height / img.naturalHeight;
      // image is scaled by html, but we need to know this scale level
      // how much is image zoomed out to fit into container
      const imageScale = Math.min(coverScaleX, coverScaleY);
 
      const scaledWidth = img.naturalWidth * imageScale;
      const scaledHeight = img.naturalHeight * imageScale;
      // how much should we zoom image in to cover container
      // const coverScale = Math.max(containerRect.width / scaledWidth, containerRect.height / scaledHeight);
 
      setImageSize({
        width: scaledWidth,
        height: scaledHeight,
      });
 
      // Center the image initially
      const initialX = (containerRect.width - scaledWidth) / 2;
      const initialY = (containerRect.height - scaledHeight) / 2;
 
      setOffset({ x: initialX, y: initialY });
      setImageLoaded(true);
    }
  }, []);
 
  const handleWheel = useCallback(
    (e: React.WheelEvent) => {
      if (!containerRef.current || !imageLoaded) return;
 
      const container = containerRef.current;
      const rect = container.getBoundingClientRect();
      const img = imageRef.current;
      if (!img) return;
 
      // Calculate cursor position relative to center
      const cursorX = e.clientX - rect.left;
      const cursorY = e.clientY - rect.top;
 
      // Zoom calculation
      const newScale =
        e.deltaY < 0
          ? Math.min(scale * (1 + ZOOM_FACTOR), MAX_ZOOM) // Max zoom
          : Math.max(scale * (1 - ZOOM_FACTOR), 1); // Min zoom
 
      // Calculate zoom translation
      const scaleDelta = newScale / scale;
      // cursor - offset = cursor position relative to image; and that's the value being scaled.
      // cursor position on a screen should stay the same, so we need to calculate new offset
      // by scaling the distance to image edges and subtracting it from cursor position
      const newX = cursorX - (cursorX - offset.x) * scaleDelta;
      const newY = cursorY - (cursorY - offset.y) * scaleDelta;
 
      setScale(newScale);
      setOffset(constrainOffset({ x: newX, y: newY }));
    },
    [imageLoaded, offset, scale, constrainOffset],
  );
 
  const handleMouseMove = useCallback(
    (e: MouseEvent) => {
      if (!containerRef.current || !imageRef.current) return;
 
      const { x: oldX, y: oldY } = dragParams.current.dragAnchor;
      const { x: offsetX, y: offsetY } = dragParams.current.startOffset;
      const newX = e.clientX - oldX;
      const newY = e.clientY - oldY;
 
      setOffset(constrainOffset({ x: offsetX + newX, y: offsetY + newY }));
    },
    [constrainOffset],
  );
 
  const handleMouseUp = useCallback(
    (e: MouseEvent) => {
      e.preventDefault();
      e.stopPropagation();
 
      setIsDragging(false);
 
      window.removeEventListener("mousemove", handleMouseMove);
      window.removeEventListener("mouseup", handleMouseUp);
    },
    [handleMouseMove],
  );
 
  const handleMouseDown = useCallback(
    (e: React.MouseEvent) => {
      if (!containerRef.current || scale <= 1) return;
 
      setIsDragging(true);
      dragParams.current.dragAnchor = { x: e.clientX, y: e.clientY };
      dragParams.current.startOffset = { ...offset };
 
      window.addEventListener("mousemove", handleMouseMove);
      // this event would be fired even if we release the mouse outside the window
      // we catch `click` and use `capture: true` to block the click outside of the modal
      /** @see ModalPopup#onClickOutside() */
      window.addEventListener("click", handleMouseUp, { capture: true, once: true });
    },
    [scale, offset, handleMouseMove, handleMouseUp],
  );
 
  // Container styles
  const containerStyle: CSSProperties = {
    minHeight: "200px",
    maxHeight: "calc(90vh - 120px)",
    width: "100%",
    position: "relative",
    overflow: "hidden",
    cursor: scale > 1 ? (isDragging ? "grabbing" : "grab") : "default",
    userSelect: "none",
  };
 
  // Image styles
  const imageStyle: CSSProperties = imageLoaded
    ? {
        maxWidth: "100%",
        maxHeight: "100%",
        transform: `translate(${offset.x}px, ${offset.y}px) scale(${scale})`,
        transformOrigin: "0 0",
      }
    : {
        width: "100%",
        height: "100%",
        objectFit: "contain",
      };
 
  return (
    <div
      ref={containerRef}
      style={containerStyle}
      className={cn(styles.imageContainer, "px-tight")}
      onWheel={handleWheel}
      onMouseDown={handleMouseDown}
    >
      {src && (
        <img
          ref={imageRef}
          src={src}
          alt="Task Preview"
          style={imageStyle}
          className={styles.image}
          onLoad={handleImageLoad}
        />
      )}
    </div>
  );
});
 
const ImagePreviewWrapper = observer(({ task, field }: ImagePreviewProps) => {
  if (!task || !field) return null;
  return <ImagePreview task={task} field={field} />;
});
 
export { ImagePreviewWrapper as ImagePreview };