-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
6502 lines (5667 loc) · 223 KB
/
content.js
File metadata and controls
6502 lines (5667 loc) · 223 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
// Content script for screenshot and annotation overlay
// Prevent multiple script injections - wrap everything in guard
if (!window.screenshotAnnotationScriptLoaded) {
window.screenshotAnnotationScriptLoaded = true;
// ============================================================================
// PRODUCTION LOGGER
// ============================================================================
const DEBUG_MODE = false; // Set to false for production
const logger = {
log: (...args) => { if (DEBUG_MODE) console.log('[Content]', ...args); },
info: (...args) => { if (DEBUG_MODE) console.info('[Content]', ...args); },
warn: (...args) => console.warn('[Content]', ...args),
error: (...args) => console.error('[Content]', ...args)
};
// ============================================================================
// MEMORY MANAGEMENT
// ============================================================================
// Cleanup canvas to prevent memory leaks
function cleanupCanvas(canvas) {
if (!canvas) return;
try {
const ctx = canvas.getContext('2d');
if (ctx) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
// Reset dimensions to minimal size to free memory
canvas.width = 1;
canvas.height = 1;
// Remove from DOM if attached
if (canvas.parentNode) {
canvas.parentNode.removeChild(canvas);
}
} catch (e) {
logger.warn('Canvas cleanup warning:', e);
}
}
let screenshotDataUrl = null;
let annotations = [];
let currentTool = 'select';
let selectedArrowType = null; // Track which arrow is selected
let selectedShapeType = null; // Track which shape is selected (rectangle, circle)
let selectedEmoji = null; // Track which emoji is selected
let selectedAnnotationIndex = -1;
let isDragging = false;
let isResizing = false;
let isRotating = false;
let isDrawingShape = false; // Track if drawing a new shape
let isDrawingFreehand = false; // Track if drawing freehand
let currentFreehandPoints = []; // Points for current freehand drawing
let isDrawingHighlight = false; // Track if drawing highlight
let currentHighlightPoints = []; // Points for current highlight stroke
let shapeStartX = 0;
let shapeStartY = 0;
let resizeHandle = null;
let dragOffsetX = 0;
let dragOffsetY = 0;
let hoveredHandle = null; // Track which handle is being hovered
let selectedColor = '#FF0000'; // Default color (red)
let selectedStrokeWidth = 3; // Default stroke width
let highlightBrushSize = 25; // Default highlight brush size (independent from pen)
let blurIntensity = 10; // Default blur intensity/radius
let blurEffectType = 'blur'; // Default blur effect type ('blur' or 'pixelate')
let isTextEditing = false; // Track if text is being edited
// v3.0 Enhancement variables
let selectedOpacity = 1.0; // Default opacity (1.0 = 100%)
let colorPresets = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF', '#000000', '#FFFFFF']; // Default color palette
let recentColors = []; // Recently used colors
let calloutCounter = 1; // Counter for numbered callouts
let lineArrowStart = false; // Whether line has arrow at start
let lineArrowEnd = true; // Whether line has arrow at end (default true for arrow lines)
let selectedTextBold = false; // Text formatting: bold
let selectedTextItalic = false; // Text formatting: italic
let selectedTextUnderline = false; // Text formatting: underline
let magnifyZoomLevel = 2; // Default magnification zoom level (2x)
// Platform detection
const isMac = navigator.userAgent.toUpperCase().indexOf('MAC') >= 0;
// Default keyboard shortcuts configuration
const DEFAULT_SHORTCUTS = {
selectTool: 'v',
penTool: 'p',
highlightTool: 'h',
textTool: 't',
blurTool: 'b',
rectangleTool: 'r',
circleTool: 'c',
undo: 'ctrl+z',
redo: 'ctrl+y',
copy: 'ctrl+c',
delete: 'delete',
escape: 'escape',
save: 'ctrl+s'
};
// User's custom shortcuts (loaded from storage)
let userShortcuts = { ...DEFAULT_SHORTCUTS };
// Undo/Redo history
let undoHistory = [];
let redoHistory = [];
const MAX_HISTORY = 50; // Limit history size
// Event listener references for cleanup
let documentClickHandler = null;
let documentKeydownHandler = null;
// Redraw optimization
let redrawScheduled = false;
let lastRedrawTime = 0;
const MIN_REDRAW_INTERVAL = 16; // ~60fps cap
// Area selection variables
let isSelectingArea = false;
let isDraggingSelection = false;
let selectionStartX = 0;
let selectionStartY = 0;
let selectionEndX = 0;
let selectionEndY = 0;
let selectionOverlay = null;
let selectionMode = 'crop'; // 'crop' = select area after capture, 'capture' = select area before capture
// Crop overlay variables
let isCropping = false;
let cropOverlay = null;
let cropRect = { x: 0, y: 0, width: 0, height: 0 };
let cropDragType = null; // 'move', 'nw', 'ne', 'sw', 'se', 'n', 's', 'e', 'w'
let cropDragStartX = 0;
let cropDragStartY = 0;
let cropInitialRect = null;
let uncropppedDataUrl = null; // Store original image for cropping
// Arrow images from the hand-drawn-arrows folder
const arrowImages = [
'arrow1.png',
'arrow2.png',
'arrow3.png',
'arrow4.png'
];
// Cache for loaded arrow images
const arrowImageCache = {};
const arrowImagePromises = {};
// Helper function to get arrow image URL
function getArrowImageURL(arrowName) {
return chrome.runtime.getURL(`hand-drawn-arrows/${arrowName}`);
}
// Preload arrow images with proper error handling
function preloadArrowImages() {
arrowImages.forEach(arrowName => {
const img = new Image();
const promise = new Promise((resolve, reject) => {
img.onload = () => {
arrowImageCache[arrowName] = img;
logger.log(`Preloaded arrow image: ${arrowName}`, img.width, img.height);
resolve(img);
};
img.onerror = (e) => {
logger.error(`Failed to preload arrow image: ${arrowName}`, e);
logger.error(`Failed URL: ${getArrowImageURL(arrowName)}`);
// Don't reject, just log - images can be loaded later
resolve(null);
};
});
const url = getArrowImageURL(arrowName);
logger.log(`Preloading arrow image: ${arrowName} from ${url}`);
img.src = url;
arrowImagePromises[arrowName] = promise;
// Store the image object immediately (will be updated on load)
arrowImageCache[arrowName] = img;
});
}
// Preload images when content script loads
preloadArrowImages();
// Modern SVG Icons System
const ICONS = {
select: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3l7.07 16.97 2.51-7.39 7.39-2.51L3 3z"/></svg>`,
arrow: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19V6M5 12l7-7 7 7"/></svg>`,
shapes: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="7" rx="1"/><circle cx="17" cy="7" r="4"/><path d="M3 17h10l-5 4z"/></svg>`,
emoji: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><line x1="9" y1="9" x2="9.01" y2="9"/><line x1="15" y1="9" x2="15.01" y2="9"/></svg>`,
pen: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19l7-7 3 3-7 7-3-3z"/><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/><path d="M2 2l7.586 7.586"/><circle cx="11" cy="11" r="2"/></svg>`,
text: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="4 7 4 4 20 4 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="4" x2="12" y2="20"/></svg>`,
blur: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></svg>`,
crop: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6.13 1L6 16a2 2 0 0 0 2 2h15"/><path d="M1 6.13L16 6a2 2 0 0 1 2 2v15"/></svg>`,
zoomIn: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/><line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/></svg>`,
zoomOut: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/><line x1="8" y1="11" x2="14" y2="11"/></svg>`,
undo: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7v6h6"/><path d="M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13"/></svg>`,
redo: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 7v6h-6"/><path d="M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7"/></svg>`,
copy: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>`,
clear: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg>`,
save: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>`,
close: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>`,
settings: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>`,
share: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>`
};
// Helper function to get icon HTML
function getIcon(name, size = 18) {
const svg = ICONS[name] || ICONS.shapes; // Fallback to shapes if icon not found
return `<span class="icon-svg" style="width:${size}px;height:${size}px;display:inline-block;vertical-align:middle;">${svg}</span>`;
}
// Helper function to switch to Select tool (global scope for access from all functions)
function switchToSelectTool() {
selectTool('select');
}
// General tool selection function
function selectTool(toolName) {
currentTool = toolName;
selectedArrowType = null;
selectedShapeType = null;
hoveredHandle = null;
// Update UI buttons
document.querySelectorAll('.tool-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.dropdown-item').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.arrow-btn').forEach(b => b.classList.remove('active'));
// Also update the Objects dropdown toggle
const objectsDropdownToggle = document.getElementById('objects-dropdown-toggle');
if (objectsDropdownToggle) {
objectsDropdownToggle.classList.remove('active');
}
// Activate the correct button
const toolBtn = document.querySelector(`[data-tool="${toolName}"]`);
if (toolBtn) toolBtn.classList.add('active');
// Update canvas cursor and mode
const canvas = document.getElementById('annotation-canvas');
if (canvas) {
// Remove all tool mode classes
canvas.classList.remove('select-mode', 'pen-mode', 'highlight-mode', 'blur-mode');
if (toolName === 'select') {
canvas.classList.add('select-mode');
canvas.style.cursor = 'default';
} else if (toolName === 'pen') {
canvas.classList.add('pen-mode');
canvas.style.cursor = ''; // Let CSS class handle it
} else if (toolName === 'highlight') {
canvas.classList.add('highlight-mode');
canvas.style.cursor = ''; // Let CSS class handle it
} else if (toolName === 'blur') {
canvas.classList.add('blur-mode');
canvas.style.cursor = ''; // Let CSS class handle it
} else if (toolName === 'text') {
canvas.style.cursor = 'text';
} else {
canvas.style.cursor = 'crosshair';
}
}
// Show/hide color picker based on tool
const colorGroup = document.querySelector('.color-group');
if (colorGroup) {
colorGroup.style.display = (toolName === 'blur') ? 'none' : 'flex';
}
redrawAnnotations();
}
// Prevent multiple listeners if script is injected multiple times
// Listen for messages from popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
logger.log('Content script received message:', request);
if (request.action === 'startCapture') {
logger.log('Starting area selection...');
try {
// Cancel any existing area selection
if (isSelectingArea) {
cancelAreaSelection();
}
// Pass mode from request (default to 'crop' for backward compatibility)
const mode = request.mode || 'crop';
startAreaSelection(mode);
sendResponse({ success: true });
} catch (error) {
logger.error('Error starting area selection:', error);
sendResponse({ success: false, error: error.message });
}
return true; // Keep channel open for async response
}
// Handle full-page capture
if (request.action === 'startFullPageCapture') {
logger.log('Starting full-page capture...');
try {
startFullPageCapture();
sendResponse({ success: true });
} catch (error) {
logger.error('Error starting full-page capture:', error);
sendResponse({ success: false, error: error.message });
}
return true;
}
return false;
});
// Signal that content script is ready
logger.log('Screenshot annotation content script loaded and ready');
function startAreaSelection(mode = 'crop') {
if (isSelectingArea) return;
isSelectingArea = true;
selectionMode = mode; // Store mode for later use
// Create selection overlay (iOS-style)
const overlay = document.createElement('div');
overlay.id = 'area-selection-overlay';
overlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, 0.3);
z-index: 999998;
cursor: crosshair;
`;
const selectionBox = document.createElement('div');
selectionBox.id = 'selection-box';
selectionBox.style.cssText = `
position: absolute;
border: 2px solid #007AFF;
background: rgba(0, 122, 255, 0.1);
pointer-events: none;
display: none;
border-radius: 4px;
box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.3);
`;
const instructions = document.createElement('div');
instructions.style.cssText = `
position: fixed;
top: 60px;
left: 50%;
transform: translateX(-50%);
background: rgba(0, 0, 0, 0.75);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
color: white;
padding: 12px 24px;
border-radius: 12px;
font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Text', sans-serif;
font-size: 15px;
font-weight: 500;
z-index: 999999;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
`;
// Update instruction text based on mode
if (mode === 'capture') {
instructions.textContent = 'Drag to select area • Release to capture selection';
} else {
instructions.textContent = 'Drag to select area • Release to capture';
}
overlay.appendChild(selectionBox);
overlay.appendChild(instructions);
document.body.appendChild(overlay);
document.body.style.overflow = 'hidden';
selectionOverlay = overlay;
// Mouse events for area selection
overlay.addEventListener('mousedown', handleSelectionStart);
overlay.addEventListener('mousemove', handleSelectionMove);
overlay.addEventListener('mouseup', handleSelectionEnd);
// Cancel on Escape
document.addEventListener('keydown', handleEscapeKey);
}
function handleEscapeKey(e) {
if (e.key === 'Escape' && isSelectingArea) {
cancelAreaSelection();
}
}
function handleSelectionStart(e) {
e.preventDefault();
e.stopPropagation();
isDraggingSelection = true;
const rect = selectionOverlay.getBoundingClientRect();
selectionStartX = e.clientX - rect.left;
selectionStartY = e.clientY - rect.top;
selectionEndX = selectionStartX;
selectionEndY = selectionStartY;
const selectionBox = document.getElementById('selection-box');
selectionBox.style.display = 'block';
selectionBox.style.left = selectionStartX + 'px';
selectionBox.style.top = selectionStartY + 'px';
selectionBox.style.width = '0px';
selectionBox.style.height = '0px';
}
function handleSelectionMove(e) {
if (!isSelectingArea || !isDraggingSelection) return;
const rect = selectionOverlay.getBoundingClientRect();
const currentX = e.clientX - rect.left;
const currentY = e.clientY - rect.top;
const selectionBox = document.getElementById('selection-box');
const left = Math.min(selectionStartX, currentX);
const top = Math.min(selectionStartY, currentY);
const width = Math.abs(currentX - selectionStartX);
const height = Math.abs(currentY - selectionStartY);
selectionBox.style.left = left + 'px';
selectionBox.style.top = top + 'px';
selectionBox.style.width = width + 'px';
selectionBox.style.height = height + 'px';
// Show dimension display during selection
const display = document.getElementById('dimension-display');
if (display && width > 0 && height > 0) {
const boxRect = selectionBox.getBoundingClientRect();
display.style.display = 'block';
display.style.left = (boxRect.left + boxRect.width / 2) + 'px';
display.style.top = (boxRect.top - 35) + 'px';
display.style.transform = 'translateX(-50%)';
display.textContent = `${Math.round(width)} × ${Math.round(height)}px`;
}
selectionEndX = currentX;
selectionEndY = currentY;
}
function handleSelectionEnd(e) {
if (!isSelectingArea || !isDraggingSelection) return;
e.preventDefault();
e.stopPropagation();
isDraggingSelection = false;
hideDimensionDisplay();
const width = Math.abs(selectionEndX - selectionStartX);
const height = Math.abs(selectionEndY - selectionStartY);
if (width > 10 && height > 10) {
// Valid selection - route based on mode
if (selectionMode === 'capture') {
// NEW: Selection-first mode - capture only selected area
captureSelectionOnly();
} else {
// EXISTING: Crop mode - capture full viewport then crop
captureSelectedArea();
}
} else {
// Selection too small, cancel
cancelAreaSelection();
}
}
function cancelAreaSelection() {
if (selectionOverlay) {
selectionOverlay.remove();
selectionOverlay = null;
}
hideDimensionDisplay();
document.body.style.overflow = '';
isSelectingArea = false;
isDraggingSelection = false;
document.removeEventListener('keydown', handleEscapeKey);
}
// ==================== CROP OVERLAY FUNCTIONS ====================
function showCropOverlay() {
logger.log('showCropOverlay() called, screenshotDataUrl:', screenshotDataUrl ? 'exists' : 'null');
isCropping = true;
uncropppedDataUrl = screenshotDataUrl;
// Create crop overlay
cropOverlay = document.createElement('div');
cropOverlay.id = 'crop-overlay';
cropOverlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, 0.9);
z-index: 1000000;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
`;
// Create toolbar
const toolbar = document.createElement('div');
toolbar.style.cssText = `
position: absolute;
top: 20px;
left: 50%;
transform: translateX(-50%);
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
padding: 12px 24px;
border-radius: 12px;
display: flex;
gap: 16px;
align-items: center;
font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Text', sans-serif;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
z-index: 999999;
`;
const instructions = document.createElement('span');
instructions.style.cssText = `
color: #333;
font-size: 14px;
font-weight: 500;
`;
instructions.textContent = 'Drag handles to crop • Drag image to reposition';
const skipBtn = document.createElement('button');
skipBtn.textContent = 'Skip';
skipBtn.style.cssText = `
background: #e0e0e0;
color: #333;
border: none;
padding: 8px 16px;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: background 0.2s;
`;
skipBtn.onmouseover = () => skipBtn.style.background = '#d0d0d0';
skipBtn.onmouseout = () => skipBtn.style.background = '#e0e0e0';
skipBtn.onclick = skipCrop;
const confirmBtn = document.createElement('button');
confirmBtn.textContent = 'Apply Crop';
confirmBtn.style.cssText = `
background: #007AFF;
color: white;
border: none;
padding: 8px 16px;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: background 0.2s;
`;
confirmBtn.onmouseover = () => confirmBtn.style.background = '#0056b3';
confirmBtn.onmouseout = () => confirmBtn.style.background = '#007AFF';
confirmBtn.onclick = applyCrop;
toolbar.appendChild(instructions);
toolbar.appendChild(skipBtn);
toolbar.appendChild(confirmBtn);
// Create image container
const imageContainer = document.createElement('div');
imageContainer.id = 'crop-image-container';
imageContainer.style.cssText = `
position: relative;
max-width: 90vw;
max-height: 80vh;
display: flex;
align-items: center;
justify-content: center;
`;
// Create the image
const img = document.createElement('img');
img.id = 'crop-source-image';
img.src = screenshotDataUrl;
img.style.cssText = `
max-width: 90vw;
max-height: 80vh;
object-fit: contain;
user-select: none;
-webkit-user-drag: none;
`;
// Create crop area (will be positioned after image loads)
const cropArea = document.createElement('div');
cropArea.id = 'crop-area';
cropArea.style.cssText = `
position: absolute;
border: 2px dashed #007AFF;
background: transparent;
cursor: move;
box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.5);
`;
// Create resize handles
const handles = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'];
handles.forEach(pos => {
const handle = document.createElement('div');
handle.className = 'crop-handle';
handle.dataset.handle = pos;
let cursor = 'move';
if (pos === 'nw' || pos === 'se') cursor = 'nwse-resize';
else if (pos === 'ne' || pos === 'sw') cursor = 'nesw-resize';
else if (pos === 'n' || pos === 's') cursor = 'ns-resize';
else if (pos === 'e' || pos === 'w') cursor = 'ew-resize';
handle.style.cssText = `
position: absolute;
width: 12px;
height: 12px;
background: #007AFF;
border: 2px solid white;
border-radius: 50%;
cursor: ${cursor};
z-index: 10;
`;
// Position handles
if (pos.includes('n')) handle.style.top = '-6px';
if (pos.includes('s')) handle.style.bottom = '-6px';
if (pos.includes('w')) handle.style.left = '-6px';
if (pos.includes('e')) handle.style.right = '-6px';
if (pos === 'n' || pos === 's') {
handle.style.left = '50%';
handle.style.transform = 'translateX(-50%)';
}
if (pos === 'e' || pos === 'w') {
handle.style.top = '50%';
handle.style.transform = 'translateY(-50%)';
}
if (pos === 'nw') { handle.style.top = '-6px'; handle.style.left = '-6px'; }
if (pos === 'ne') { handle.style.top = '-6px'; handle.style.right = '-6px'; }
if (pos === 'sw') { handle.style.bottom = '-6px'; handle.style.left = '-6px'; }
if (pos === 'se') { handle.style.bottom = '-6px'; handle.style.right = '-6px'; }
cropArea.appendChild(handle);
});
// Create dimension display for crop
const cropDimDisplay = document.createElement('div');
cropDimDisplay.id = 'crop-dimension-display';
cropDimDisplay.style.cssText = `
position: absolute;
bottom: -30px;
left: 50%;
transform: translateX(-50%);
background: rgba(0, 0, 0, 0.75);
color: white;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
font-family: -apple-system, BlinkMacSystemFont, monospace;
white-space: nowrap;
`;
cropArea.appendChild(cropDimDisplay);
imageContainer.appendChild(img);
imageContainer.appendChild(cropArea);
cropOverlay.appendChild(toolbar);
cropOverlay.appendChild(imageContainer);
document.body.appendChild(cropOverlay);
document.body.style.overflow = 'hidden';
// Initialize crop area after image loads
img.onload = () => {
const imgRect = img.getBoundingClientRect();
const containerRect = imageContainer.getBoundingClientRect();
// Calculate image position within container
const imgLeft = (containerRect.width - imgRect.width) / 2;
const imgTop = (containerRect.height - imgRect.height) / 2;
// Initialize crop rect to full image
cropRect = {
x: 0,
y: 0,
width: imgRect.width,
height: imgRect.height
};
updateCropAreaDisplay();
};
// Add event listeners
cropArea.addEventListener('mousedown', handleCropMouseDown);
document.addEventListener('mousemove', handleCropMouseMove);
document.addEventListener('mouseup', handleCropMouseUp);
document.addEventListener('keydown', handleCropKeyDown);
}
function updateCropAreaDisplay() {
const cropArea = document.getElementById('crop-area');
const img = document.getElementById('crop-source-image');
const dimDisplay = document.getElementById('crop-dimension-display');
if (!cropArea || !img) return;
const imgRect = img.getBoundingClientRect();
const container = document.getElementById('crop-image-container');
const containerRect = container.getBoundingClientRect();
// Calculate image offset within container
const imgOffsetX = (containerRect.width - imgRect.width) / 2;
const imgOffsetY = (containerRect.height - imgRect.height) / 2;
// Clamp crop rect to image bounds
cropRect.x = Math.max(0, Math.min(cropRect.x, imgRect.width - 20));
cropRect.y = Math.max(0, Math.min(cropRect.y, imgRect.height - 20));
cropRect.width = Math.max(20, Math.min(cropRect.width, imgRect.width - cropRect.x));
cropRect.height = Math.max(20, Math.min(cropRect.height, imgRect.height - cropRect.y));
cropArea.style.left = (imgOffsetX + cropRect.x) + 'px';
cropArea.style.top = (imgOffsetY + cropRect.y) + 'px';
cropArea.style.width = cropRect.width + 'px';
cropArea.style.height = cropRect.height + 'px';
// Update dimension display with actual pixel dimensions
const scaleX = img.naturalWidth / imgRect.width;
const scaleY = img.naturalHeight / imgRect.height;
const actualWidth = Math.round(cropRect.width * scaleX);
const actualHeight = Math.round(cropRect.height * scaleY);
dimDisplay.textContent = `${actualWidth} × ${actualHeight}px`;
}
function handleCropMouseDown(e) {
e.preventDefault();
e.stopPropagation();
const handle = e.target.closest('.crop-handle');
if (handle) {
cropDragType = handle.dataset.handle;
} else {
cropDragType = 'move';
}
cropDragStartX = e.clientX;
cropDragStartY = e.clientY;
cropInitialRect = { ...cropRect };
}
function handleCropMouseMove(e) {
if (!cropDragType || !cropInitialRect) return;
const img = document.getElementById('crop-source-image');
if (!img) return;
const imgRect = img.getBoundingClientRect();
const dx = e.clientX - cropDragStartX;
const dy = e.clientY - cropDragStartY;
if (cropDragType === 'move') {
cropRect.x = Math.max(0, Math.min(cropInitialRect.x + dx, imgRect.width - cropRect.width));
cropRect.y = Math.max(0, Math.min(cropInitialRect.y + dy, imgRect.height - cropRect.height));
} else {
// Handle resize
let newX = cropInitialRect.x;
let newY = cropInitialRect.y;
let newWidth = cropInitialRect.width;
let newHeight = cropInitialRect.height;
if (cropDragType.includes('w')) {
newX = Math.max(0, Math.min(cropInitialRect.x + dx, cropInitialRect.x + cropInitialRect.width - 20));
newWidth = cropInitialRect.width - (newX - cropInitialRect.x);
}
if (cropDragType.includes('e')) {
newWidth = Math.max(20, Math.min(cropInitialRect.width + dx, imgRect.width - cropInitialRect.x));
}
if (cropDragType.includes('n')) {
newY = Math.max(0, Math.min(cropInitialRect.y + dy, cropInitialRect.y + cropInitialRect.height - 20));
newHeight = cropInitialRect.height - (newY - cropInitialRect.y);
}
if (cropDragType.includes('s')) {
newHeight = Math.max(20, Math.min(cropInitialRect.height + dy, imgRect.height - cropInitialRect.y));
}
cropRect.x = newX;
cropRect.y = newY;
cropRect.width = newWidth;
cropRect.height = newHeight;
}
updateCropAreaDisplay();
}
function handleCropMouseUp(e) {
cropDragType = null;
cropInitialRect = null;
}
function handleCropKeyDown(e) {
if (e.key === 'Escape') {
cancelCrop();
} else if (e.key === 'Enter') {
applyCrop();
}
}
function skipCrop() {
closeCropOverlay();
showAnnotationOverlay();
}
function cancelCrop() {
closeCropOverlay();
// Reset to uncropped state
screenshotDataUrl = uncropppedDataUrl;
uncropppedDataUrl = null;
}
function applyCrop() {
const img = document.getElementById('crop-source-image');
if (!img) {
skipCrop();
return;
}
const imgRect = img.getBoundingClientRect();
const scaleX = img.naturalWidth / imgRect.width;
const scaleY = img.naturalHeight / imgRect.height;
// Create canvas for cropped image
const canvas = document.createElement('canvas');
canvas.width = Math.round(cropRect.width * scaleX);
canvas.height = Math.round(cropRect.height * scaleY);
const ctx = canvas.getContext('2d', { alpha: false, colorSpace: 'srgb' });
ctx.imageSmoothingEnabled = false;
// Draw cropped portion
ctx.drawImage(
img,
Math.round(cropRect.x * scaleX),
Math.round(cropRect.y * scaleY),
canvas.width,
canvas.height,
0,
0,
canvas.width,
canvas.height
);
// Update screenshot data URL
screenshotDataUrl = canvas.toDataURL('image/png');
uncropppedDataUrl = null;
closeCropOverlay();
showAnnotationOverlay();
}
function closeCropOverlay() {
if (cropOverlay) {
cropOverlay.remove();
cropOverlay = null;
}
document.body.style.overflow = '';
isCropping = false;
document.removeEventListener('mousemove', handleCropMouseMove);
document.removeEventListener('mouseup', handleCropMouseUp);
document.removeEventListener('keydown', handleCropKeyDown);
}
// ==================== END CROP OVERLAY FUNCTIONS ====================
async function captureSelectedArea() {
// Get selection coordinates relative to viewport
const selectionBox = document.getElementById('selection-box');
const boxRect = selectionBox.getBoundingClientRect();
// Remove selection overlay BEFORE capturing
cancelAreaSelection();
// Wait for the overlay to be fully removed from the DOM and screen repainted
// Using multiple rAF frames + small timeout to ensure browser has fully rendered
await new Promise(resolve => {
requestAnimationFrame(() => {
requestAnimationFrame(() => {
// Additional small delay to ensure the repaint is complete
setTimeout(resolve, 50);
});
});
});
// Capture full screenshot (overlay should now be completely gone)
chrome.runtime.sendMessage({ action: 'captureScreenshot' }, (response) => {
if (chrome.runtime.lastError) {
logger.error('Error capturing screenshot:', chrome.runtime.lastError);
alert('Error capturing screenshot: ' + chrome.runtime.lastError.message);
isSelectingArea = false;
return;
}
if (response && response.success) {
// Crop to selected area
const img = new Image();
img.onload = () => {
// Calculate scale factor (screenshot might be different size than viewport due to DPI)
const scaleX = img.naturalWidth / window.innerWidth;
const scaleY = img.naturalHeight / window.innerHeight;
// Use native resolution for best quality
const canvas = document.createElement('canvas');
canvas.width = Math.round(boxRect.width * scaleX);
canvas.height = Math.round(boxRect.height * scaleY);
// Use alpha:false for opaque screenshots (better color accuracy)
const ctx = canvas.getContext('2d', { alpha: false, colorSpace: 'srgb' });
// Disable image smoothing for pixel-perfect capture
ctx.imageSmoothingEnabled = false;
// Draw cropped area at native resolution
ctx.drawImage(
img,
Math.round(boxRect.left * scaleX),
Math.round(boxRect.top * scaleY),
Math.round(boxRect.width * scaleX),
Math.round(boxRect.height * scaleY),
0,
0,
canvas.width,
canvas.height
);
// Convert to data URL - PNG doesn't use quality parameter but keeping for clarity
screenshotDataUrl = canvas.toDataURL('image/png');
showCropOverlay();
};
img.src = response.dataUrl;
} else {
logger.error('Screenshot capture failed:', response);
alert('Failed to capture screenshot. ' + (response?.error || 'Unknown error'));
isSelectingArea = false;
}
});
}
// Capture selection-only mode (select area first, then capture)
async function captureSelectionOnly() {
// Get selection coordinates
const selectionBox = document.getElementById('selection-box');
if (!selectionBox) return;
const boxRect = selectionBox.getBoundingClientRect();
// Store coordinates before removing overlay
const selectionRect = {
left: boxRect.left,
top: boxRect.top,
width: boxRect.width,
height: boxRect.height
};
// Remove selection overlay BEFORE capturing
cancelAreaSelection();
// Wait for overlay removal
await new Promise(resolve => {
requestAnimationFrame(() => {
requestAnimationFrame(() => {
setTimeout(resolve, 50);
});
});
});
// Capture full viewport
chrome.runtime.sendMessage({ action: 'captureScreenshot' }, (response) => {
if (chrome.runtime.lastError) {
logger.error('Error capturing screenshot:', chrome.runtime.lastError);
alert('Error capturing screenshot: ' + chrome.runtime.lastError.message);
return;
}
if (response && response.success) {
// Immediately crop to selection and skip crop overlay
const img = new Image();
img.onload = () => {
// Calculate scale factor for high-DPI displays
const scaleX = img.naturalWidth / window.innerWidth;
const scaleY = img.naturalHeight / window.innerHeight;
// Create cropped canvas
const canvas = document.createElement('canvas');
canvas.width = Math.round(selectionRect.width * scaleX);