Bin
2025-12-16 9e0b2ba2c317b1a86212f24cbae3195ad1f3dbfa
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
import type { BezierPoint } from "../types";
import type { EventHandlerProps } from "./types";
import { getClosestPointOnLine, getClosestPointOnBezierCurve } from "../utils";
import { addBezierPoint } from "./drawing";
 
// Convert stage coordinates to image coordinates
export function stageToImageCoordinates(
  stagePos: { x: number; y: number },
  transform: { zoom: number; offsetX: number; offsetY: number },
  fitScale: number,
  x: number,
  y: number,
): { x: number; y: number } {
  const scale = transform.zoom * fitScale;
  return {
    x: (stagePos.x - x - transform.offsetX) / scale,
    y: (stagePos.y - y - transform.offsetY) / scale,
  };
}
 
// Check if a point is within canvas bounds
export function isPointInCanvasBounds(point: { x: number; y: number }, width: number, height: number): boolean {
  return point.x >= 0 && point.y >= 0 && point.x <= width && point.y <= height;
}
 
// Snap coordinates to pixel grid
export function snapToPixel(point: { x: number; y: number }, enabled = false) {
  if (!enabled) return point;
 
  return {
    x: Math.round(point.x),
    y: Math.round(point.y),
  };
}
 
// Calculate distance between two points
export function getDistance(point1: { x: number; y: number }, point2: { x: number; y: number }): number {
  return Math.sqrt((point1.x - point2.x) ** 2 + (point1.y - point2.y) ** 2);
}
 
// Check if a point is within hit radius of another point
export function isPointInHitRadius(
  point: { x: number; y: number },
  target: { x: number; y: number },
  hitRadius: number,
): boolean {
  return getDistance(point, target) <= hitRadius;
}
 
