-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
901 lines (793 loc) · 28.3 KB
/
content.js
File metadata and controls
901 lines (793 loc) · 28.3 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
let measureMode = false; // default OFF
let activeOverlays = []; // Track active overlays
let preventScroll = false; // Flag to prevent scrolling
let clickedElements = []; // Track clicked elements
let lastClickedElementInfo = null; // Track the last clicked element for hover comparison
// Listen for messages from the background script
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "TOGGLE_MEASURE_MODE") {
measureMode = !measureMode;
console.log("Measure mode is now:", measureMode);
if (measureMode) {
// Enable scroll prevention when measure mode is on
preventScroll = true;
} else {
// If turning measure mode off, remove all overlays
removeAllOverlays();
preventScroll = false;
}
}
});
// Listen for Escape key to clear all measurements or deactivate
let lastEscapePressTime = 0; // Track time of last Escape press
const doublePressThreshold = 500; // Milliseconds for double press detection
document.addEventListener("keydown", (event) => {
if (event.key === "Escape") {
const now = Date.now();
const timeDiff = now - lastEscapePressTime;
if (timeDiff < doublePressThreshold) {
// Double press: Deactivate measure mode completely
if (measureMode) {
// Only deactivate if currently active
console.log("Double Escape detected: Deactivating measure mode.");
measureMode = false;
preventScroll = false;
removeAllOverlays(); // Clear UI
// Optional: Send message if background needs to know state change
// chrome.runtime.sendMessage({ type: "MEASURE_MODE_DEACTIVATED" });
}
lastEscapePressTime = 0; // Reset timer after double press
} else {
// Single press: Clear current measurements if mode is active
if (measureMode) {
console.log("Single Escape detected: Clearing overlays.");
removeAllOverlays();
}
lastEscapePressTime = now; // Record time of this press
}
}
});
// Function to remove all overlays
function removeAllOverlays() {
// Iterate through the tracked overlays and remove them
activeOverlays.forEach((el) => {
if (el && el.parentNode) {
el.parentNode.removeChild(el);
}
});
// Also remove any remaining hover/distance elements just in case
document
.querySelectorAll(
".multi-measure-hover, .multi-measure-hover-distance-line, .multi-measure-hover-distance-label"
)
.forEach((el) => el.remove());
// Clear the tracking arrays and state
activeOverlays = [];
clickedElements = [];
lastClickedElementInfo = null;
}
// Prevent scrolling when measure mode is active
window.addEventListener(
"scroll",
(event) => {
if (preventScroll && measureMode) {
window.scrollTo(0, 0); // Reset to top
}
},
{ passive: false }
);
// Handle hover to show temporary dimensions AND distances to last clicked
document.addEventListener("mousemove", (event) => {
if (!measureMode) return;
// Remove previous hover overlay and hover distance lines/labels
document
.querySelectorAll(
".multi-measure-hover, .multi-measure-hover-distance-line, .multi-measure-hover-distance-label"
)
.forEach((el) => el.remove());
const targetEl = event.target;
// Don't create overlays for our own elements
if (
targetEl.classList.contains("multi-measure-overlay") ||
targetEl.classList.contains("multi-measure-line") ||
targetEl.classList.contains("multi-measure-hover") ||
targetEl.classList.contains("multi-measure-label") ||
targetEl.closest(
".multi-measure-overlay, .multi-measure-line, .multi-measure-hover, .multi-measure-label, .multi-measure-dimension-box, .multi-measure-guideline, .multi-measure-distance-label"
)
) {
return;
}
const currentRect = targetEl.getBoundingClientRect();
// Create the basic hover overlay
createHoverOverlay(currentRect, targetEl);
// If there's a previously clicked element, draw distance lines
if (lastClickedElementInfo) {
drawHoverDistanceLines(lastClickedElementInfo.rect, currentRect);
}
});
// Handle click to create persistent measurements AND set last clicked element
document.addEventListener(
"click",
(event) => {
if (!measureMode) return;
event.preventDefault();
event.stopPropagation();
const targetEl = event.target;
// Don't create overlays for our own elements
if (
targetEl.classList.contains("multi-measure-overlay") ||
targetEl.classList.contains("multi-measure-line") ||
targetEl.classList.contains("multi-measure-hover") ||
targetEl.classList.contains("multi-measure-label") ||
targetEl.closest(
".multi-measure-overlay, .multi-measure-line, .multi-measure-hover, .multi-measure-label, .multi-measure-dimension-box, .multi-measure-guideline, .multi-measure-distance-label, .multi-measure-persistent-distance-line, .multi-measure-persistent-distance-label"
)
) {
return;
}
// --- Click Logic ---
const newRect = targetEl.getBoundingClientRect();
let isNewMeasurement = false;
// Check if this element was *already* clicked and has a persistent overlay
const alreadyClickedIndex = clickedElements.findIndex(
(el) => el === targetEl
);
if (alreadyClickedIndex === -1) {
// --- First time clicking this element ---
isNewMeasurement = true;
// Create the main overlay on the element
createOverlay(newRect, targetEl);
// Calculate and show all margins and padding
showElementBoxModel(targetEl);
// Add to clicked elements list
clickedElements.push(targetEl);
// Remove any temporary hover effect for this specific element if it exists
targetEl
.querySelectorAll(".multi-measure-hover")
.forEach((el) => el.remove());
document.querySelectorAll(".multi-measure-hover").forEach((el) => {
if (
el.style.top === newRect.top + window.scrollY + "px" &&
el.style.left === newRect.left + window.scrollX + "px"
) {
el.remove();
}
});
}
// --- Generate and Copy TSX Snippet ---
if (isNewMeasurement) {
// Only generate/copy on the *first* click of an element
const tsxSnippet = generateTsxSnippet(targetEl);
navigator.clipboard
.writeText(tsxSnippet)
.then(() => {
console.log("TSX Snippet copied to clipboard:", tsxSnippet);
// Optional: Add a brief visual feedback here, like flashing the overlay
})
.catch((err) => {
console.error("Failed to copy TSX snippet:", err);
});
}
// --- Draw Persistent Distance Lines (if there was a previous click) ---
if (lastClickedElementInfo) {
// Draw persistent lines between PREVIOUSLY clicked and NEWLY clicked
drawPersistentDistanceLines(lastClickedElementInfo.rect, newRect);
}
// *** Update last clicked element reference for the NEXT hover/click ***
lastClickedElementInfo = { rect: newRect, element: targetEl };
// Optional: Log if it was a new measurement or just setting reference
// if (!isNewMeasurement) {
// console.log("Set last clicked element reference to already measured element.");
// }
},
true
);
// Create an outline overlay for the clicked element (persistent)
function createOverlay(rect, element) {
const overlay = document.createElement("div");
overlay.classList.add("multi-measure-overlay");
const scrollTop = window.scrollY;
const scrollLeft = window.scrollX;
overlay.style.top = rect.top + scrollTop + "px";
overlay.style.left = rect.left + scrollLeft + "px";
overlay.style.width = rect.width + "px";
overlay.style.height = rect.height + "px";
// Create a single, primary dimension box (e.g., "167x27")
const dimensionBox = document.createElement("div");
dimensionBox.classList.add("multi-measure-dimension-box");
dimensionBox.textContent = `${Math.round(rect.width)}×${Math.round(
rect.height
)}`;
// Position it consistently centered above the element
const boxOffset = 18; // Increased offset further
dimensionBox.style.top = rect.top + scrollTop - boxOffset + "px";
dimensionBox.style.left = rect.left + scrollLeft + rect.width / 2 + "px";
dimensionBox.style.transform = "translate(-50%, -100%)"; // Center horizontally, move up
document.body.appendChild(overlay);
document.body.appendChild(dimensionBox);
activeOverlays.push(overlay);
activeOverlays.push(dimensionBox);
return overlay;
}
// Create a hover overlay (temporary)
function createHoverOverlay(rect, element) {
const overlay = document.createElement("div");
overlay.classList.add("multi-measure-hover");
const scrollTop = window.scrollY;
const scrollLeft = window.scrollX;
overlay.style.top = rect.top + scrollTop + "px";
overlay.style.left = rect.left + scrollLeft + "px";
overlay.style.width = rect.width + "px";
overlay.style.height = rect.height + "px";
// Dimension label
const label = document.createElement("div");
label.classList.add("multi-measure-hover-label");
label.textContent = `${Math.round(rect.width)}×${Math.round(rect.height)}`;
overlay.appendChild(label);
document.body.appendChild(overlay);
}
// Display the element's box model (margins, padding, borders)
function showElementBoxModel(element) {
const styles = window.getComputedStyle(element);
const rect = element.getBoundingClientRect();
// Get dimensions
const scrollTop = window.scrollY;
const scrollLeft = window.scrollX;
const marginTop = parseFloat(styles.marginTop);
const marginRight = parseFloat(styles.marginRight);
const marginBottom = parseFloat(styles.marginBottom);
const marginLeft = parseFloat(styles.marginLeft);
const paddingTop = parseFloat(styles.paddingTop);
const paddingRight = parseFloat(styles.paddingRight);
const paddingBottom = parseFloat(styles.paddingBottom);
const paddingLeft = parseFloat(styles.paddingLeft);
// Content dimensions
const contentWidth = rect.width - paddingLeft - paddingRight;
const contentHeight = rect.height - paddingTop - paddingBottom;
// Draw margin overlays (orange)
if (marginTop > 0) {
createMarginOverlay(
rect.left + scrollLeft - marginLeft,
rect.top + scrollTop - marginTop,
rect.width + marginLeft + marginRight,
marginTop,
"top"
);
}
if (marginRight > 0) {
createMarginOverlay(
rect.right + scrollLeft,
rect.top + scrollTop - marginTop,
marginRight,
rect.height + marginTop + marginBottom,
"right"
);
}
if (marginBottom > 0) {
createMarginOverlay(
rect.left + scrollLeft - marginLeft,
rect.bottom + scrollTop,
rect.width + marginLeft + marginRight,
marginBottom,
"bottom"
);
}
if (marginLeft > 0) {
createMarginOverlay(
rect.left + scrollLeft - marginLeft,
rect.top + scrollTop - marginTop,
marginLeft,
rect.height + marginTop + marginBottom,
"left"
);
}
// Draw padding overlays (green)
if (paddingTop > 0) {
createPaddingOverlay(
rect.left + scrollLeft,
rect.top + scrollTop,
rect.width,
paddingTop,
"top"
);
}
if (paddingRight > 0) {
createPaddingOverlay(
rect.right + scrollLeft - paddingRight,
rect.top + scrollTop,
paddingRight,
rect.height,
"right"
);
}
if (paddingBottom > 0) {
createPaddingOverlay(
rect.left + scrollLeft,
rect.bottom + scrollTop - paddingBottom,
rect.width,
paddingBottom,
"bottom"
);
}
if (paddingLeft > 0) {
createPaddingOverlay(
rect.left + scrollLeft,
rect.top + scrollTop,
paddingLeft,
rect.height,
"left"
);
}
// Draw content box
const contentOverlay = document.createElement("div");
contentOverlay.classList.add("multi-measure-content");
contentOverlay.style.top = rect.top + scrollTop + paddingTop + "px";
contentOverlay.style.left = rect.left + scrollLeft + paddingLeft + "px";
contentOverlay.style.width = contentWidth + "px";
contentOverlay.style.height = contentHeight + "px";
document.body.appendChild(contentOverlay);
activeOverlays.push(contentOverlay);
// Draw guide lines with distance labels
// drawBoundedGuideLinesWithDistance(rect, element);
}
// Create a margin overlay with a label
function createMarginOverlay(left, top, width, height, position) {
const overlay = document.createElement("div");
overlay.classList.add(
"multi-measure-margin",
`multi-measure-margin-${position}`
);
// Suggestion: Add a distinct background color/opacity for margins in your CSS
// e.g., .multi-measure-margin { background-color: rgba(255, 165, 0, 0.3); /* Orange tint */ }
overlay.style.top = top + "px";
overlay.style.left = left + "px";
overlay.style.width = width + "px";
overlay.style.height = height + "px";
// Label showing the margin size
const label = document.createElement("div");
label.classList.add("multi-measure-margin-label");
if (position === "top" || position === "bottom") {
label.textContent = `${Math.round(height)}px`; // Removed "margin " prefix
label.style.left = "50%";
label.style.transform = "translateX(-50%)";
label.style.top = position === "top" ? "0" : "auto";
label.style.bottom = position === "bottom" ? "0" : "auto";
} else {
label.textContent = `${Math.round(width)}px`; // Removed "margin " prefix
label.style.top = "50%";
label.style.transform = "translateY(-50%)";
label.style.left = position === "left" ? "0" : "auto";
label.style.right = position === "right" ? "0" : "auto";
}
overlay.appendChild(label);
document.body.appendChild(overlay);
activeOverlays.push(overlay);
}
// Create a padding overlay with a label
function createPaddingOverlay(left, top, width, height, position) {
const overlay = document.createElement("div");
overlay.classList.add(
"multi-measure-padding",
`multi-measure-padding-${position}`
);
// Suggestion: Add a distinct background color/opacity for padding in your CSS
// e.g., .multi-measure-padding { background-color: rgba(144, 238, 144, 0.4); /* Green tint */ }
overlay.style.top = top + "px";
overlay.style.left = left + "px";
overlay.style.width = width + "px";
overlay.style.height = height + "px";
// Label showing the padding size
const label = document.createElement("div");
label.classList.add("multi-measure-padding-label");
if (position === "top" || position === "bottom") {
label.textContent = `${Math.round(height)}px`; // Removed "padding " prefix
label.style.left = "50%";
label.style.transform = "translateX(-50%)";
label.style.top = position === "top" ? "0" : "auto";
label.style.bottom = position === "bottom" ? "0" : "auto";
} else {
label.textContent = `${Math.round(width)}px`; // Removed "padding " prefix
label.style.top = "50%";
label.style.transform = "translateY(-50%)";
label.style.left = position === "left" ? "0" : "auto";
label.style.right = position === "right" ? "0" : "auto";
}
overlay.appendChild(label);
document.body.appendChild(overlay);
activeOverlays.push(overlay);
}
// NEW function to draw temporary distance lines on hover
function drawHoverDistanceLines(rect1, rect2) {
const scrollTop = window.scrollY;
const scrollLeft = window.scrollX;
// Calculate centers and edges relative to document
const r1 = {
top: rect1.top + scrollTop,
bottom: rect1.bottom + scrollTop,
left: rect1.left + scrollLeft,
right: rect1.right + scrollLeft,
centerX: rect1.left + scrollLeft + rect1.width / 2,
centerY: rect1.top + scrollTop + rect1.height / 2,
};
const r2 = {
top: rect2.top + scrollTop,
bottom: rect2.bottom + scrollTop,
left: rect2.left + scrollLeft,
right: rect2.right + scrollLeft,
centerX: rect2.left + scrollLeft + rect2.width / 2,
centerY: rect2.top + scrollTop + rect2.height / 2,
};
// Calculate horizontal and vertical distances between edges
let horizontalDist, verticalDist;
let hLineY, vLineX;
let hLineX1, hLineX2;
let vLineY1, vLineY2;
// Horizontal Distance Calculation
if (r2.left >= r1.right) {
// Hovered is to the right of clicked
horizontalDist = Math.round(r2.left - r1.right);
hLineY = r1.centerY; // Draw line from center Y of clicked
hLineX1 = r1.right;
hLineX2 = r2.left;
} else if (r2.right <= r1.left) {
// Hovered is to the left of clicked
horizontalDist = Math.round(r1.left - r2.right);
hLineY = r1.centerY;
hLineX1 = r2.right;
hLineX2 = r1.left;
} else {
// Elements overlap horizontally
horizontalDist = 0;
}
// Vertical Distance Calculation
if (r2.top >= r1.bottom) {
// Hovered is below clicked
verticalDist = Math.round(r2.top - r1.bottom);
vLineX = r1.centerX; // Draw line from center X of clicked
vLineY1 = r1.bottom;
vLineY2 = r2.top;
} else if (r2.bottom <= r1.top) {
// Hovered is above clicked
verticalDist = Math.round(r1.top - r2.bottom);
vLineX = r1.centerX;
vLineY1 = r2.bottom;
vLineY2 = r1.top;
} else {
// Elements overlap vertically
verticalDist = 0;
}
// Draw Horizontal Line & Label if distance > 0
if (horizontalDist > 0) {
createHoverDistanceLineAndLabel(
hLineX1,
hLineY,
hLineX2,
hLineY,
horizontalDist,
"horizontal"
);
}
// Draw Vertical Line & Label if distance > 0
if (verticalDist > 0) {
createHoverDistanceLineAndLabel(
vLineX,
vLineY1,
vLineX,
vLineY2,
verticalDist,
"vertical"
);
}
}
// Helper to create a single hover distance line and its label
function createHoverDistanceLineAndLabel(
x1,
y1,
x2,
y2,
distance,
orientation
) {
const line = document.createElement("div");
line.classList.add("multi-measure-hover-distance-line");
const label = document.createElement("div");
label.classList.add("multi-measure-hover-distance-label");
label.textContent = `${distance}px`;
if (orientation === "horizontal") {
const left = Math.min(x1, x2);
const width = Math.abs(x2 - x1);
line.style.top = y1 + "px";
line.style.left = left + "px";
line.style.width = width + "px";
line.style.height = "1px";
label.style.top = y1 + "px";
label.style.left = left + width / 2 + "px";
label.style.transform = "translate(-50%, -110%)"; // Position above line
} else {
// Vertical
const top = Math.min(y1, y2);
const height = Math.abs(y2 - y1);
line.style.top = top + "px";
line.style.left = x1 + "px";
line.style.width = "1px";
line.style.height = height + "px";
label.style.left = x1 + "px";
label.style.top = top + height / 2 + "px";
label.style.transform = "translate(10px, -50%)"; // Position right of line
}
document.body.appendChild(line);
document.body.appendChild(label);
// Note: We don't add these to activeOverlays because they are cleared on every mouse move
}
// NEW function to draw PERSISTENT distance lines between two rects
function drawPersistentDistanceLines(rect1, rect2) {
const scrollTop = window.scrollY;
const scrollLeft = window.scrollX;
// Calculate centers and edges relative to document
const r1 = {
top: rect1.top + scrollTop,
bottom: rect1.bottom + scrollTop,
left: rect1.left + scrollLeft,
right: rect1.right + scrollLeft,
centerX: rect1.left + scrollLeft + rect1.width / 2,
centerY: rect1.top + scrollTop + rect1.height / 2,
};
const r2 = {
top: rect2.top + scrollTop,
bottom: rect2.bottom + scrollTop,
left: rect2.left + scrollLeft,
right: rect2.right + scrollLeft,
centerX: rect2.left + scrollLeft + rect2.width / 2,
centerY: rect2.top + scrollTop + rect2.height / 2,
};
// Calculate horizontal and vertical distances between edges
let horizontalDist, verticalDist;
let hLineY, vLineX;
let hLineX1, hLineX2;
let vLineY1, vLineY2;
// Horizontal Distance Calculation (same logic as hover)
if (r2.left >= r1.right) {
horizontalDist = Math.round(r2.left - r1.right);
hLineY = r1.centerY;
hLineX1 = r1.right;
hLineX2 = r2.left;
} else if (r2.right <= r1.left) {
horizontalDist = Math.round(r1.left - r2.right);
hLineY = r1.centerY;
hLineX1 = r2.right;
hLineX2 = r1.left;
} else {
horizontalDist = 0;
}
// Vertical Distance Calculation (same logic as hover)
if (r2.top >= r1.bottom) {
verticalDist = Math.round(r2.top - r1.bottom);
vLineX = r1.centerX;
vLineY1 = r1.bottom;
vLineY2 = r2.top;
} else if (r2.bottom <= r1.top) {
verticalDist = Math.round(r1.top - r2.bottom);
vLineX = r1.centerX;
vLineY1 = r2.bottom;
vLineY2 = r1.top;
} else {
verticalDist = 0;
}
// Draw Horizontal Line & Label if distance > 0
if (horizontalDist > 0) {
createPersistentDistanceLineAndLabel(
hLineX1,
hLineY,
hLineX2,
hLineY,
horizontalDist,
"horizontal"
);
}
// Draw Vertical Line & Label if distance > 0
if (verticalDist > 0) {
createPersistentDistanceLineAndLabel(
vLineX,
vLineY1,
vLineX,
vLineY2,
verticalDist,
"vertical"
);
}
}
// Helper to create a single PERSISTENT distance line and its label
function createPersistentDistanceLineAndLabel(
x1,
y1,
x2,
y2,
distance,
orientation
) {
const line = document.createElement("div");
line.classList.add("multi-measure-persistent-distance-line"); // Use persistent class
const label = document.createElement("div");
label.classList.add("multi-measure-persistent-distance-label"); // Use persistent class
label.textContent = `${distance}px`;
if (orientation === "horizontal") {
const left = Math.min(x1, x2);
const width = Math.abs(x2 - x1);
line.style.top = y1 + "px";
line.style.left = left + "px";
line.style.width = width + "px";
line.style.height = "1px";
label.style.top = y1 + "px";
label.style.left = left + width / 2 + "px";
label.style.transform = "translate(-50%, -110%)"; // Position above line
} else {
// Vertical
const top = Math.min(y1, y2);
const height = Math.abs(y2 - y1);
line.style.top = top + "px";
line.style.left = x1 + "px";
line.style.width = "1px";
line.style.height = height + "px";
label.style.left = x1 + "px";
label.style.top = top + height / 2 + "px";
label.style.transform = "translate(10px, -50%)"; // Position right of line
}
document.body.appendChild(line);
document.body.appendChild(label);
// Add to activeOverlays so they get cleared with Escape
activeOverlays.push(line);
activeOverlays.push(label);
}
// --- NEW: Helper Function to Generate TSX for a Single Element ---
function generateSingleElementTsx(element, isChild = false) {
const tagName = element.tagName.toLowerCase();
const rect = element.getBoundingClientRect();
const styles = window.getComputedStyle(element);
let content = element.textContent?.trim() ?? "";
// Basic check if the element ONLY contains text/comment nodes
let hasOnlyTextOrCommentChildren = true;
if (element.childNodes.length > 0) {
for (const node of element.childNodes) {
if (
node.nodeType !== Node.TEXT_NODE &&
node.nodeType !== Node.COMMENT_NODE
) {
hasOnlyTextOrCommentChildren = false;
break;
}
}
}
// Limit content length, especially for children or parents without element children
if (isChild || hasOnlyTextOrCommentChildren) {
if (content.length > 50) {
content = content.substring(0, 47) + "...";
}
} else {
content = ""; // Don't include parent's text if it has element children
}
const tailwindClasses = [];
// --- Dimensions ---
const width = Math.round(rect.width);
const height = Math.round(rect.height);
if (width > 0) tailwindClasses.push(`w-[${width}px]`);
if (height > 0) tailwindClasses.push(`h-[${height}px]`);
// --- Margins ---
const marginTop = Math.round(parseFloat(styles.marginTop));
const marginRight = Math.round(parseFloat(styles.marginRight));
const marginBottom = Math.round(parseFloat(styles.marginBottom));
const marginLeft = Math.round(parseFloat(styles.marginLeft));
if (marginTop) tailwindClasses.push(`mt-[${marginTop}px]`);
if (marginRight) tailwindClasses.push(`mr-[${marginRight}px]`);
if (marginBottom) tailwindClasses.push(`mb-[${marginBottom}px]`);
if (marginLeft) tailwindClasses.push(`ml-[${marginLeft}px]`);
// --- Padding ---
const paddingTop = Math.round(parseFloat(styles.paddingTop));
const paddingRight = Math.round(parseFloat(styles.paddingRight));
const paddingBottom = Math.round(parseFloat(styles.paddingBottom));
const paddingLeft = Math.round(parseFloat(styles.paddingLeft));
if (paddingTop) tailwindClasses.push(`pt-[${paddingTop}px]`);
if (paddingRight) tailwindClasses.push(`pr-[${paddingRight}px]`);
if (paddingBottom) tailwindClasses.push(`pb-[${paddingBottom}px]`);
if (paddingLeft) tailwindClasses.push(`pl-[${paddingLeft}px]`);
// --- Display & Flexbox ---
if (styles.display === "flex") {
tailwindClasses.push("flex");
// Only add flex properties to the parent, not necessarily children
if (!isChild) {
switch (styles.flexDirection) {
case "row":
break;
case "row-reverse":
tailwindClasses.push("flex-row-reverse");
break;
case "column":
tailwindClasses.push("flex-col");
break;
case "column-reverse":
tailwindClasses.push("flex-col-reverse");
break;
}
switch (styles.justifyContent) {
case "flex-start":
break;
case "flex-end":
tailwindClasses.push("justify-end");
break;
case "center":
tailwindClasses.push("justify-center");
break;
case "space-between":
tailwindClasses.push("justify-between");
break;
case "space-around":
tailwindClasses.push("justify-around");
break;
case "space-evenly":
tailwindClasses.push("justify-evenly");
break;
}
switch (styles.alignItems) {
case "stretch":
break;
case "flex-start":
tailwindClasses.push("items-start");
break;
case "flex-end":
tailwindClasses.push("items-end");
break;
case "center":
tailwindClasses.push("items-center");
break;
case "baseline":
tailwindClasses.push("items-baseline");
break;
}
}
} else if (styles.display === "grid") {
tailwindClasses.push("grid");
// Grid properties are complex to map automatically
} else if (styles.display === "block" && tagName !== "div") {
tailwindClasses.push("block");
} else if (styles.display === "inline-block") {
tailwindClasses.push("inline-block");
} else if (styles.display === "inline") {
tailwindClasses.push("inline");
}
// TODO: Add text color, font size, font weight, background-color, border-radius etc.
const classesString = tailwindClasses.join(" ");
const classAttribute = classesString ? ` className="${classesString}"` : "";
// If it's a child or has no element children, include content and close tag simply
if (isChild || hasOnlyTextOrCommentChildren) {
return `<${tagName}${classAttribute}>${content}</${tagName}>`;
} else {
// If it's the parent and has element children, return just the opening tag
// The closing tag and children will be handled by the main function
return `<${tagName}${classAttribute}>`;
}
}
// --- Updated Main Function to handle children ---
function generateTsxSnippet(element) {
// Generate the TSX for the parent element itself (opening tag or full tag)
const parentTsx = generateSingleElementTsx(element, false);
// Check if the parent TSX is self-contained (has content or no children)
const isSelfContained = parentTsx.endsWith(
`</${element.tagName.toLowerCase()}>`
);
if (isSelfContained) {
// Parent has no element children or is simple text node, return its own TSX
return parentTsx;
} else {
// Parent has element children, let's build the nested structure
let childrenTsx = "";
const childIndent = " "; // Indentation for children
for (const child of element.children) {
// Generate TSX for each direct child
childrenTsx += `\n${childIndent}${generateSingleElementTsx(child, true)}`;
}
// Add closing tag for the parent
const tagName = element.tagName.toLowerCase();
return `${parentTsx}${childrenTsx}\n</${tagName}>`;
}
}
// --- End of New Function ---