File size: 15,865 Bytes
f56a29b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import { useCallback } from 'react';
import { useCanvasStore, useKeyboardStore } from '@/lib/store';
import { useHistorySnapshot } from '@/lib/hooks/use-history-snapshot';
import type { PPTElement } from '@/lib/types/slides';
import type { AlignmentLineProps } from '@/lib/types/edit';
import { getRectRotatedRange, uniqAlignLines, type AlignLine } from '@/lib/utils/element';
import { useCanvasOperations } from '@/lib/hooks/use-canvas-operations';

/**
 * Drag element hook
 *
 * @param elementListRef - Element list ref (holds latest value)
 * @param setElementList - Element list setter (triggers re-render)
 * @param setAlignmentLines - Alignment lines setter
 */
export function useDragElement(
  elementListRef: React.RefObject<PPTElement[]>,
  setElementList: React.Dispatch<React.SetStateAction<PPTElement[]>>,
  setAlignmentLines: React.Dispatch<React.SetStateAction<AlignmentLineProps[]>>,
) {
  const activeElementIdList = useCanvasStore.use.activeElementIdList();
  const activeGroupElementId = useCanvasStore.use.activeGroupElementId();
  const canvasScale = useCanvasStore.use.canvasScale();
  const shiftKeyState = useKeyboardStore((state) => state.shiftKeyState);

  const viewportRatio = useCanvasStore.use.viewportRatio();
  const viewportSize = useCanvasStore.use.viewportSize();
  const updateSlide = useCanvasOperations().updateSlide;

  const { addHistorySnapshot } = useHistorySnapshot();

  const dragElement = useCallback(
    (e: React.MouseEvent | React.TouchEvent, element: PPTElement) => {
      const native = e.nativeEvent;
      const isTouchEvent = native instanceof TouchEvent;
      if (isTouchEvent && !native.changedTouches?.length) return;

      if (!activeElementIdList.includes(element.id)) return;

      let isMouseDown = true;
      const edgeWidth = viewportSize;
      const edgeHeight = viewportSize * viewportRatio;

      const sorptionRange = 5;

      // Save original element list for computing multi-select offsets
      const originElementList: PPTElement[] = JSON.parse(JSON.stringify(elementListRef.current));
      const originActiveElementList = originElementList.filter((el) =>
        activeElementIdList.includes(el.id),
      );

      const elOriginLeft = element.left;
      const elOriginTop = element.top;
      const elOriginWidth = element.width;
      const elOriginHeight = 'height' in element && element.height ? element.height : 0;
      const elOriginRotate = 'rotate' in element && element.rotate ? element.rotate : 0;

      const startPageX = isTouchEvent ? native.changedTouches[0].pageX : native.pageX;
      const startPageY = isTouchEvent ? native.changedTouches[0].pageY : native.pageY;

      let isMisoperation: boolean | null = null;

      const isActiveGroupElement = element.id === activeGroupElementId;

      // Collect alignment snap lines
      // Includes snap positions of other elements on canvas (excluding the target): top/bottom/left/right edges, horizontal/vertical centers
      // Lines and rotated elements need their bounding ranges recalculated
      let horizontalLines: AlignLine[] = [];
      let verticalLines: AlignLine[] = [];

      for (const el of elementListRef.current) {
        if (el.type === 'line') continue;
        if (isActiveGroupElement && el.id === element.id) continue;
        if (!isActiveGroupElement && activeElementIdList.includes(el.id)) continue;

        let left, top, width, height;
        if ('rotate' in el && el.rotate) {
          const { xRange, yRange } = getRectRotatedRange({
            left: el.left,
            top: el.top,
            width: el.width,
            height: el.height,
            rotate: el.rotate,
          });
          left = xRange[0];
          top = yRange[0];
          width = xRange[1] - xRange[0];
          height = yRange[1] - yRange[0];
        } else {
          left = el.left;
          top = el.top;
          width = el.width;
          height = el.height;
        }

        const right = left + width;
        const bottom = top + height;
        const centerX = top + height / 2;
        const centerY = left + width / 2;

        const topLine: AlignLine = { value: top, range: [left, right] };
        const bottomLine: AlignLine = { value: bottom, range: [left, right] };
        const horizontalCenterLine: AlignLine = {
          value: centerX,
          range: [left, right],
        };
        const leftLine: AlignLine = { value: left, range: [top, bottom] };
        const rightLine: AlignLine = { value: right, range: [top, bottom] };
        const verticalCenterLine: AlignLine = {
          value: centerY,
          range: [top, bottom],
        };

        horizontalLines.push(topLine, bottomLine, horizontalCenterLine);
        verticalLines.push(leftLine, rightLine, verticalCenterLine);
      }

      // Canvas viewport edges: four boundaries, horizontal center, vertical center
      const edgeTopLine: AlignLine = { value: 0, range: [0, edgeWidth] };
      const edgeBottomLine: AlignLine = {
        value: edgeHeight,
        range: [0, edgeWidth],
      };
      const edgeHorizontalCenterLine: AlignLine = {
        value: edgeHeight / 2,
        range: [0, edgeWidth],
      };
      const edgeLeftLine: AlignLine = { value: 0, range: [0, edgeHeight] };
      const edgeRightLine: AlignLine = {
        value: edgeWidth,
        range: [0, edgeHeight],
      };
      const edgeVerticalCenterLine: AlignLine = {
        value: edgeWidth / 2,
        range: [0, edgeHeight],
      };

      horizontalLines.push(edgeTopLine, edgeBottomLine, edgeHorizontalCenterLine);
      verticalLines.push(edgeLeftLine, edgeRightLine, edgeVerticalCenterLine);

      // Deduplicate alignment snap lines
      horizontalLines = uniqAlignLines(horizontalLines);
      verticalLines = uniqAlignLines(verticalLines);

      const handleMouseMove = (e: MouseEvent | TouchEvent) => {
        const currentPageX = e instanceof MouseEvent ? e.pageX : e.changedTouches[0].pageX;
        const currentPageY = e instanceof MouseEvent ? e.pageY : e.changedTouches[0].pageY;

        // If mouse movement is too small, consider it a misoperation:
        // null = first move, need to check; true = still in misoperation range; false = moved beyond range
        if (isMisoperation !== false) {
          isMisoperation =
            Math.abs(startPageX - currentPageX) < sorptionRange &&
            Math.abs(startPageY - currentPageY) < sorptionRange;
        }
        if (!isMouseDown || isMisoperation) return;

        let moveX = (currentPageX - startPageX) / canvasScale;
        let moveY = (currentPageY - startPageY) / canvasScale;

        // Lock to horizontal or vertical direction when Shift is held
        if (shiftKeyState) {
          if (Math.abs(moveX) > Math.abs(moveY)) moveY = 0;
          if (Math.abs(moveX) < Math.abs(moveY)) moveX = 0;
        }

        // Base target position
        let targetLeft = elOriginLeft + moveX;
        let targetTop = elOriginTop + moveY;

        // Calculate target element's bounding range on canvas for alignment snapping
        // Must distinguish single-select vs multi-select; single-select further distinguishes line, normal, and rotated elements
        let targetMinX: number, targetMaxX: number, targetMinY: number, targetMaxY: number;

        if (activeElementIdList.length === 1 || isActiveGroupElement) {
          if (elOriginRotate) {
            const { xRange, yRange } = getRectRotatedRange({
              left: targetLeft,
              top: targetTop,
              width: elOriginWidth,
              height: elOriginHeight,
              rotate: elOriginRotate,
            });
            targetMinX = xRange[0];
            targetMaxX = xRange[1];
            targetMinY = yRange[0];
            targetMaxY = yRange[1];
          } else if (element.type === 'line') {
            targetMinX = targetLeft;
            targetMaxX = targetLeft + Math.max(element.start[0], element.end[0]);
            targetMinY = targetTop;
            targetMaxY = targetTop + Math.max(element.start[1], element.end[1]);
          } else {
            targetMinX = targetLeft;
            targetMaxX = targetLeft + elOriginWidth;
            targetMinY = targetTop;
            targetMaxY = targetTop + elOriginHeight;
          }
        } else {
          const leftValues = [];
          const topValues = [];
          const rightValues = [];
          const bottomValues = [];

          for (let i = 0; i < originActiveElementList.length; i++) {
            const element = originActiveElementList[i];
            const left = element.left + moveX;
            const top = element.top + moveY;
            const width = element.width;
            const height = 'height' in element && element.height ? element.height : 0;
            const rotate = 'rotate' in element && element.rotate ? element.rotate : 0;

            if ('rotate' in element && element.rotate) {
              const { xRange, yRange } = getRectRotatedRange({
                left,
                top,
                width,
                height,
                rotate,
              });
              leftValues.push(xRange[0]);
              topValues.push(yRange[0]);
              rightValues.push(xRange[1]);
              bottomValues.push(yRange[1]);
            } else if (element.type === 'line') {
              leftValues.push(left);
              topValues.push(top);
              rightValues.push(left + Math.max(element.start[0], element.end[0]));
              bottomValues.push(top + Math.max(element.start[1], element.end[1]));
            } else {
              leftValues.push(left);
              topValues.push(top);
              rightValues.push(left + width);
              bottomValues.push(top + height);
            }
          }

          targetMinX = Math.min(...leftValues);
          targetMaxX = Math.max(...rightValues);
          targetMinY = Math.min(...topValues);
          targetMaxY = Math.max(...bottomValues);
        }

        const targetCenterX = targetMinX + (targetMaxX - targetMinX) / 2;
        const targetCenterY = targetMinY + (targetMaxY - targetMinY) / 2;

        // Compare alignment snap lines with target position; auto-correct when difference is within threshold
        // Horizontal and vertical directions are calculated separately
        const _alignmentLines: AlignmentLineProps[] = [];
        let isVerticalAdsorbed = false;
        let isHorizontalAdsorbed = false;

        for (let i = 0; i < horizontalLines.length; i++) {
          const { value, range } = horizontalLines[i];
          const min = Math.min(...range, targetMinX, targetMaxX);
          const max = Math.max(...range, targetMinX, targetMaxX);

          if (Math.abs(targetMinY - value) < sorptionRange && !isHorizontalAdsorbed) {
            targetTop = targetTop - (targetMinY - value);
            isHorizontalAdsorbed = true;
            _alignmentLines.push({
              type: 'horizontal',
              axis: { x: min - 50, y: value },
              length: max - min + 100,
            });
          }
          if (Math.abs(targetMaxY - value) < sorptionRange && !isHorizontalAdsorbed) {
            targetTop = targetTop - (targetMaxY - value);
            isHorizontalAdsorbed = true;
            _alignmentLines.push({
              type: 'horizontal',
              axis: { x: min - 50, y: value },
              length: max - min + 100,
            });
          }
          if (Math.abs(targetCenterY - value) < sorptionRange && !isHorizontalAdsorbed) {
            targetTop = targetTop - (targetCenterY - value);
            isHorizontalAdsorbed = true;
            _alignmentLines.push({
              type: 'horizontal',
              axis: { x: min - 50, y: value },
              length: max - min + 100,
            });
          }
        }

        for (let i = 0; i < verticalLines.length; i++) {
          const { value, range } = verticalLines[i];
          const min = Math.min(...range, targetMinY, targetMaxY);
          const max = Math.max(...range, targetMinY, targetMaxY);

          if (Math.abs(targetMinX - value) < sorptionRange && !isVerticalAdsorbed) {
            targetLeft = targetLeft - (targetMinX - value);
            isVerticalAdsorbed = true;
            _alignmentLines.push({
              type: 'vertical',
              axis: { x: value, y: min - 50 },
              length: max - min + 100,
            });
          }
          if (Math.abs(targetMaxX - value) < sorptionRange && !isVerticalAdsorbed) {
            targetLeft = targetLeft - (targetMaxX - value);
            isVerticalAdsorbed = true;
            _alignmentLines.push({
              type: 'vertical',
              axis: { x: value, y: min - 50 },
              length: max - min + 100,
            });
          }
          if (Math.abs(targetCenterX - value) < sorptionRange && !isVerticalAdsorbed) {
            targetLeft = targetLeft - (targetCenterX - value);
            isVerticalAdsorbed = true;
            _alignmentLines.push({
              type: 'vertical',
              axis: { x: value, y: min - 50 },
              length: max - min + 100,
            });
          }
        }

        setAlignmentLines(_alignmentLines);
        let newElements: PPTElement[];

        // In single-select mode or when the active group element is being operated, only update that element's position
        if (activeElementIdList.length === 1 || isActiveGroupElement) {
          newElements = elementListRef.current.map((el) => {
            if (el.id === element.id) {
              return { ...el, left: targetLeft, top: targetTop };
            }
            return el;
          });
        }
        // In multi-select mode, also update positions of other selected elements
        // Their positions are calculated from the movement offset of the handle element
        else {
          const handleElement = elementListRef.current.find((el) => el.id === element.id);
          if (!handleElement) return;

          newElements = elementListRef.current.map((el) => {
            if (activeElementIdList.includes(el.id)) {
              if (el.id === element.id) {
                return { ...el, left: targetLeft, top: targetTop };
              }
              return {
                ...el,
                left: el.left + (targetLeft - handleElement.left),
                top: el.top + (targetTop - handleElement.top),
              };
            }
            return el;
          });
        }

        // Update both ref (latest value) and state (trigger re-render)
        elementListRef.current = newElements;
        setElementList(newElements);
      };

      const handleMouseUp = (e: MouseEvent | TouchEvent) => {
        isMouseDown = false;

        document.ontouchmove = null;
        document.ontouchend = null;
        document.onmousemove = null;
        document.onmouseup = null;

        setAlignmentLines([]);

        const currentPageX = e instanceof MouseEvent ? e.pageX : e.changedTouches[0].pageX;
        const currentPageY = e instanceof MouseEvent ? e.pageY : e.changedTouches[0].pageY;

        if (startPageX === currentPageX && startPageY === currentPageY) return;

        updateSlide({ elements: elementListRef.current });
        addHistorySnapshot();
      };

      if (isTouchEvent) {
        document.ontouchmove = handleMouseMove;
        document.ontouchend = handleMouseUp;
      } else {
        document.onmousemove = handleMouseMove;
        document.onmouseup = handleMouseUp;
      }
    },
    [
      activeElementIdList,
      activeGroupElementId,
      shiftKeyState,
      canvasScale,
      elementListRef,
      setElementList,
      setAlignmentLines,
      updateSlide,
      addHistorySnapshot,
      viewportRatio,
      viewportSize,
    ],
  );

  return {
    dragElement,
  };
}