// Find the closest point on the path to a given cursor position
export function findClosestPointOnPath(
  cursorPos: { x: number; y: number },
  points: BezierPoint[],
  allowClose?: boolean,
  isPathClosed?: boolean,
): { point: { x: number; y: number }; segmentIndex: number } | null {
  if (points.length < 2) return null;
 
  let closestPoint = { x: 0, y: 0 };
  let closestDistance = Number.POSITIVE_INFINITY;
  let closestSegmentIndex = 0;
 
  // Create a map for quick point lookup
  const pointMap = new Map<string, BezierPoint>();
  for (const point of points) {
    pointMap.set(point.id, point);
  }
 
  // Check each segment
  for (let i = 0; i < points.length; i++) {
    const point = points[i];
    if (!point.prevPointId) continue;
 
    const prevPoint = pointMap.get(point.prevPointId);
    if (!prevPoint) continue;
 
    let segmentClosestPoint: { x: number; y: number };
 
    // Replicate the exact rendering logic from PolylineShape
    if (prevPoint.isBezier && prevPoint.controlPoint2 && point.isBezier && point.controlPoint1) {
      // Full Bezier curve - both points have control points
      segmentClosestPoint = getClosestPointOnBezierCurve(
        cursorPos,
        prevPoint,
        prevPoint.controlPoint2,
        point.controlPoint1,
        point,
      );
    } else if (prevPoint.isBezier && prevPoint.controlPoint2) {
      // Partial Bezier curve - only prevPoint has controlPoint2
      const dx = point.x - prevPoint.x;
      const dy = point.y - prevPoint.y;
      const controlX = point.x - dx * 0.3;
      const controlY = point.y - dy * 0.3;
      segmentClosestPoint = getClosestPointOnBezierCurve(
        cursorPos,
        prevPoint,
        prevPoint.controlPoint2,
        { x: controlX, y: controlY },
        point,
      );
    } else if (point.isBezier && point.controlPoint1) {
      // Partial Bezier curve - only current point has controlPoint1
      const dx = point.x - prevPoint.x;
      const dy = point.y - prevPoint.y;
      const controlX = prevPoint.x + dx * 0.3;
      const controlY = prevPoint.y + dy * 0.3;
      segmentClosestPoint = getClosestPointOnBezierCurve(
        cursorPos,
        prevPoint,
        { x: controlX, y: controlY },
        point.controlPoint1,
        point,
      );
    } else {
      // Straight line
      segmentClosestPoint = getClosestPointOnLine(cursorPos, prevPoint, point);
    }
 
    const distance = getDistance(cursorPos, segmentClosestPoint);
 
    if (distance < closestDistance) {
      closestDistance = distance;
      closestPoint = segmentClosestPoint;
      closestSegmentIndex = i;
    }
  }
 
  // Check closing segment if path is closed
  // Allow closing if we have more than 2 points or at least one bezier point
  const canClosePath = () => {
    // Allow closing if we have more than 2 points
    if (points.length > 2) {
      return true;
    }
 
    // Allow closing if we have at least one bezier point
    const hasBezierPoint = points.some((point) => point.isBezier);
    if (hasBezierPoint) {
      return true;
    }
 
    return false;
  };
 
  if (allowClose && isPathClosed && canClosePath()) {
    const lastPoint = points[points.length - 1];
    const firstPoint = points[0];
 
    let segmentClosestPoint: { x: number; y: number };
 
    // Replicate the exact rendering logic from PolylineShape for closing segment
    if (lastPoint.isBezier && lastPoint.controlPoint2 && firstPoint.isBezier && firstPoint.controlPoint1) {
      // Full Bezier curve - both points have control points
      segmentClosestPoint = getClosestPointOnBezierCurve(
        cursorPos,
        lastPoint,
        lastPoint.controlPoint2,
        firstPoint.controlPoint1,
        firstPoint,
      );
    } else if (lastPoint.isBezier && lastPoint.controlPoint2) {
      // Partial Bezier curve - only lastPoint has controlPoint2
      const dx = firstPoint.x - lastPoint.x;
      const dy = firstPoint.y - lastPoint.y;
      const controlX = firstPoint.x - dx * 0.3;
      const controlY = firstPoint.y - dy * 0.3;
      segmentClosestPoint = getClosestPointOnBezierCurve(
        cursorPos,
        lastPoint,
        lastPoint.controlPoint2,
        { x: controlX, y: controlY },
        firstPoint,
      );
    } else if (firstPoint.isBezier && firstPoint.controlPoint1) {
      // Partial Bezier curve - only firstPoint has controlPoint1
      const dx = firstPoint.x - lastPoint.x;
      const dy = firstPoint.y - lastPoint.y;
      const controlX = lastPoint.x + dx * 0.3;
      const controlY = lastPoint.y + dy * 0.3;
      segmentClosestPoint = getClosestPointOnBezierCurve(
        cursorPos,
        lastPoint,
        { x: controlX, y: controlY },
        firstPoint.controlPoint1,
        firstPoint,
      );
    } else {
      // Straight line
      segmentClosestPoint = getClosestPointOnLine(cursorPos, lastPoint, firstPoint);
    }
 
    const distance = getDistance(cursorPos, segmentClosestPoint);
    if (distance < closestDistance) {
      closestDistance = distance;
      closestPoint = segmentClosestPoint;
      closestSegmentIndex = points.length; // Use points.length to indicate closing segment
    }
  }
 
  // Only return if we're within a reasonable distance (e.g., 50 pixels)
  const maxSnapDistance = 50;
  if (closestDistance <= maxSnapDistance) {
    return {
      point: closestPoint,
      segmentIndex: closestSegmentIndex,
    };
  }
 
  return null;
}
 
/**
 * Calculate the distance from a point to a line segment
 */
