Repository navigation
Expand file tree
/
Copy patheditor-transform.js
More file actions
1991 lines (1714 loc) · 81.6 KB
/
Copy patheditor-transform.js
File metadata and controls
1991 lines (1714 loc) · 81.6 KB
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* VectorCutter - SVG Editor Module
* Module: editor-transform.js
* Description: Transformation, Resize, Rotation, Scaling, Mirroring/Flipping & Movement
*/
Object.assign(SVGEditor.prototype, {
startResizing(handleType, clientX, clientY) {
this.isResizing = true;
this.resizeHandleType = handleType;
this.initialMouseX = clientX;
this.initialMouseY = clientY;
// Capture SVG initial mouse for snapping delta calc
this.initialMouseSVG = this.screenToSVG(clientX, clientY);
this.initialElementStates = this.selectedElements.map(element =>
this.getElementState(element)
);
this.initialGroupBbox = this.getGroupBoundingBox();
this.initialSelectionBox = {
x: this.selectionRect?.getAttribute('x') || 0,
y: this.selectionRect?.getAttribute('y') || 0,
width: this.selectionRect?.getAttribute('width') || 0,
height: this.selectionRect?.getAttribute('height') || 0
};
if (this.selectedElements.length === 1) {
const element = this.selectedElements[0];
const tagName = element.tagName;
if (tagName === 'rect') {
const bbox = element.getBBox();
this.resizeInfo = {
nw: { x: bbox.x, y: bbox.y },
ne: { x: bbox.x + bbox.width, y: bbox.y },
sw: { x: bbox.x, y: bbox.y + bbox.height },
se: { x: bbox.x + bbox.width, y: bbox.y + bbox.height }
};
} else if (tagName === 'line') {
const x1 = parseFloat(element.getAttribute('x1') || 0);
const y1 = parseFloat(element.getAttribute('y1') || 0);
const x2 = parseFloat(element.getAttribute('x2') || 0);
const y2 = parseFloat(element.getAttribute('y2') || 0);
const bbox = element.getBBox();
const minX = bbox.x;
const maxX = bbox.x + bbox.width;
const minY = bbox.y;
const maxY = bbox.y + bbox.height;
const endpoint1IsNW = Math.abs(x1 - minX) < 0.1 && Math.abs(y1 - minY) < 0.1;
const endpoint1IsNE = Math.abs(x1 - maxX) < 0.1 && Math.abs(y1 - minY) < 0.1;
const endpoint1IsSW = Math.abs(x1 - minX) < 0.1 && Math.abs(y1 - maxY) < 0.1;
const endpoint1IsSE = Math.abs(x1 - maxX) < 0.1 && Math.abs(y1 - maxY) < 0.1;
this.resizeInfo = {
endpoint1: { x: x1, y: y1 },
endpoint2: { x: x2, y: y2 },
endpoint1IsNW: endpoint1IsNW,
endpoint1IsNE: endpoint1IsNE,
endpoint1IsSW: endpoint1IsSW,
endpoint1IsSE: endpoint1IsSE
};
}
}
},
resizeElement(currentClientX, currentClientY) {
if (this.selectedElements.length === 0 || !this.initialElementStates) return;
// Calculate raw delta in SVG units based on screen movement
const screenDx = currentClientX - this.initialMouseX;
const screenDy = currentClientY - this.initialMouseY;
const rect = this.canvas.getBoundingClientRect();
let svgDx = (screenDx / rect.width) * this.viewBox.width;
let svgDy = (screenDy / rect.height) * this.viewBox.height;
// Handle Snapping for Resize
if (this.snapEnabled) {
// Calculate current unsnapped mouse position in SVG
const unsnappedMouseSVG = {
x: this.initialMouseSVG.x + svgDx,
y: this.initialMouseSVG.y + svgDy
};
// Find snap target for this mouse position
const snap = this.findSnapTarget(unsnappedMouseSVG.x, unsnappedMouseSVG.y, this.selectedElements[0]);
if (snap.snapped) {
// Recalculate deltas to reach the snap point perfectly
svgDx = snap.x - this.initialMouseSVG.x;
svgDy = snap.y - this.initialMouseSVG.y;
}
}
let groupRotation = 0;
if (this.selectedElements.length === 1) {
groupRotation = this.getElementRotation(this.selectedElements[0]);
}
let rawDx = svgDx;
let rawDy = svgDy;
let scaleX = 1;
let scaleY = 1;
if (groupRotation !== 0) {
const rad = -groupRotation * Math.PI / 180;
const localDx = svgDx * Math.cos(rad) - svgDy * Math.sin(rad);
const localDy = svgDx * Math.sin(rad) + svgDy * Math.cos(rad);
rawDx = localDx;
rawDy = localDy;
}
this.selectedElements.forEach((element, index) => {
const initialState = this.initialElementStates[index];
const tagName = element.tagName;
const isStructure = element.getAttribute('data-type') === 'structure'; // NEW CHECK
if (tagName === 'rect') {
this.resizeRectangleNonSymmetric(element, initialState, rawDx, rawDy, this.resizeHandleType);
} else if (isStructure) {
// NEW: Route structures to a rectangle-like resizing logic
this.resizeStructureLikeRectangle(element, initialState, rawDx, rawDy, this.resizeHandleType);
} else if (tagName === 'line') {
this.resizeLineNonSymmetric(element, initialState, rawDx, rawDy, this.resizeHandleType);
} else {
switch(this.resizeHandleType) {
case 'nw':
scaleX = 1 - rawDx / this.initialGroupBbox.width;
scaleY = 1 - rawDy / this.initialGroupBbox.height;
break;
case 'n':
scaleY = 1 - rawDy / this.initialGroupBbox.height;
break;
case 'ne':
scaleX = 1 + rawDx / this.initialGroupBbox.width;
scaleY = 1 - rawDy / this.initialGroupBbox.height;
break;
case 'w':
scaleX = 1 - rawDx / this.initialGroupBbox.width;
break;
case 'e':
scaleX = 1 + rawDx / this.initialGroupBbox.width;
break;
case 'sw':
scaleX = 1 - rawDx / this.initialGroupBbox.width;
scaleY = 1 + rawDy / this.initialGroupBbox.height;
break;
case 's':
scaleY = 1 + rawDy / this.initialGroupBbox.height;
break;
case 'se':
scaleX = 1 + rawDx / this.initialGroupBbox.width;
scaleY = 1 + rawDy / this.initialGroupBbox.height;
break;
}
this.scaleElementRelativeToPoint(element, initialState, scaleX, scaleY,
this.initialGroupBbox.x + this.initialGroupBbox.width/2,
this.initialGroupBbox.y + this.initialGroupBbox.height/2);
}
});
this.updateSelectionHandles();
this.updateContextMenuValues();
},
resizeStructureLikeRectangle(element, initialState, dx, dy, handleType) {
// 1. Get Initial State
const oldTx = initialState.x;
const oldTy = initialState.y;
const oldScaleX = initialState.scaleX || 1;
const oldScaleY = initialState.scaleY || 1;
const rotation = initialState.rotation || 0;
// Local BBox (Unscaled)
const bbox = element.getBBox();
const localX = bbox.x;
const localY = bbox.y;
const localW = bbox.width;
const localH = bbox.height;
// 2. Determine Local Anchor Point (The point opposite to the handle)
let anchorRelX = 0;
let anchorRelY = 0;
switch(handleType) {
case 'nw': anchorRelX = localW; anchorRelY = localH; break; // Anchor SE
case 'n': anchorRelX = localW/2; anchorRelY = localH; break; // Anchor S
case 'ne': anchorRelX = 0; anchorRelY = localH; break; // Anchor SW
case 'w': anchorRelX = localW; anchorRelY = localH/2; break; // Anchor E
case 'e': anchorRelX = 0; anchorRelY = localH/2; break; // Anchor W
case 'sw': anchorRelX = localW; anchorRelY = 0; break; // Anchor NE
case 's': anchorRelX = localW/2; anchorRelY = 0; break; // Anchor N
case 'se': anchorRelX = 0; anchorRelY = 0; break; // Anchor NW
}
// 3. Helper: Map Local Point to Global (accounting for SCALE pivot shift)
const localToGlobal = (relX, relY, tx, ty, sx, sy, rot) => {
// Scaled position relative to top-left of box
const scaledX = relX * sx;
const scaledY = relY * sy;
// Visual Center of the SCALED box
// We must rotate around the SCALED center
const centerX = (localW * sx) / 2;
const centerY = (localH * sy) / 2;
const rad = rot * Math.PI / 180;
const cos = Math.cos(rad);
const sin = Math.sin(rad);
// Rotate point around the scaled center
const dx = scaledX - centerX;
const dy = scaledY - centerY;
const rotatedX = centerX + (dx * cos - dy * sin);
const rotatedY = centerY + (dx * sin + dy * cos);
// Global pos = Origin + (BoxOffset * Scale) + RotatedPoint
return {
x: tx + (localX * sx) + rotatedX,
y: ty + (localY * sy) + rotatedY
};
};
// 4. Calculate Global Anchor (Fixed Point in World Space)
const globalAnchor = localToGlobal(anchorRelX, anchorRelY, oldTx, oldTy, oldScaleX, oldScaleY, rotation);
// 5. Calculate New Visual Size based on Deltas
let dW = 0, dH = 0;
switch(handleType) {
case 'nw': dW = -dx; dH = -dy; break;
case 'n': dH = -dy; break;
case 'ne': dW = dx; dH = -dy; break;
case 'w': dW = -dx; break;
case 'e': dW = dx; break;
case 'sw': dW = -dx; dH = dy; break;
case 's': dH = dy; break;
case 'se': dW = dx; dH = dy; break;
}
const curVisW = localW * oldScaleX;
const curVisH = localH * oldScaleY;
const newVisW = Math.max(1, curVisW + dW);
const newVisH = Math.max(1, curVisH + dH);
// 6. Calculate New Scales
const newScaleX = newVisW / localW;
const newScaleY = newVisH / localH;
// 7. Calculate New Translate (Reverse Engineer)
// Find where the anchor would be if we just scaled/rotated at 0,0
const newAnchorOffset = localToGlobal(anchorRelX, anchorRelY, 0, 0, newScaleX, newScaleY, rotation);
// Shift Translate so the anchor lands on GlobalAnchor
const newTx = globalAnchor.x - newAnchorOffset.x;
const newTy = globalAnchor.y - newAnchorOffset.y;
// 8. Construct Transform
// FIX IS HERE: We must rotate around the SCALED Center
const localCx = localX + localW / 2;
const localCy = localY + localH / 2;
// Scale the rotation pivot coordinates by the new scale
const pivotX = localCx * newScaleX;
const pivotY = localCy * newScaleY;
// Since 'rotate' happens AFTER 'scale' in the transform pipeline,
// the coordinate system is already scaled.
// Wait... SVG applies functions Right-to-Left.
// scale() applies first. The grid expands.
// So 'rotate' needs coordinates in the SCALED grid?
// NO. If the grid expands, 50 becomes 100 on screen.
// If we say rotate(..., 50, 50) it rotates around 100, 100 on screen?
// Actually, explicit <g> transforms are tricky.
// Let's use the explicit order that matches our logic:
// 1. Translate (Global placement)
// 2. Rotate (Around visual center)
// 3. Scale (Size adjustment)
// To rotate around visual center:
// Center is (localCx, localCy).
// After scale(sx, sy), visual center is NOT at localCx, localCy.
// It is at (localCx, localCy) in the *unscaled* system, which maps to *scaled* visual center.
// The previous bug was assuming standard transform order logic applied cleanly.
// Let's use the SCALED pivot logic:
let newTransform = `translate(${newTx}, ${newTy})`;
if (rotation !== 0) {
// We use the SCALED pivot point to keep rotation centered
newTransform += ` rotate(${rotation}, ${localCx * newScaleX}, ${localCy * newScaleY})`;
}
newTransform += ` scale(${newScaleX}, ${newScaleY})`;
element.setAttribute('transform', newTransform);
},
resizeRectangleNonSymmetric(element, initialState, dx, dy, handleType) {
// 1. Calculate delta in dimensions and local position based on handle
let dX = 0;
let dY = 0;
let dW = 0;
let dH = 0;
// dx, dy are already in the local aligned coordinate system
switch(handleType) {
case 'nw': dX = dx; dY = dy; dW = -dx; dH = -dy; break;
case 'n': dY = dy; dH = -dy; break;
case 'ne': dY = dy; dW = dx; dH = -dy; break;
case 'w': dX = dx; dW = -dx; break;
case 'e': dW = dx; break;
case 'sw': dX = dx; dW = -dx; dH = dy; break;
case 's': dH = dy; break;
case 'se': dW = dx; dH = dy; break;
}
// 2. Apply deltas to initial state
let newW = initialState.width + dW;
let newH = initialState.height + dH;
let newX = initialState.x + dX;
let newY = initialState.y + dY;
// Constrain width
if (newW < 0.1) {
const offset = 0.1 - newW;
newW = 0.1;
// If we were moving the left edge ('w', 'nw', 'sw'), adjust X
if (handleType.includes('w')) {
newX -= offset;
}
}
// Constrain height
if (newH < 0.1) {
const offset = 0.1 - newH;
newH = 0.1;
if (handleType.includes('n')) {
newY -= offset;
}
}
// 3. Calculate shifts to maintain world position
const initialCx = initialState.x + initialState.width / 2;
const initialCy = initialState.y + initialState.height / 2;
const newLocalCx = newX + newW / 2;
const newLocalCy = newY + newH / 2;
// Vector from old geometric center to new geometric center (in local space)
const deltaCx = newLocalCx - initialCx;
const deltaCy = newLocalCy - initialCy;
const rotation = initialState.rotation || 0;
// Determine the world pivot point of the initial state
// If the initial transform had an explicit center, use it. Otherwise use geometric center.
const initialPivotX = (initialState.rotationCx !== undefined) ? initialState.rotationCx : initialCx;
const initialPivotY = (initialState.rotationCy !== undefined) ? initialState.rotationCy : initialCy;
// 4. Rotate the delta vector to world space
const rad = rotation * Math.PI / 180;
const cos = Math.cos(rad);
const sin = Math.sin(rad);
const worldDeltaX = deltaCx * cos - deltaCy * sin;
const worldDeltaY = deltaCx * sin + deltaCy * cos;
// 5. Calculate Old Geometric Center in World Space
// We need this because the rotation pivot might not have been the center.
// Vector from Pivot to Center (Local)
const dx_p = initialCx - initialPivotX;
const dy_p = initialCy - initialPivotY;
// Rotate this vector to get world offset from pivot
const oldGeoCenterWorldX = initialPivotX + dx_p * cos - dy_p * sin;
const oldGeoCenterWorldY = initialPivotY + dx_p * sin + dy_p * cos;
// 6. Calculate New Geometric Center in World Space
const newGeoCenterWorldX = oldGeoCenterWorldX + worldDeltaX;
const newGeoCenterWorldY = oldGeoCenterWorldY + worldDeltaY;
// 7. Update attributes
// We position the rect so its center aligns with newGeoCenterWorld
// And we set the rotation pivot TO newGeoCenterWorld.
element.setAttribute('width', newW);
element.setAttribute('height', newH);
element.setAttribute('x', newGeoCenterWorldX - newW / 2);
element.setAttribute('y', newGeoCenterWorldY - newH / 2);
if (rotation !== 0) {
element.setAttribute('transform', `rotate(${rotation}, ${newGeoCenterWorldX}, ${newGeoCenterWorldY})`);
} else {
element.removeAttribute('transform');
}
this.updateContextMenuValues();
}
// New method for non-symmetric line resizing
// Alternative: Edge handles stretch line in one dimension only,
resizeLineNonSymmetric(element, initialState, dx, dy, handleType) {
let x1 = initialState.x1;
let y1 = initialState.y1;
let x2 = initialState.x2;
let y2 = initialState.y2;
// Get line center
const centerX = (x1 + x2) / 2;
const centerY = (y1 + y2) / 2;
// Determine which endpoints are on which sides
const leftEndpoint = x1 <= x2 ? 0 : 1;
const rightEndpoint = x1 >= x2 ? 0 : 1;
const topEndpoint = y1 <= y2 ? 0 : 1;
const bottomEndpoint = y1 >= y2 ? 0 : 1;
switch(handleType) {
case 'nw':
// Move top-left corner
if (leftEndpoint === 0 && topEndpoint === 0) {
x1 += dx;
y1 += dy;
} else if (leftEndpoint === 1 && topEndpoint === 1) {
x2 += dx;
y2 += dy;
}
break;
case 'n':
// STRETCH vertically by moving the top endpoint(s)
// Actually for a line, there's only one top endpoint
if (topEndpoint === 0) {
y1 += dy;
} else {
y2 += dy;
}
break;
case 'ne':
// Move top-right corner
if (rightEndpoint === 0 && topEndpoint === 0) {
x1 += dx;
y1 += dy;
} else if (rightEndpoint === 1 && topEndpoint === 1) {
x2 += dx;
y2 += dy;
}
break;
case 'w':
// STRETCH horizontally by moving the left endpoint
if (leftEndpoint === 0) {
x1 += dx;
} else {
x2 += dx;
}
break;
case 'e':
// STRETCH horizontally by moving the right endpoint
if (rightEndpoint === 0) {
x1 += dx;
} else {
x2 += dx;
}
break;
case 'sw':
// Move bottom-left corner
if (leftEndpoint === 0 && bottomEndpoint === 0) {
x1 += dx;
y1 += dy;
} else if (leftEndpoint === 1 && bottomEndpoint === 1) {
x2 += dx;
y2 += dy;
}
break;
case 's':
// STRETCH vertically by moving the bottom endpoint
if (bottomEndpoint === 0) {
y1 += dy;
} else {
y2 += dy;
}
break;
case 'se':
// Move bottom-right corner
if (rightEndpoint === 0 && bottomEndpoint === 0) {
x1 += dx;
y1 += dy;
} else if (rightEndpoint === 1 && bottomEndpoint === 1) {
x2 += dx;
y2 += dy;
}
break;
}
element.setAttribute('x1', x1);
element.setAttribute('y1', y1);
element.setAttribute('x2', x2);
element.setAttribute('y2', y2);
this.updateContextMenuValues();
},
scaleElementRelativeToPoint(element, initialState, scaleX, scaleY, centerX, centerY) {
const tagName = element.tagName;
const isLatex = element.getAttribute('data-type') === 'latex';
const isStructure = element.getAttribute('data-type') === 'structure';
// Force uniform scaling for LaTeX/Text to prevent distortion
if (tagName === 'text' || isLatex || isStructure) {
const uniformScale = Math.max(Math.abs(scaleX), Math.abs(scaleY));
scaleX = uniformScale;
scaleY = uniformScale;
}
if (isLatex || isStructure || tagName === 'g') {
const bbox = initialState.bbox || element.getBBox();
const oldScale = initialState.scaleX || 1;
// Local center of the paths inside the group
const localCx = bbox.x + bbox.width / 2;
const localCy = bbox.y + bbox.height / 2;
// Calculate current visual center in canvas space
const currentVisCx = initialState.x + (localCx * oldScale);
const currentVisCy = initialState.y + (localCy * oldScale);
// New scale
const newScale = oldScale * scaleX;
// Where the center should be after scaling relative to the anchor (centerX/Y)
const newVisCx = centerX + (currentVisCx - centerX) * scaleX;
const newVisCy = centerY + (currentVisCy - centerY) * scaleY;
// Back-calculate the new translation
const newTx = newVisCx - (localCx * newScale);
const newTy = newVisCy - (localCy * newScale);
// Update Transform
let newTransform = `translate(${newTx}, ${newTy})`;
if (initialState.rotation) {
// Rotate around the internal center
newTransform += ` rotate(${initialState.rotation}, ${localCx * newScale}, ${localCy * newScale})`;
}
newTransform += ` scale(${newScale})`;
element.setAttribute('transform', newTransform);
return;
}
switch(tagName) {
case 'text':
const x = initialState.x;
const y = initialState.y;
const fontSize = initialState.fontSize || 16;
// Scale position relative to fixed center
const newX = centerX + (x - centerX) * scaleX;
const newY = centerY + (y - centerY) * scaleY;
const newFontSize = Math.max(1, fontSize * scaleX);
element.setAttribute('x', newX);
element.setAttribute('y', newY);
element.setAttribute('font-size', newFontSize);
const bbox = element.getBBox();
this.updateElementTransform(element, bbox);
break;
case 'rect': {
const x = initialState.x;
const y = initialState.y;
const width = initialState.width;
const height = initialState.height;
const newCenterX = centerX + ((x + width/2) - centerX) * scaleX;
const newCenterY = centerY + ((y + height/2) - centerY) * scaleY;
const newWidth = width * scaleX;
const newHeight = height * scaleY;
const newX = newCenterX - newWidth / 2;
const newY = newCenterY - newHeight / 2;
element.setAttribute('x', newX);
element.setAttribute('y', newY);
element.setAttribute('width', newWidth);
element.setAttribute('height', newHeight);
const bbox = element.getBBox();
this.updateElementTransform(element, bbox);
break;
}
case 'circle': {
const cx = initialState.cx;
const cy = initialState.cy;
const r = initialState.r;
const newCx = centerX + (cx - centerX) * scaleX;
const newCy = centerY + (cy - centerY) * scaleY;
const avgScale = (scaleX + scaleY) / 2;
const newR = Math.max(0.1, r * avgScale);
element.setAttribute('cx', newCx);
element.setAttribute('cy', newCy);
element.setAttribute('r', newR);
const bbox = element.getBBox();
this.updateElementTransform(element, bbox);
break;
}
case 'ellipse': {
const cx = initialState.cx;
const cy = initialState.cy;
const rx = initialState.rx;
const ry = initialState.ry;
const newCx = centerX + (cx - centerX) * scaleX;
const newCy = centerY + (cy - centerY) * scaleY;
const newRx = Math.max(0.1, rx * scaleX);
const newRy = Math.max(0.1, ry * scaleY);
element.setAttribute('cx', newCx);
element.setAttribute('cy', newCy);
element.setAttribute('rx', newRx);
element.setAttribute('ry', newRy);
const bbox = element.getBBox();
this.updateElementTransform(element, bbox);
break;
}
case 'line': {
const x1 = initialState.x1;
const y1 = initialState.y1;
const x2 = initialState.x2;
const y2 = initialState.y2;
const lineCenterX = (x1 + x2) / 2;
const lineCenterY = (y1 + y2) / 2;
const newCenterX = centerX + (lineCenterX - centerX) * scaleX;
const newCenterY = centerY + (lineCenterY - centerY) * scaleY;
const newX1 = newCenterX + (x1 - lineCenterX) * scaleX;
const newY1 = newCenterY + (y1 - lineCenterY) * scaleY;
const newX2 = newCenterX + (x2 - lineCenterX) * scaleX;
const newY2 = newCenterY + (y2 - lineCenterY) * scaleY;
element.setAttribute('x1', newX1);
element.setAttribute('y1', newY1);
element.setAttribute('x2', newX2);
element.setAttribute('y2', newY2);
const bbox = element.getBBox();
this.updateElementTransform(element, bbox);
break;
}
case 'path': {
const d = initialState.d;
if (!d) break;
const commands = this.parsePathCommands(d);
let newPath = '';
for (const cmd of commands) {
const type = cmd.type;
newPath += type;
if (type.toLowerCase() === 'h') {
for (let i = 0; i < cmd.values.length; i++) {
const x = centerX + (cmd.values[i] - centerX) * scaleX;
newPath += ` ${x}`;
}
} else if (type.toLowerCase() === 'v') {
for (let i = 0; i < cmd.values.length; i++) {
const y = centerY + (cmd.values[i] - centerY) * scaleY;
newPath += ` ${y}`;
}
} else if (type.toLowerCase() === 'a') {
for (let i = 0; i < cmd.values.length; i += 7) {
if (i + 6 < cmd.values.length) {
const rx = cmd.values[i] * scaleX;
const ry = cmd.values[i + 1] * scaleY;
const rotation = cmd.values[i + 2];
const largeArc = cmd.values[i + 3];
const sweep = cmd.values[i + 4];
const x = centerX + (cmd.values[i + 5] - centerX) * scaleX;
const y = centerY + (cmd.values[i + 6] - centerY) * scaleY;
newPath += ` ${rx} ${ry} ${rotation} ${largeArc} ${sweep} ${x} ${y}`;
}
}
} else {
for (let i = 0; i < cmd.values.length; i += 2) {
if (i + 1 < cmd.values.length) {
const x = centerX + (cmd.values[i] - centerX) * scaleX;
const y = centerY + (cmd.values[i + 1] - centerY) * scaleY;
newPath += ` ${x} ${y}`;
}
}
}
newPath += ' ';
}
element.setAttribute('d', newPath.trim());
const bbox = element.getBBox();
this.updateElementTransform(element, bbox);
break;
}
}
},
scaleElementByPercentage(scaleFactor) {
if (!this.selectedElement) return;
const element = this.selectedElement;
const tagName = element.tagName.toLowerCase();
const isLatex = element.getAttribute('data-type') === 'latex';
const isStructure = element.getAttribute('data-type') === 'structure';
if (isLatex || isStructure || tagName === 'g') {
const state = this.getElementState(element);
const bbox = element.getBBox();
// 1. Calculate the current visual center before scaling
const oldVisualCenterX = state.x + (bbox.x + bbox.width / 2) * state.scaleX;
const oldVisualCenterY = state.y + (bbox.y + bbox.height / 2) * state.scaleY;
// 2. Apply new scale
const newScaleX = state.scaleX * scaleFactor;
const newScaleY = state.scaleY * scaleFactor;
// 3. Adjust translation to keep the element centered at the same spot
const newTx = oldVisualCenterX - (bbox.x + bbox.width / 2) * newScaleX;
const newTy = oldVisualCenterY - (bbox.y + bbox.height / 2) * newScaleY;
// 4. Update Transform
const pivotX = (bbox.x + bbox.width / 2) * newScaleX;
const pivotY = (bbox.y + bbox.height / 2) * newScaleY;
element.setAttribute('transform',
`translate(${newTx}, ${newTy}) rotate(${state.rotation}, ${pivotX}, ${pivotY}) scale(${newScaleX}, ${newScaleY})`
);
} else {
// Fallback for standard shapes (your existing switch logic)
const originalState = this.getElementState(element);
const bbox = element.getBBox();
const centerX = bbox.x + bbox.width / 2;
const centerY = bbox.y + bbox.height / 2;
switch(tagName) {
case 'rect': {
const newW = state.width * scaleFactor;
const newH = state.height * scaleFactor;
const newX = centerX - newW / 2;
const newY = centerY - newH / 2;
element.setAttribute('width', newW);
element.setAttribute('height', newH);
element.setAttribute('x', newX);
element.setAttribute('y', newY);
// Update rotation to pivot around new center
if (state.rotation !== 0) {
element.setAttribute('transform', `rotate(${state.rotation}, ${centerX}, ${centerY})`);
}
break;
}
case 'circle': {
const newR = state.r * scaleFactor;
element.setAttribute('r', Math.max(0.1, newR));
break;
}
case 'ellipse': {
const newRX = state.rx * scaleFactor;
const newRY = state.ry * scaleFactor;
element.setAttribute('rx', Math.max(0.1, newRX));
element.setAttribute('ry', Math.max(0.1, newRY));
break;
}
case 'line': {
const dx1 = (state.x1 - centerX) * scaleFactor;
const dy1 = (state.y1 - centerY) * scaleFactor;
const dx2 = (state.x2 - centerX) * scaleFactor;
const dy2 = (state.y2 - centerY) * scaleFactor;
element.setAttribute('x1', centerX + dx1);
element.setAttribute('y1', centerY + dy1);
element.setAttribute('x2', centerX + dx2);
element.setAttribute('y2', centerY + dy2);
break;
}
case 'text': {
const newFontSize = state.fontSize * scaleFactor;
element.setAttribute('font-size', Math.max(1, newFontSize));
// Adjust x/y to keep text centered (since text scales from its anchor)
const oldX = state.x;
const oldY = state.y;
const newX = centerX + (oldX - centerX) * scaleFactor;
const newY = centerY + (oldY - centerY) * scaleFactor;
element.setAttribute('x', newX);
element.setAttribute('y', newY);
break;
}
case 'path': {
const d = state.d;
const commands = this.parsePathCommands(d);
let newPath = '';
for (const cmd of commands) {
newPath += cmd.type;
// Paths use different numbers of values depending on command type
if (cmd.type.toLowerCase() === 'h') {
cmd.values.forEach(v => {
newPath += ` ${centerX + (v - centerX) * scaleFactor}`;
});
} else if (cmd.type.toLowerCase() === 'v') {
cmd.values.forEach(v => {
newPath += ` ${centerY + (v - centerY) * scaleFactor}`;
});
} else if (cmd.type.toLowerCase() === 'a') {
// Arc command: rx ry x-axis-rotation large-arc-flag sweep-flag x y
for (let i = 0; i < cmd.values.length; i += 7) {
newPath += ` ${cmd.values[i] * scaleFactor}`; // rx
newPath += ` ${cmd.values[i+1] * scaleFactor}`; // ry
newPath += ` ${cmd.values[i+2]}`; // rot (no change)
newPath += ` ${cmd.values[i+3]}`; // large-arc
newPath += ` ${cmd.values[i+4]}`; // sweep
newPath += ` ${centerX + (cmd.values[i+5] - centerX) * scaleFactor}`; // x
newPath += ` ${centerY + (cmd.values[i+6] - centerY) * scaleFactor}`; // y
}
} else {
// Standard x,y coordinate pairs (M, L, C, Q, S, T)
for (let i = 0; i < cmd.values.length; i += 2) {
newPath += ` ${centerX + (cmd.values[i] - centerX) * scaleFactor}`;
newPath += ` ${centerY + (cmd.values[i+1] - centerY) * scaleFactor}`;
}
}
}
element.setAttribute('d', newPath.trim());
break;
}
}
}
// Refresh UI and Save to History
this.updateSelectionHandles();
this.updateContextMenuValues();
this.saveState();
},
showScaleDialog() {
if (!this.selectedElement) {
alert('Please select an element first.');
return;
}
// Create scale dialog overlay
const overlay = document.createElement('div');
overlay.className = 'scale-modal-overlay';
overlay.innerHTML = `
<div class="scale-modal">
<h3>Scale Element</h3>
<div class="scale-input-group">
<label for="scalePercentage">Scale Percentage (%):</label>
<input type="number" id="scalePercentage" value="100" min="1" max="1000" step="1">
</div>
<div class="scale-modal-buttons">
<button id="applyScale">Apply</button>
<button id="cancelScale">Cancel</button>
</div>
</div>
`;
document.body.appendChild(overlay);
// Focus the input
setTimeout(() => {
document.getElementById('scalePercentage').focus();
document.getElementById('scalePercentage').select();
}, 100);
// Event listeners
document.getElementById('applyScale').addEventListener('click', () => {
const percentage = parseFloat(document.getElementById('scalePercentage').value);
if (isNaN(percentage) || percentage <= 0) {
alert('Please enter a valid positive number.');
return;
}
this.scaleElementByPercentage(percentage / 100);
document.body.removeChild(overlay);
});
document.getElementById('cancelScale').addEventListener('click', () => {
document.body.removeChild(overlay);
});
// Close when clicking outside the modal
overlay.addEventListener('click', (e) => {
if (e.target === overlay) {
document.body.removeChild(overlay);
}
});
// Close with Escape key
const handleEscape = (e) => {
if (e.key === 'Escape') {
document.body.removeChild(overlay);
document.removeEventListener('keydown', handleEscape);
}
};
document.addEventListener('keydown', handleEscape);
}
// 3. Scale Element by Percentage,
startRotating(clientX, clientY) {
if (this.selectedElements.length === 0) return;
this.isRotating = true;
// Clear state first to ensure no stale data
this.rotationCenter = null;
this.initialElementStates = null;
this.initialElementCenters = null;
this.initialElementRotations = null;
this.initialMouseAngle = 0;
try {
// Initialize states and centers
this.initialElementStates = this.selectedElements.map(element =>
this.getElementState(element)
);
this.initialElementCenters = this.selectedElements.map(element => ({
x: this.getElementCenterX(element),
y: this.getElementCenterY(element)
}));
// Calculate center of the selection using correct bounding box
const bounds = this.calculateSelectionBounds();
if (bounds) {
const centerX = bounds.x + bounds.width / 2;
const centerY = bounds.y + bounds.height / 2;
// Store the rotation center
this.rotationCenter = { x: centerX, y: centerY };
// Get initial mouse position in SVG coordinates
const startPoint = this.screenToSVG(clientX, clientY);
// Calculate initial angle in SVG coordinates (not screen coordinates)
this.initialMouseAngle = Math.atan2(startPoint.y - centerY, startPoint.x - centerX);
// Store initial rotation for each element
this.initialElementRotations = this.selectedElements.map(element => {
const transform = element.getAttribute('transform');
if (transform && transform.includes('rotate')) {
const match = transform.match(/rotate\(([-\d.]+)/);
if (match) {
return parseFloat(match[1]);
}
}
return 0;
});
}
} catch (e) {
console.error("Error starting rotation:", e);
this.isRotating = false;
}
},
rotateElement(currentClientX, currentClientY) {
if (this.selectedElements.length === 0 || !this.rotationCenter) return;
const currentPoint = this.screenToSVG(currentClientX, currentClientY);
const currentAngle = Math.atan2(
currentPoint.y - this.rotationCenter.y,
currentPoint.x - this.rotationCenter.x
);
let rotationDelta = (currentAngle - this.initialMouseAngle) * (180 / Math.PI);
this.selectedElements.forEach((element, index) => {
const state = this.initialElementStates[index];
const newRotation = (this.initialElementRotations[index] || 0) + rotationDelta;
if (element.tagName === 'g' || element.getAttribute('data-type')) {
const bbox = element.getBBox();
const localCx = bbox.x + bbox.width / 2;
const localCy = bbox.y + bbox.height / 2;
const sx = state.scaleX || 1;
const sy = state.scaleY || 1;
// Maintain visual center: NewTranslate = RotationCenter - (LocalCenter * Scale)
// But since the group rotates around its visual center (Pivot), we simply set:
const pivotX = localCx * sx;
const pivotY = localCy * sy;
// Format: translate -> rotate(angle, pivot) -> scale
element.setAttribute('transform',
`translate(${state.x}, ${state.y}) rotate(${newRotation}, ${pivotX}, ${pivotY}) scale(${sx}, ${sy})`
);
} else {
// Standard shapes
const cx = this.rotationCenter.x;
const cy = this.rotationCenter.y;
element.setAttribute('transform', `rotate(${newRotation}, ${cx}, ${cy})`);
}
});
this.updateSelectionHandles();
this.updateContextMenuValues();
},
rotateElementByAngle() {