"tests/csrc/unittests/test_sampling_kernels.cu" did not exist on "53d2e42cbe70898f9b13969e896a8f555d2947aa"
index.tsx 10.5 KB
Newer Older
dechen lin's avatar
dechen lin committed
1
2
3
4
5
6
7
8
9
10
11
12
import React, {
  useEffect,
  useRef,
  useState,
  useMemo,
  forwardRef,
  useImperativeHandle,
  useCallback,
} from "react";
import cls from "classnames";
import { isObjEqual } from "@/utils/render";
import { useSize } from "ahooks";
dechen lin's avatar
dechen lin committed
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

interface IImageLayersViewerProps {
  imageUrl: string;
  imageWidth: number;
  imageHeight: number;
  layout: Array<{
    category_id: number;
    poly: number[];
    score: number;
    latex?: string;
  }>;
  layerVisible?: boolean;
  disableZoom?: boolean;
  className?: string;
  onChange?: (data: { scale: number }) => void;
}

export interface ImageLayerViewerRef {
  containerRef: HTMLDivElement | null;
  zoomIn: () => void;
  zoomOut: () => void;
  scale: number;
  updateScaleAndPosition: () => void;
}

dechen lin's avatar
dechen lin committed
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const ImageLayerViewer = forwardRef<
  ImageLayerViewerRef,
  IImageLayersViewerProps