export function distanceToLineSegment(
  point: { x: number; y: number },
  lineStart: { x: number; y: number },
  lineEnd: { x: number; y: number },
): number {
  const A = point.x - lineStart.x;
  const B = point.y - lineStart.y;
  const C = lineEnd.x - lineStart.x;
  const D = lineEnd.y - lineStart.y;
 
  const dot = A * C + B * D;
  const lenSq = C * C + D * D;
  let param = -1;
 
  if (lenSq !== 0) {
    param = dot / lenSq;
  }
 
  let xx: number;
  let yy: number;
 
  if (param < 0) {
    xx = lineStart.x;
    yy = lineStart.y;
  } else if (param > 1) {
    xx = lineEnd.x;
    yy = lineEnd.y;
  } else {
    xx = lineStart.x + param * C;
    yy = lineStart.y + param * D;
  }
 
  const dx = point.x - xx;
  const dy = point.y - yy;
 
  return Math.sqrt(dx * dx + dy * dy);
}
 
// Shared utility for handling bezier point creation during drag operations
export function handleBezierDragCreation(
  props: EventHandlerProps,
  startPos: { x: number; y: number },
  handledSelectionInMouseDown: { current: boolean },
): boolean {
  // Check if bezier is allowed
  if (!props.allowBezier) {
    return false;
  }
 
  // Create the bezier point immediately at the starting position
  const startImagePos = stageToImageCoordinates(startPos, props.transform, props.fitScale, props.x, props.y);
 
  // Create bezier point with initial control points
  const newPointIndex = props.initialPoints.length;
  const result = addBezierPoint(props, startImagePos.x, startImagePos.y);
  if (result) {
    // Store the index of the newly created bezier point
    props.setNewPointDragIndex(newPointIndex);
    // Set dragging state for bezier control point manipulation
    props.setIsDraggingNewBezier(true);
    // Mark that we've handled this interaction to prevent click handler from running
    handledSelectionInMouseDown.current = true;
    return true;
  }
  return false;
}
 
// Shared utility for continuing bezier drag (updating control points)
export function continueBezierDrag(props: EventHandlerProps): void {
  if (props.newPointDragIndex !== null && props.cursorPosition) {
    const bezierPointIndex = props.newPointDragIndex;
    const newPoints = [...props.initialPoints];
    const bezierPoint = newPoints[bezierPointIndex];
 
    if (bezierPoint && bezierPoint.isBezier && props.cursorPosition) {
      // Keep the bezier point at its original position (where the drag started)
      // Only update the control points to follow the cursor
 
      // Calculate the drag vector from the bezier point to current cursor
      const dragVectorX = props.cursorPosition.x - bezierPoint.x;
      const dragVectorY = props.cursorPosition.y - bezierPoint.y;
 
      // Calculate the distance from the bezier point to the cursor
      const controlDistance = Math.sqrt(dragVectorX * dragVectorX + dragVectorY * dragVectorY);
 
      // Normalize the drag vector
      const normalizedDragX = dragVectorX / controlDistance;
      const normalizedDragY = dragVectorY / controlDistance;
 
      // Create control points with pixel snapping
      const controlPoint1Pos = {
        x: bezierPoint.x + normalizedDragX * controlDistance,
        y: bezierPoint.y + normalizedDragY * controlDistance,
      };
      const controlPoint2Pos = {
        x: bezierPoint.x - normalizedDragX * controlDistance,
        y: bezierPoint.y - normalizedDragY * controlDistance,
      };
 
      const snappedControlPoint1 = snapToPixel(controlPoint1Pos, props.pixelSnapping);
      const snappedControlPoint2 = snapToPixel(controlPoint2Pos, props.pixelSnapping);
 
      // Create a new point object with updated control points
      newPoints[bezierPointIndex] = {
        ...bezierPoint,
        controlPoint1: {
          x: snappedControlPoint1.x,
          y: snappedControlPoint1.y,
        },
        controlPoint2: {
          x: snappedControlPoint2.x,
          y: snappedControlPoint2.y,
        },
      };
 
      // Update the points
      props.onPointsChange?.(newPoints);
      props.onPointEdited?.(newPoints[bezierPointIndex], bezierPointIndex);
    }
  }
}