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
import type React from "react";
import { Path } from "react-konva";
import type { BezierPoint } from "../types";
import chroma from "chroma-js";
import type { KonvaEventObject } from "konva/lib/Node";
 
interface VectorShapeProps {
  segments: Array<{ from: BezierPoint; to: BezierPoint }>;
  allowClose?: boolean;
  isPathClosed?: boolean;
  stroke?: string;
  fill?: string;
  strokeWidth?: number;
  opacity?: number;
  transform?: { zoom: number; offsetX: number; offsetY: number };
  fitScale?: number;
  onClick?: (e: KonvaEventObject<MouseEvent>) => void;
  onMouseEnter?: (e: any) => void;
  onMouseLeave?: (e: any) => void;
  onMouseDown?: (e: KonvaEventObject<MouseEvent>) => void;
  onMouseMove?: (e: KonvaEventObject<MouseEvent>) => void;
  onMouseUp?: (e: KonvaEventObject<MouseEvent>) => void;
}
 
// Convert Bezier segments to SVG path data for a single continuous path
function segmentsToPathData(
  segments: Array<{ from: BezierPoint; to: BezierPoint }>,
  allowClose: boolean,
  isPathClosed: boolean,
): string {
  if (segments.length === 0) return "";
 
  let pathData = "";
 
  // Start with the first point
  const firstSegment = segments[0];
  pathData += `M ${firstSegment.from.x} ${firstSegment.from.y}`;
 
  // Add each segment
  for (let i = 0; i < segments.length; i++) {
    const segment = segments[i];
    const { from, to } = segment;
 
    if (from.isBezier && from.controlPoint2 && to.isBezier && to.controlPoint1) {
      // Full Bezier curve
      pathData += ` C ${from.controlPoint2.x} ${from.controlPoint2.y}, ${to.controlPoint1.x} ${to.controlPoint1.y}, ${to.x} ${to.y}`;
    } else if (from.isBezier && from.controlPoint2) {
      // Partial Bezier curve - only from point has control point
      const dx = to.x - from.x;
      const dy = to.y - from.y;
      const controlX = to.x - dx * 0.3;
      const controlY = to.y - dy * 0.3;
      pathData += ` C ${from.controlPoint2.x} ${from.controlPoint2.y}, ${controlX} ${controlY}, ${to.x} ${to.y}`;
    } else if (to.isBezier && to.controlPoint1) {
      // Partial Bezier curve - only to point has control point
      const dx = to.x - from.x;
      const dy = to.y - from.y;
      const controlX = from.x + dx * 0.3;
      const controlY = from.y + dy * 0.3;
      pathData += ` C ${controlX} ${controlY}, ${to.controlPoint1.x} ${to.controlPoint1.y}, ${to.x} ${to.y}`;
    } else {
      // Straight line
      pathData += ` L ${to.x} ${to.y}`;
    }
  }
 
  // Close the path if needed
  if (allowClose && isPathClosed && segments.length > 0) {
    pathData += " Z";
  }
 
  return pathData;
}
 
// Group segments into connected paths for skeleton mode
function groupSegmentsIntoPaths(
  segments: Array<{ from: BezierPoint; to: BezierPoint }>,
): Array<Array<{ from: BezierPoint; to: BezierPoint }>> {
  if (segments.length === 0) return [];
 
  const paths: Array<Array<{ from: BezierPoint; to: BezierPoint }>> = [];
  const usedSegments = new Set<number>();
 
  for (let i = 0; i < segments.length; i++) {
    if (usedSegments.has(i)) continue;
 
    const currentPath: Array<{ from: BezierPoint; to: BezierPoint }> = [];
    const pathPoints = new Set<string>();
 
    // Start with this segment
    currentPath.push(segments[i]);
    pathPoints.add(segments[i].from.id);
    pathPoints.add(segments[i].to.id);
    usedSegments.add(i);
 
    // Find all connected segments
    let foundMore = true;
    while (foundMore) {
      foundMore = false;
      for (let j = 0; j < segments.length; j++) {
        if (usedSegments.has(j)) continue;
 
        const segment = segments[j];
        // Check if this segment connects to our current path
        if (pathPoints.has(segment.from.id) || pathPoints.has(segment.to.id)) {
          currentPath.push(segment);
          pathPoints.add(segment.from.id);
          pathPoints.add(segment.to.id);
          usedSegments.add(j);
          foundMore = true;
        }
      }
    }
 
    // Sort segments within each path to ensure they form a continuous sequence
    const sortedPath = sortSegmentsForContinuousPath(currentPath);
    paths.push(sortedPath);
  }
 
  return paths;
}
 