>(
  (
    {
      imageUrl,
      imageHeight,
      imageWidth,
      onChange,
      layout,
      disableZoom,
      className = "",
      layerVisible = true,
    },
    ref
  ) => {
dechen lin's avatar
dechen lin committed
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
    const containerRef = useRef<HTMLDivElement>(null);
    const imageCanvasRef = useRef<HTMLCanvasElement>(null);
    const overlayCanvasRef = useRef<HTMLCanvasElement>(null);
    const rafRef = useRef<number | null>(null);
    const containerSize = useSize(containerRef);

    const [scale, setScale] = useState(1);
    const [position, setPosition] = useState({ x: 0, y: 0 });
    const [padding, setPadding] = useState({ left: 0, top: 0 });

    const minZoom = 0.1;
    const maxZoom = 3;
    const zoomSensitivity = 0.001;
    const zoomStep = 0.1;

    const dpr = useMemo(() => window.devicePixelRatio || 1, []);

    const image = useMemo(() => {
      const img = new Image();
      img.src = imageUrl;
      return img;
    }, [imageUrl]);

    const calculateInitialScaleAndPosition = useCallback(() => {
dechen lin's avatar
dechen lin committed
79
80
      if (!containerRef.current)
        return { initialScale: 1, initialPosition: { x: 0, y: 0 } };
dechen lin's avatar
dechen lin committed
81
82
83
84
85
86
87
88
89
90
91
92
      const containerWidth = containerRef.current.clientWidth;
      const containerHeight = containerRef.current.clientHeight;

      const scaleX = containerWidth / imageWidth;
      const scaleY = containerHeight / imageHeight;
      const initialScale = Math.min(scaleX, scaleY, 1); // Ensure it doesn't scale up initially

      const scaledWidth = imageWidth * initialScale;
      const scaledHeight = imageHeight * initialScale;

      const initialPosition = {
        x: (containerWidth - scaledWidth) / 2,
dechen lin's avatar
dechen lin committed
93
        y: (containerHeight - scaledHeight) / 2,
dechen lin's avatar
dechen lin committed
94
95
96
97
98
99
      };

      return { initialScale, initialPosition };
    }, [imageWidth, imageHeight]);

    const updateScaleAndPosition = useCallback(() => {
dechen lin's avatar
dechen lin committed
100
101
      const { initialScale, initialPosition } =
        calculateInitialScaleAndPosition();
dechen lin's avatar
dechen lin committed
102
103
104
105
106
107
108
109
110
111
      setScale(initialScale);
      setPosition(initialPosition);
      setPadding({ left: 0, top: 0 });
    }, [calculateInitialScaleAndPosition]);

    useEffect(() => {
      updateScaleAndPosition();
    }, [imageWidth, imageHeight]);

    const drawImage = useCallback(() => {
dechen lin's avatar
dechen lin committed
112
      const ctx = imageCanvasRef.current?.getContext("2d");
dechen lin's avatar
dechen lin committed
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
      if (!ctx || !image.complete) return;

      const scaledWidth = imageWidth * scale;
      const scaledHeight = imageHeight * scale;

      ctx.canvas.width = scaledWidth * dpr;
      ctx.canvas.height = scaledHeight * dpr;
      ctx.canvas.style.width = `${scaledWidth}px`;
      ctx.canvas.style.height = `${scaledHeight}px`;

      ctx.scale(dpr, dpr);

      ctx.clearRect(0, 0, scaledWidth, scaledHeight);
      ctx.drawImage(image, 0, 0, scaledWidth, scaledHeight);
    }, [image, imageWidth, imageHeight, scale, dpr]);

    const drawLayout = useCallback(() => {
dechen lin's avatar
dechen lin committed
130
      const ctx = overlayCanvasRef.current?.getContext("2d");
dechen lin's avatar
dechen lin committed
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
      if (!ctx) return;

      const scaledWidth = imageWidth * scale;
      const scaledHeight = imageHeight * scale;

      ctx.canvas.width = scaledWidth * dpr;
      ctx.canvas.height = scaledHeight * dpr;
      ctx.canvas.style.width = `${scaledWidth}px`;
      ctx.canvas.style.height = `${scaledHeight}px`;

      ctx.scale(dpr, dpr);

      ctx.clearRect(0, 0, scaledWidth, scaledHeight);

      layout?.forEach((item) => {
dechen lin's avatar
dechen lin committed
146
147
148
        const [x1, y1, x2, y2, x3, y3, x4, y4] = item.poly.map(
          (coord) => coord * scale
        );
dechen lin's avatar
dechen lin committed
149
150
151

        switch (item.category_id) {
          case 9:
dechen lin's avatar
dechen lin committed
152
153
            ctx.fillStyle = "rgba(230, 113, 230, 0.4)";
            ctx.strokeStyle = "rgba(230, 113, 230, 1)";
dechen lin's avatar
dechen lin committed
154
155
            break;
          case 8:
dechen lin's avatar
dechen lin committed
156
157
            ctx.fillStyle = "rgba(240, 240, 124, 0.4)";
            ctx.strokeStyle = "rgba(240, 240, 124, 1)";
dechen lin's avatar
dechen lin committed
158
159
            break;
          case 13:
dechen lin's avatar
dechen lin committed
160
161
            ctx.fillStyle = "rgba(150, 232, 172, 0.4)";
            ctx.strokeStyle = "rgba(150, 232, 172, 1)";
dechen lin's avatar
dechen lin committed
162
163
            break;
          case 14:
dechen lin's avatar
dechen lin committed
164
165
            ctx.fillStyle = "rgba(230, 122, 171, 0.4)";
            ctx.strokeStyle = "rgba(230, 122, 171, 1)";
dechen lin's avatar
dechen lin committed
166
167
            break;
          default:
dechen lin's avatar
dechen lin committed
168
169
            ctx.fillStyle = "transparent";
            ctx.strokeStyle = "transparent";
dechen lin's avatar
dechen lin committed
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
        }

        ctx.beginPath();
        ctx.moveTo(x1, y1);
        ctx.lineTo(x2, y2);
        ctx.lineTo(x3, y3);
        ctx.lineTo(x4, y4);
        ctx.closePath();
        ctx.fill();
        ctx.stroke();
      });
    }, [layout, scale, dpr]);

    const updateScale = useCallback(
      (newScale: number, clientX: number, clientY: number) => {
        if (containerRef.current) {
          const rect = containerRef.current.getBoundingClientRect();
          const containerWidth = rect.width;
          const containerHeight = rect.height;
          const x = clientX - rect.left;
          const y = clientY - rect.top;

          const prevScaledWidth = imageWidth * scale;
          const prevScaledHeight = imageHeight * scale;
          const newScaledWidth = imageWidth * newScale;
          const newScaledHeight = imageHeight * newScale;

          let newPosition = {
dechen lin's avatar
dechen lin committed
198
199
200
201
202
203
204
205
            x:
              position.x -
              ((x - position.x) * (newScaledWidth - prevScaledWidth)) /
                prevScaledWidth,
            y:
              position.y -
              ((y - position.y) * (newScaledHeight - prevScaledHeight)) /
                prevScaledHeight,
dechen lin's avatar
dechen lin committed
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
          };

          // Center the image if it's smaller than the container
          if (newScaledWidth < containerWidth) {
            newPosition.x = (containerWidth - newScaledWidth) / 2;
          }
          if (newScaledHeight < containerHeight) {
            newPosition.y = (containerHeight - newScaledHeight) / 2;
          }

          setScale(newScale);
          setPosition(newPosition);

          // Calculate new padding
          const newPadding = {
            left: Math.max(0, -newPosition.x),
dechen lin's avatar
dechen lin committed
222
            top: Math.max(0, -newPosition.y),
dechen lin's avatar
dechen lin committed
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
          };
          setPadding(newPadding);
        }
      },
      [scale, position, imageWidth, imageHeight]
    );

    const handleZoom = useCallback(
      (delta: number, clientX: number, clientY: number) => {
        const newScale = scale * Math.exp(-delta * zoomSensitivity);
        const boundedNewScale = Math.max(minZoom, Math.min(newScale, maxZoom));

        if (rafRef.current !== null) {
          cancelAnimationFrame(rafRef.current);
        }

        rafRef.current = requestAnimationFrame(() => {
          updateScale(boundedNewScale, clientX, clientY);
        });
      },
      [scale, updateScale]
    );

    const handleCenterZoom = useCallback(
      (zoomIn: boolean) => {
dechen lin's avatar
dechen lin committed
248
249
250
        const newScale = zoomIn
          ? scale * (1 + zoomStep)
          : scale / (1 + zoomStep);
dechen lin's avatar
dechen lin committed
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
        const boundedNewScale = Math.max(minZoom, Math.min(newScale, maxZoom));

        if (containerRef.current) {
          const rect = containerRef.current.getBoundingClientRect();
          const centerX = rect.width / 2;
          const centerY = rect.height / 2;

          updateScale(boundedNewScale, centerX, centerY);
        }
      },
      [scale, updateScale]
    );

    const zoomIn = useCallback(() => {
      handleCenterZoom(true);
    }, [handleCenterZoom]);

    const zoomOut = useCallback(() => {
      handleCenterZoom(false);
    }, [handleCenterZoom]);

    useImperativeHandle(
      ref,
      () => ({
        containerRef: containerRef.current,
        zoomIn,
        zoomOut,
        scale,
dechen lin's avatar
dechen lin committed
279
        updateScaleAndPosition,
dechen lin's avatar
dechen lin committed
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
      }),
      [zoomIn, zoomOut, scale]
    );

    useEffect(() => {
      const container = containerRef.current;
      if (!container) return;

      const handleWheel = (e: WheelEvent) => {
        if (e.ctrlKey || e.metaKey) {
          e.preventDefault();
          handleZoom(e.deltaY * 4.8, e.clientX, e.clientY);
        }
      };

dechen lin's avatar
dechen lin committed
295
      container.addEventListener("wheel", handleWheel, { passive: false });
dechen lin's avatar
dechen lin committed
296
297

      return () => {
dechen lin's avatar
dechen lin committed
298
        container.removeEventListener("wheel", handleWheel);
dechen lin's avatar
dechen lin committed
299
300
301
302
303
304
305
      };
    }, [handleZoom]);

    useEffect(() => {
      if (containerRef?.current) {
        containerRef.current?.scrollTo({
          left: padding.left,
dechen lin's avatar
dechen lin committed
306
          top: padding.top,
dechen lin's avatar
dechen lin committed
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
        });
      }
    }, [padding]);

    useEffect(() => {
      const draw = () => {
        drawImage();
        drawLayout();
      };

      if (image.complete) {
        draw();
      } else {
        image.onload = draw;
      }
    }, [image, drawImage, drawLayout]);

    useEffect(() => {
      if (overlayCanvasRef.current) {
dechen lin's avatar
dechen lin committed
326
        overlayCanvasRef.current.style.opacity = layerVisible ? "1" : "0";
dechen lin's avatar
dechen lin committed
327
328
329
330
331
332
333
334
      }
    }, [layerVisible]);

    useEffect(() => {
      onChange?.({ scale });
    }, [scale]);

    return (
dechen lin's avatar
dechen lin committed
335
336
337
338
339
340
341
      <div
        className={cls(
          className,
          "w-full h-full overflow-auto scrollbar-thin relative"
        )}
        ref={containerRef}
      >
dechen lin's avatar
dechen lin committed
342
343
344
        <div
          style={{
            paddingLeft: `${padding.left}px`,
dechen lin's avatar
dechen lin committed
345
            paddingTop: `${padding.top}px`,
dechen lin's avatar
dechen lin committed
346
347
348
349
350
351
352
          }}
        >
          <div
            className="absolute"
            style={{
              width: `${imageWidth * scale}px`,
              height: `${imageHeight * scale}px`,
dechen lin's avatar
dechen lin committed
353
              transform: `translate(${position.x}px, ${position.y}px)`,
dechen lin's avatar
dechen lin committed
354
355
356
357
358
359
            }}
          >
            <canvas
              ref={imageCanvasRef}
              style={{
                width: `${imageWidth * scale}px`,
dechen lin's avatar
dechen lin committed
360
                height: `${imageHeight * scale}px`,
dechen lin's avatar
dechen lin committed
361
362
363
364
365
366
367
              }}
            />
            <canvas
              ref={overlayCanvasRef}
              className="absolute top-0 left-0"
              style={{
                width: `${imageWidth * scale}px`,
dechen lin's avatar
dechen lin committed
368
                height: `${imageHeight * scale}px`,
dechen lin's avatar
dechen lin committed
369
370
371
372
373
374
375
376
377
378
              }}
            />
          </div>
        </div>
      </div>
    );
  }
);

export default React.memo(ImageLayerViewer, isObjEqual);