// Sort segments to form a continuous path
function sortSegmentsForContinuousPath(
  segments: Array<{ from: BezierPoint; to: BezierPoint }>,
): Array<{ from: BezierPoint; to: BezierPoint }> {
  if (segments.length <= 1) return segments;
 
  const sorted: Array<{ from: BezierPoint; to: BezierPoint }> = [];
  const remaining = new Set(segments);
 
  // Start with the first segment
  let currentSegment = segments[0];
  sorted.push(currentSegment);
  remaining.delete(currentSegment);
 
  // Find the next segment that connects to the current one
  while (remaining.size > 0) {
    let foundNext = false;
 
    for (const segment of remaining) {
      // Check if this segment connects to the end of our current path
      if (segment.from.id === currentSegment.to.id) {
        sorted.push(segment);
        remaining.delete(segment);
        currentSegment = segment;
        foundNext = true;
        break;
      }
 
      // Check if this segment connects to the beginning of our current path (reverse it)
      // Reverse the segment to connect properly
      const reversedSegment = { from: segment.to, to: segment.from };
      sorted.unshift(reversedSegment);
      remaining.delete(segment);
      currentSegment = reversedSegment;
      foundNext = true;
      break;
    }
 
    // If we can't find a direct connection, look for any connection
    if (!foundNext) {
      for (const segment of remaining) {
        if (
          segment.from.id === currentSegment.to.id ||
          segment.to.id === currentSegment.to.id ||
          segment.from.id === currentSegment.from.id ||
          segment.to.id === currentSegment.from.id
        ) {
          // If it connects to the end, add it normally
          if (segment.from.id === currentSegment.to.id) {
            sorted.push(segment);
          }
          // If it connects to the end but reversed, reverse it
          else if (segment.to.id === currentSegment.to.id) {
            const reversedSegment = { from: segment.to, to: segment.from };
            sorted.push(reversedSegment);
          }
          // If it connects to the beginning, add it at the start
          else if (segment.to.id === currentSegment.from.id) {
            sorted.unshift(segment);
          }
          // If it connects to the beginning but reversed, reverse it and add at start
          else if (segment.from.id === currentSegment.from.id) {
            const reversedSegment = { from: segment.to, to: segment.from };
            sorted.unshift(reversedSegment);
          }
 
          remaining.delete(segment);
          currentSegment = sorted[sorted.length - 1]; // Update current segment to the last one
          foundNext = true;
          break;
        }
      }
    }
 
    // If we still can't find a connection, just add the remaining segments as separate paths
    if (!foundNext) {
      break;
    }
  }
 
  // Add any remaining segments as separate paths (these will be handled by the main grouping function)
  return sorted;
}
 
export const VectorShape: React.FC<VectorShapeProps> = ({
  segments,
  allowClose = false,
  isPathClosed = false,
  stroke = "#3b82f6",
  fill = "rgba(239, 68, 68, 0.3)",
  strokeWidth = 2,
  opacity = 1,
  transform = { zoom: 1, offsetX: 0, offsetY: 0 },
  fitScale = 1,
  onClick,
  onMouseEnter,
  onMouseLeave,
  onMouseDown,
  onMouseMove,
  onMouseUp,
}) => {
  if (segments.length === 0) return null;
 
  const effectiveZoom = transform.zoom * fitScale;
 
  // For skeleton mode, render each segment as a separate line to avoid path ordering issues
  // For non-skeleton mode, use the grouped path approach
  const isSkeletonMode = segments.some((segment) => {
    // Check if we have branching (multiple segments with the same from point)
    const fromPoints = segments.map((s) => s.from.id);
    const uniqueFromPoints = new Set(fromPoints);
    return fromPoints.length !== uniqueFromPoints.size;
  });
 
  if (isSkeletonMode) {
    // Render each segment as a separate line
    return (
      <>
        {segments.map((segment, index) => {
          const { from, to } = segment;
 
          // Create a simple line path for each segment
          let pathData = `M ${from.x} ${from.y}`;
 
          if (from.isBezier && from.controlPoint2 && to.isBezier && to.controlPoint1) {
            // Full Bezier curve
            pathData += ` C ${from.controlPoint2.x} ${from.controlPoint2.y}, ${to.controlPoint1.x} ${to.controlPoint1.y}, ${to.x} ${to.y}`;
          } else if (from.isBezier && from.controlPoint2) {
            // Partial Bezier curve - only from point has control point
            const dx = to.x - from.x;
            const dy = to.y - from.y;
            const controlX = to.x - dx * 0.3;
            const controlY = to.y - dy * 0.3;
            pathData += ` C ${from.controlPoint2.x} ${from.controlPoint2.y}, ${controlX} ${controlY}, ${to.x} ${to.y}`;
          } else if (to.isBezier && to.controlPoint1) {
            // Partial Bezier curve - only to point has control point
            const dx = to.x - from.x;
            const dy = to.y - from.y;
            const controlX = from.x + dx * 0.3;
            const controlY = from.y + dy * 0.3;
            pathData += ` C ${controlX} ${controlY}, ${to.controlPoint1.x} ${to.controlPoint1.y}, ${to.x} ${to.y}`;
          } else {
            // Straight line
            pathData += ` L ${to.x} ${to.y}`;
          }
 
          return (
            <Path
              key={`segment-${index}`}
              data={pathData}
              stroke={stroke}
              strokeWidth={2}
              strokeScaleEnabled={false}
              fill={undefined} // No fill for individual segments
              hitStrokeWidth={20}
              onClick={onClick}
              onMouseEnter={onMouseEnter}
              onMouseLeave={onMouseLeave}
              onMouseDown={onMouseDown}
              onMouseMove={onMouseMove}
              onMouseUp={onMouseUp}
            />
          );
        })}
      </>
    );
  }
  // Use the grouped path approach for non-skeleton mode
  const pathGroups = groupSegmentsIntoPaths(segments);
 
  return (
    <>
      {pathGroups.map((pathSegments, index) => {
        const pathData = segmentsToPathData(pathSegments, allowClose, isPathClosed);
 
        // Apply opacity only to fill color using chroma.js
        const fillWithOpacity = allowClose && isPathClosed && fill ? chroma(fill).alpha(opacity).css() : undefined;
 
        return (
          <Path
            key={`path-${index}`}
            data={pathData}
            stroke={stroke}
            strokeWidth={strokeWidth}
            strokeScaleEnabled={false}
            fill={fillWithOpacity}
            hitStrokeWidth={20}
            onClick={onClick}
            onMouseEnter={onMouseEnter}
            onMouseLeave={onMouseLeave}
            onMouseDown={onMouseDown}
            onMouseMove={onMouseMove}
            onMouseUp={onMouseUp}
          />
        );
      })}
    </>
  );
};