-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1891 lines (1654 loc) · 83.2 KB
/
content.js
File metadata and controls
1891 lines (1654 loc) · 83.2 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.js
(function() {
// Prevent multiple injections
if (document.getElementById('drawing-toolbar-extension')) {
return;
}
// --- Configuration ---
const TOOLBAR_ID = 'drawing-toolbar-extension';
const CANVAS_ID = 'drawing-canvas-extension';
const PREFIX = 'dt-';
const INVITE_DIALOG_ID = 'dt-invite-dialog';
const EXPORT_DIALOG_ID = 'dt-export-choice-dialog';
const SHARE_DIALOG_ID = 'dt-share-dialog';
const INVITE_URL_BASE = 'https://annotateweb.com/?join=';
const SHARE_API_BASE = 'https://annotateweb.surfly.workers.dev/';
// --- State ---
let currentTool = 'navigate';
let currentColor = '#6200d9';
let currentLineWidth = 5;
let isDrawing = false;
let startX, startY; // These will become document-relative
let canvas, ctx;
let snapshot;
let drawingOperations = []; // To store all drawing operations
let undoStack = []; // To store operations that were undone (for redo)
let currentPath = null; // To store current pen/eraser path
let isDraggingToolbar = false;
let toolbarOffsetX, toolbarOffsetY;
// --- Helper Functions --- (No changes)
function hexToRgba(hex, alpha = 1) {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}
// Generate short UUID for sharing
function generateShortId() {
return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
}
// Helper function to get document-relative coordinates from mouse or touch events
function getDocumentRelativeCoordinates(event) {
// Handle touch events
if (event.touches && event.touches.length > 0) {
// Use the first touch point
return {
x: event.touches[0].clientX + window.scrollX,
y: event.touches[0].clientY + window.scrollY
};
} else if (event.changedTouches && event.changedTouches.length > 0) {
// For touchend/touchcancel events where touches[] is empty
return {
x: event.changedTouches[0].clientX + window.scrollX,
y: event.changedTouches[0].clientY + window.scrollY
};
}
// Handle mouse events
return {
x: event.clientX + window.scrollX,
y: event.clientY + window.scrollY
};
}
// NEW: Function to draw all stored annotations onto a given canvas context
function drawAnnotationsOnCanvas(targetCtx, operations, offsetX = 0, offsetY = 0) {
if (!targetCtx || !operations) return;
operations.forEach(op => {
targetCtx.strokeStyle = op.color;
targetCtx.fillStyle = op.color;
targetCtx.lineWidth = op.lineWidth;
targetCtx.globalCompositeOperation = op.compositeOperation || 'source-over';
targetCtx.beginPath();
if (op.tool === 'pen' || op.tool === 'eraser' || op.tool === 'highlight') {
if (op.points && op.points.length > 0) {
const firstPoint = op.points[0];
targetCtx.moveTo(firstPoint.x - offsetX, firstPoint.y - offsetY);
for (let i = 1; i < op.points.length; i++) {
const point = op.points[i];
targetCtx.lineTo(point.x - offsetX, point.y - offsetY);
}
targetCtx.stroke();
}
} else if (op.tool === 'rectangle') {
targetCtx.strokeRect(
op.startX - offsetX,
op.startY - offsetY,
op.endX - op.startX,
op.endY - op.startY
);
} else if (op.tool === 'line') {
targetCtx.moveTo(op.startX - offsetX, op.startY - offsetY);
targetCtx.lineTo(op.endX - offsetX, op.endY - offsetY);
targetCtx.stroke();
} else if (op.tool === 'circle') {
targetCtx.arc(
op.centerX - offsetX,
op.centerY - offsetY,
op.radius,
0,
2 * Math.PI
);
targetCtx.stroke();
} else if (op.tool === 'text') {
targetCtx.font = op.font;
const fontSize = parseFloat(op.font) || 16;
targetCtx.fillText(op.text, op.x - offsetX, op.y - offsetY + fontSize);
}
});
targetCtx.globalCompositeOperation = 'source-over'; // Reset
}
// --- UI Creation ---
function createToolbar() {
const toolbar = document.createElement('div');
toolbar.id = TOOLBAR_ID;
toolbar.className = `${PREFIX}toolbar`;
toolbar.innerHTML = `
<div class="${PREFIX}toolbar-rows">
<!-- First Row: Drawing Tools -->
<div class="${PREFIX}toolbar-row">
<div class="${PREFIX}tool-group">
<button data-tool="navigate" class="${PREFIX}tool-button" title="Navigate Website">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"><!-- Icon from Lucide by Lucide Contributors - https://github.com/lucide-icons/lucide/blob/main/LICENSE --><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 4.1L12 6M5.1 8l-2.9-.8M6 12l-1.9 2M7.2 2.2L8 5.1m1.037 4.59a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.074z"/></svg>
</button>
<button data-tool="highlight" class="${PREFIX}tool-button" title="Highlight">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"><g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"><path d="m9 11l-6 6v3h9l3-3"/><path d="m22 12l-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4"/></g></svg>
</button>
<button data-tool="pen" class="${PREFIX}tool-button" title="Pen">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"><!-- Icon from Lucide by Lucide Contributors - https://github.com/lucide-icons/lucide/blob/main/LICENSE --><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"/></svg>
</button>
<button data-tool="line" class="${PREFIX}tool-button" title="Line">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"><!-- Icon from Lucide by Lucide Contributors - https://github.com/lucide-icons/lucide/blob/main/LICENSE --><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 20h9M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z"/></svg>
</button>
<button data-tool="rectangle" class="${PREFIX}tool-button" title="Rectangle">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"><!-- Icon from Lucide by Lucide Contributors - https://github.com/lucide-icons/lucide/blob/main/LICENSE --><rect width="20" height="12" x="2" y="6" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" rx="2"/></svg>
</button>
<button data-tool="circle" class="${PREFIX}tool-button" title="Circle">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"><!-- Icon from Lucide by Lucide Contributors - https://github.com/lucide-icons/lucide/blob/main/LICENSE --><circle cx="12" cy="12" r="10" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"/></svg>
</button>
<button data-tool="text" class="${PREFIX}tool-button" title="Text">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"><!-- Icon from Lucide by Lucide Contributors - https://github.com/lucide-icons/lucide/blob/main/LICENSE --><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 22h-1a4 4 0 0 1-4-4V6a4 4 0 0 1 4-4h1M7 22h1a4 4 0 0 0 4-4v-1M7 2h1a4 4 0 0 1 4 4v1"/></svg>
</button>
<button data-tool="eraser" class="${PREFIX}tool-button" title="Eraser">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"><!-- Icon from Lucide by Lucide Contributors - https://github.com/lucide-icons/lucide/blob/main/LICENSE --><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m7 21l-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21m9 0H7M5 11l9 9"/></svg>
</button>
</div>
<div class="${PREFIX}drag-handle"></div>
</div>
<!-- Second Row: Controls and Actions -->
<div class="${PREFIX}toolbar-row">
<div class="${PREFIX}tool-group ${PREFIX}actions">
<button id="${PREFIX}export-button" class="${PREFIX}tool-button" title="Export to Image">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"><!-- Icon from Lucide by Lucide Contributors - https://github.com/lucide-icons/lucide/blob/main/LICENSE --><g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></g></svg>
</button>
<button id="${PREFIX}share-button" class="${PREFIX}tool-button" title="Share Annotations">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"><g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"><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"/></g></svg>
</button>
<button id="${PREFIX}invite-button" class="${PREFIX}tool-button" title="Invite">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"><g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="8.5" cy="7" r="4"></circle><line x1="20" y1="8" x2="20" y2="14"></line><line x1="23" y1="11" x2="17" y2="11"></line></g></svg>
</button>
<button id="${PREFIX}undo-button" class="${PREFIX}tool-button" title="Undo">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 14 4 9l5-5M4 9h11c4 0 6 2 6 6s-2 6-6 6h-5"/></svg>
</button>
<button id="${PREFIX}redo-button" class="${PREFIX}tool-button" title="Redo">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m15 14 5-5-5-5M20 9H9c-4 0-6 2-6 6s2 6 6 6h5"/></svg>
</button>
<button id="${PREFIX}clear-button" class="${PREFIX}tool-button" title="Clear Canvas">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"><!-- Icon from Lucide by Lucide Contributors - https://github.com/lucide-icons/lucide/blob/main/LICENSE --><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 6h18m-2 0v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6m3 0V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2m-6 5v6m4-6v6"/></svg>️
</button>
</div>
<div class="${PREFIX}tool-group">
<input type="color" id="${PREFIX}color-picker" value="${currentColor}" title="Color Picker">
<select id="${PREFIX}line-width" title="Line Width">
<option value="3">3px</option>
<option value="5" selected>5px</option>
<option value="8">8px</option>
<option value="12">12px</option>
<option value="20">20px</option>
</select>
</div>
</div>
</div>
`;
document.body.appendChild(toolbar);
// Toolbar Dragging Logic
const dragHandle = toolbar.querySelector(`.${PREFIX}drag-handle`);
// Ensure the drag handle is properly set up
if (dragHandle) {
// Mouse drag support
dragHandle.addEventListener('mousedown', (e) => {
e.stopPropagation(); // Stop event from bubbling to parent elements
isDraggingToolbar = true;
const currentRect = toolbar.getBoundingClientRect(); // Get current position
toolbarOffsetX = e.clientX - currentRect.left;
toolbarOffsetY = e.clientY - currentRect.top;
toolbar.style.transform = 'none'; // Remove transform for direct positioning
toolbar.style.left = `${currentRect.left}px`; // Set explicit left/top
toolbar.style.top = `${currentRect.top}px`;
toolbar.style.bottom = 'auto'; // Clear bottom positioning for mobile
// Don't set width and height here to prevent toolbar growth
});
// Touch drag support
dragHandle.addEventListener('touchstart', (e) => {
e.preventDefault(); // Prevent scrolling when trying to drag the toolbar
e.stopPropagation(); // Stop event from bubbling to parent elements
isDraggingToolbar = true;
const currentRect = toolbar.getBoundingClientRect(); // Get current position
toolbarOffsetX = e.touches[0].clientX - currentRect.left;
toolbarOffsetY = e.touches[0].clientY - currentRect.top;
toolbar.style.transform = 'none'; // Remove transform for direct positioning
toolbar.style.left = `${currentRect.left}px`; // Set explicit left/top
toolbar.style.top = `${currentRect.top}px`;
toolbar.style.bottom = 'auto'; // Clear bottom positioning for mobile
// Don't set width and height here to prevent toolbar growth
dragHandle.style.cursor = 'grabbing';
document.body.style.userSelect = 'none'; // Prevent text selection while dragging
e.preventDefault();
});
}
// Toolbar Event Listeners
toolbar.querySelectorAll(`.${PREFIX}tool-button[data-tool]`).forEach(button => {
button.addEventListener('click', () => selectTool(button.dataset.tool));
});
document.getElementById(`${PREFIX}color-picker`).addEventListener('input', (e) => {
currentColor = e.target.value;
if (ctx) {
ctx.strokeStyle = currentColor;
ctx.fillStyle = currentColor;
}
if (currentTool !== 'navigate') applyToolSettings();
selectTool(currentTool); // To update pen cursor color
});
document.getElementById(`${PREFIX}line-width`).addEventListener('change', (e) => {
currentLineWidth = parseInt(e.target.value, 10);
if (ctx) ctx.lineWidth = currentLineWidth;
if (currentTool !== 'navigate') applyToolSettings();
selectTool(currentTool); // To update eraser cursor size
});
document.getElementById(`${PREFIX}undo-button`).addEventListener('click', undoOperation);
document.getElementById(`${PREFIX}redo-button`).addEventListener('click', redoOperation);
document.getElementById(`${PREFIX}clear-button`).addEventListener('click', clearCanvas);
}
function addGlobalDragListeners() {
// Mouse move event for dragging
window.addEventListener('mousemove', (e) => {
if (isDraggingToolbar) {
const tb = document.getElementById(TOOLBAR_ID);
if (!tb) { // Safety check
isDraggingToolbar = false;
return;
}
let newX = e.clientX - toolbarOffsetX;
let newY = e.clientY - toolbarOffsetY;
// Constrain to viewport
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
const toolbarRect = tb.getBoundingClientRect();
if (newX < 0) newX = 0;
if (newY < 0) newY = 0;
if (newX + toolbarRect.width > viewportWidth) newX = viewportWidth - toolbarRect.width;
if (newY + toolbarRect.height > viewportHeight) newY = viewportHeight - toolbarRect.height;
// Apply new position
tb.style.left = `${newX}px`;
tb.style.top = `${newY}px`;
e.preventDefault(); // Prevent any default behavior while dragging
}
}, { passive: false }); // Important: passive: false to allow preventDefault
// Touch move event for dragging on touch devices
window.addEventListener('touchmove', (e) => {
if (isDraggingToolbar) {
e.preventDefault(); // Prevent scrolling while dragging toolbar
const tb = document.getElementById(TOOLBAR_ID);
if (!tb || !e.touches || e.touches.length === 0) { // Safety check
isDraggingToolbar = false;
return;
}
let newX = e.touches[0].clientX - toolbarOffsetX;
let newY = e.touches[0].clientY - toolbarOffsetY;
// Constrain to viewport
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
const toolbarRect = tb.getBoundingClientRect();
if (newX < 0) newX = 0;
if (newY < 0) newY = 0;
if (newX + toolbarRect.width > viewportWidth) newX = viewportWidth - toolbarRect.width;
if (newY + toolbarRect.height > viewportHeight) newY = viewportHeight - toolbarRect.height;
// Apply new position
tb.style.left = `${newX}px`;
tb.style.top = `${newY}px`;
}
}, { passive: false }); // Important: passive: false to allow preventDefault
// Mouse up event to end dragging
window.addEventListener('mouseup', (e) => {
if (isDraggingToolbar) {
isDraggingToolbar = false;
const tb = document.getElementById(TOOLBAR_ID);
if (tb) {
const dragHandle = tb.querySelector(`.${PREFIX}drag-handle`);
if (dragHandle) dragHandle.style.cursor = 'grab';
}
document.body.style.userSelect = ''; // Re-enable text selection
}
});
// Touch end event to end dragging on touch devices
window.addEventListener('touchend', (e) => {
if (isDraggingToolbar) {
isDraggingToolbar = false;
const tb = document.getElementById(TOOLBAR_ID);
if (tb) {
const dragHandle = tb.querySelector(`.${PREFIX}drag-handle`);
if (dragHandle) dragHandle.style.cursor = 'grab';
}
document.body.style.userSelect = ''; // Re-enable text selection
}
});
// Touch cancel event to handle interrupted touch events
window.addEventListener('touchcancel', (e) => {
if (isDraggingToolbar) {
isDraggingToolbar = false;
const tb = document.getElementById(TOOLBAR_ID);
if (tb) {
const dragHandle = tb.querySelector(`.${PREFIX}drag-handle`);
if (dragHandle) dragHandle.style.cursor = 'grab';
}
document.body.style.userSelect = '';
}
});
}
function createCanvas() { // MODIFIED
canvas = document.createElement('canvas');
canvas.id = CANVAS_ID;
canvas.className = `${PREFIX}canvas`;
// Set canvas dimensions to the viewport size
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Style canvas to be fixed position, covering the viewport
canvas.style.position = 'fixed';
canvas.style.top = '0';
canvas.style.left = '0';
canvas.style.zIndex = '2147483645'; // Ensure it's below toolbar (toolbar is often 2147483647 or higher)
canvas.style.pointerEvents = 'none'; // Initially no pointer events, enabled by selectTool for drawing tools
document.body.appendChild(canvas);
ctx = canvas.getContext('2d');
applyToolSettings();
// Event listeners (mousedown, mousemove, mouseup, mouseleave) remain,
// but their effectiveness is now gated by canvas.style.pointerEvents and the isDrawing flag.
// Mouse event listeners
canvas.addEventListener('mousedown', startDrawing);
window.addEventListener('mousemove', draw); // Keep global for drawing continuity if mouse leaves canvas while drawing
window.addEventListener('mouseup', stopDrawing); // Keep global to catch mouseup even if outside canvas
window.addEventListener('mouseleave', stopDrawingOnLeave); // Specifically for mouse leaving window
// Touch event listeners
canvas.addEventListener('touchstart', startDrawing, { passive: false });
window.addEventListener('touchmove', draw, { passive: false }); // Keep global for drawing continuity if touch leaves canvas
window.addEventListener('touchend', stopDrawing); // Keep global to catch touchend even if outside canvas
window.addEventListener('touchcancel', stopDrawingOnLeave); // Handle touch cancellation
}
function addStyles() {
const style = document.createElement('style');
style.textContent = `
.${PREFIX}toolbar {
position: fixed;
top: 20px; /* Initial position */
left: 50%;
transform: translateX(-50%); /* Initial centering */
background: linear-gradient(145deg, #2c3e50 0%, #1a252f 100%);
border: 1px solid #11181f;
border-top: 1px solid #4a5c6d; /* Subtle top highlight */
border-radius: 8px;
padding: 5px 8px; /* Reduced padding a bit */
box-shadow: 0 4px 12px rgba(0,0,0,0.4), inset 0 1px 0px rgba(255,255,255,0.05);
z-index: 2147483646;
font-family: 'Segoe UI', 'Roboto', sans-serif;
color: #e0e0e0;
cursor: grab; /* Indicate draggable */
transition: opacity 0.3s, visibility 0.3s; /* For toggle */
max-width: calc(100% - 20px); /* Prevent overflow on small screens */
width: auto; /* Allow it to be as wide as needed, but not more than max-width */
}
.${PREFIX}toolbar-rows {
display: flex;
flex-direction: column;
gap: 8px;
width: 100%;
}
.${PREFIX}toolbar-row {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
justify-content: flex-start; /* Align items to the left */
}
.${PREFIX}toolbar.hidden {
opacity: 0;
visibility: hidden;
pointer-events: none;
}
.${PREFIX}drag-handle { /* Dedicated drag area */
width: 20px;
height: 24px;
background: repeating-linear-gradient(-45deg, transparent, transparent 2px, rgba(255,255,255,0.1) 2px, rgba(255,255,255,0.1) 4px);
margin-right: 5px;
border-radius: 4px;
cursor: grab;
flex-shrink: 0; /* Prevent drag handle from shrinking */
}
.${PREFIX}tool-group {
display: flex;
flex-wrap: wrap; /* Allow tool buttons to wrap within groups */
gap: 5px;
align-items: center;
padding: 3px 5px;
background: rgba(0,0,0,0.1);
border-radius: 5px;
/* Make sure the tool group can shrink if needed but maintain a minimum size */
min-width: 80px;
justify-content: flex-start; /* Align items to the left */
}
.${PREFIX}tool-group.${PREFIX}actions {
background: transparent; /* Actions group might not need own background */
}
/* Responsive adjustments */
@media (max-width: 768px) {
.${PREFIX}toolbar {
top: auto; /* Move to bottom on small screens */
bottom: 10px;
padding: 4px 6px; /* Slightly smaller padding */
}
.${PREFIX}tool-group {
gap: 3px; /* Smaller gap on small screens */
padding: 2px 4px; /* Smaller padding */
}
}
@media (max-width: 480px) {
.${PREFIX}toolbar {
left: 10px;
right: 10px;
transform: none; /* Don't use transform on small screens for better performance */
width: calc(100% - 20px); /* Full width minus margins */
max-width: none; /* Override max-width */
}
.${PREFIX}tool-button {
padding: 5px 7px !important; /* Smaller buttons */
}
/* Make sure the rows stack nicely on very small screens */
.${PREFIX}tool-group {
flex-grow: 1;
justify-content: center;
}
}
.${PREFIX}tool-button {
background: linear-gradient(to bottom, #3a4b5c, #2c3a47);
border: 1px solid #1e2833;
color: #d0d8e0;
padding: 7px 9px;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
transition: all 0.15s ease-out;
box-shadow: inset 0 1px 0px rgba(255,255,255,0.08), 0 1px 1px rgba(0,0,0,0.2);
line-height: 1;
display: flex; /* Improve button layout */
align-items: center;
justify-content: center;
min-width: 34px; /* Ensure minimum button size for touch */
min-height: 34px; /* Ensure minimum button size for touch */
}
.${PREFIX}tool-button:hover {
background: linear-gradient(to bottom, #4a5f73, #364655);
border-color: #2a3845;
color: #ffffff;
}
.${PREFIX}tool-button.${PREFIX}active {
background: linear-gradient(to bottom, #00bfff, #009acd); /* Deep sky blue / Cyanish */
color: #ffffff;
border-color: #007aa3;
box-shadow: inset 0 1px 2px rgba(0,0,0,0.3), 0 1px 0px rgba(255,255,255,0.1);
}
/* Special styling for navigate button when active */
.${PREFIX}tool-button[data-tool="navigate"].${PREFIX}active {
background: linear-gradient(to bottom, #8e44ad, #7d3c98); /* Purple gradient for active */
border-color: #6c3483;
font-weight: bold;
}
.${PREFIX}tool-button[data-tool="navigate"].${PREFIX}active:hover {
background: linear-gradient(to bottom, #a569bd, #8e44ad);
border-color: #5b2c6f;
}
#${PREFIX}color-picker {
width: 36px;
height: 32px;
border: 1px solid #1e2833;
border-radius: 4px;
padding: 0;
cursor: pointer;
background-color: #2c3a47;
box-shadow: inset 0 1px 0px rgba(255,255,255,0.05);
min-width: 34px; /* Ensure minimum touch size */
min-height: 34px; /* Ensure minimum touch size */
}
#${PREFIX}color-picker::-webkit-color-swatch-wrapper { padding: 2px; }
#${PREFIX}color-picker::-webkit-color-swatch {
border: 1px solid #506070;
border-radius: 2px;
}
#${PREFIX}line-width {
padding: 7px 5px;
border-radius: 4px;
border: 1px solid #1e2833;
background-color: #2c3a47;
color: #d0d8e0;
font-size: 13px;
box-shadow: inset 0 1px 0px rgba(255,255,255,0.05);
}
#${PREFIX}line-width option {
background-color: #2c3a47;
color: #d0d8e0;
}
.${PREFIX}canvas {
position: fixed; /* Changed from absolute */
top: 0;
left: 0;
/* width and height will be set dynamically */
z-index: 2147483645; /* Below toolbar, above page */
pointer-events: none;
transition: opacity 0.3s, visibility 0.3s;
}
.${PREFIX}canvas.${PREFIX}drawing-active { pointer-events: auto; }
.${PREFIX}canvas.hidden {
opacity: 0;
visibility: hidden;
pointer-events: none;
}
/* Styles for temporary text input */
.${PREFIX}text-input {
position: fixed;
z-index: 2147483647; /* Max z-index, above canvas/toolbar */
background-color: white !important;
border: 2px solid #6200d9 !important;
border-radius: 4px !important;
padding: 8px !important;
font-size: 16px !important;
color: #333 !important;
min-width: 120px !important;
max-width: 180px !important;
width: auto !important;
box-shadow: 0 2px 8px rgba(0,0,0,0.3) !important;
outline: none !important;
font-family: Arial, sans-serif !important;
transition: border-color 0.2s !important;
margin: 0 !important;
line-height: 1.4 !important;
}
.${PREFIX}text-input:focus {
border-color: #4800a0 !important;
box-shadow: 0 2px 12px rgba(98, 0, 217, 0.4) !important;
}
`;
document.head.appendChild(style);
}
// --- Drawing Logic & Tool Management ---
function applyToolSettings() { // (Largely same as before)
if (!ctx || !canvas) return;
if (currentTool === 'eraser') {
ctx.globalCompositeOperation = 'destination-out';
ctx.lineWidth = Math.max(5, currentLineWidth * 1.5); // Eraser typically larger
ctx.strokeStyle = 'rgba(0,0,0,1)'; // Eraser color doesn't matter for destination-out
} else if (currentTool === 'highlight') {
ctx.globalCompositeOperation = 'source-over';
ctx.lineWidth = Math.max(8, currentLineWidth * 2); // Highlighter is wider
ctx.strokeStyle = hexToRgba(currentColor, 0.4); // Semi-transparent version of the color
ctx.fillStyle = hexToRgba(currentColor, 0.4);
} else if (currentTool === 'text') {
// Text tool specific settings (e.g., font) can be applied here if needed when text is drawn
// For now, ensure it doesn't inherit drawing styles meant for shapes/pen
ctx.globalCompositeOperation = 'source-over'; // Default drawing mode
// Potentially set font here, e.g., ctx.font = "16px Arial";
} else {
ctx.globalCompositeOperation = 'source-over';
ctx.lineWidth = currentLineWidth; // Apply the current line width
ctx.strokeStyle = currentColor;
ctx.fillStyle = currentColor;
}
}
function selectTool(tool) {
currentTool = tool;
const buttons = document.querySelectorAll(`.${PREFIX}tool-button`);
buttons.forEach(button => button.classList.remove(`${PREFIX}active`));
const selectedButton = document.querySelector(`.${PREFIX}tool-button[data-tool="${tool}"]`);
if (selectedButton) {
selectedButton.classList.add(`${PREFIX}active`);
}
if (!canvas) return;
switch (tool) {
case 'pen':
case 'line':
case 'rectangle':
case 'circle':
case 'highlight': // Added highlight tool
case 'eraser':
case 'text': // Text tool also needs pointer events on canvas for click
canvas.style.cursor = (tool === 'text') ? 'text' : 'crosshair';
canvas.style.pointerEvents = 'auto'; // Enable drawing interactions
break;
case 'navigate':
default:
canvas.style.cursor = 'default';
canvas.style.pointerEvents = 'none'; // Disable drawing interactions on canvas itself
break;
}
// Clear any existing temporary text input if switching away from text tool
const existingInput = document.getElementById(`${PREFIX}text-input`);
if (existingInput && tool !== 'text') {
// Pass `false` to drawTextAndRemoveInput to prevent drawing, just remove input.
drawTextAndRemoveInput(existingInput, false);
}
// Apply tool settings after selecting tool
applyToolSettings();
}
function startDrawing(e) {
// For touch events, only prevent default when we're going to draw
// This allows normal scrolling when in navigation mode
if (e.type === 'touchstart' && currentTool !== 'navigate') {
e.preventDefault();
} else if (e.type === 'mousedown' && e.button !== 0) {
// For mouse events, only proceed with left button
return;
}
if (isDraggingToolbar) return; // Don't start drawing if toolbar is being dragged
const docCoords = getDocumentRelativeCoordinates(e);
// startX and startY are now document-relative
startX = docCoords.x;
startY = docCoords.y;
if (currentTool === 'navigate') return;
if (currentTool === 'text') {
// For text tool, we don't start drawing, we show a text input at click position
handleTextToolClick(startX, startY); // Document-relative coordinates
return; // Exit early, no further drawing logic needed
}
isDrawing = true;
// Apply current tool settings to canvas drawing context
applyToolSettings();
if (currentTool === 'pen' || currentTool === 'eraser' || currentTool === 'highlight') {
// Create a new path object to store the pen, highlight, or eraser operation
currentPath = {
tool: currentTool,
points: [{ x: startX, y: startY }], // Document-relative coordinates
color: currentTool === 'highlight' ? hexToRgba(currentColor, 0.4) : currentColor,
lineWidth: ctx.lineWidth,
compositeOperation: ctx.globalCompositeOperation
};
// Apply tool-specific settings for the viewport drawing
ctx.lineWidth = currentPath.lineWidth;
ctx.globalCompositeOperation = currentPath.compositeOperation;
} else if (['rectangle', 'circle', 'line'].includes(currentTool)) {
// Snapshot is for viewport preview, still useful.
snapshot = ctx.getImageData(0, 0, canvas.width, canvas.height);
}
ctx.beginPath();
// Drawing on the fixed canvas uses viewport coordinates.
// For pen/eraser/line, this is the first point.
ctx.moveTo(e.clientX, e.clientY);
}
function draw(e) {
// Only prevent default for touch events when actually drawing
// This allows normal scrolling when not in drawing mode
if (e.type === 'touchmove' && isDrawing) {
e.preventDefault();
}
if (!isDrawing && !isDraggingToolbar) return;
if (isDraggingToolbar) {
const toolbar = document.getElementById(TOOLBAR_ID);
let newX = e.clientX - toolbarOffsetX;
let newY = e.clientY - toolbarOffsetY;
// Keep toolbar within viewport bounds (optional)
// newX = Math.max(0, Math.min(newX, window.innerWidth - toolbar.offsetWidth));
// newY = Math.max(0, Math.min(newY, window.innerHeight - toolbar.offsetHeight));
toolbar.style.left = `${newX}px`;
toolbar.style.top = `${newY}px`;
return;
}
if (!isDrawing) return;
const docCoords = getDocumentRelativeCoordinates(e);
const currX = docCoords.x; // Document-relative X
const currY = docCoords.y; // Document-relative Y
// Viewport-relative coordinates for drawing on the fixed canvas
const viewportCurrentX = e.clientX;
const viewportCurrentY = e.clientY;
// Also convert startX/Y to viewport (subtract scroll) when needed
const viewportStartX = startX - window.scrollX;
const viewportStartY = startY - window.scrollY;
if (currentTool === 'pen' || currentTool === 'eraser' || currentTool === 'highlight') {
if (currentPath) {
currentPath.points.push({ x: docCoords.x, y: docCoords.y });
}
// Draw on the viewport canvas using viewport coordinates
ctx.lineTo(viewportCurrentX, viewportCurrentY);
ctx.stroke();
// For pen/eraser/line, begin new path so each segment is separate if desired (or keep as one long path)
// ctx.beginPath(); // This might be needed if stroke() doesn't auto-begin
// ctx.moveTo(viewportCurrentX, viewportCurrentY); // And then move to current point
} else if (snapshot && (currentTool === 'rectangle' || currentTool === 'circle' || currentTool === 'line')) {
ctx.putImageData(snapshot, 0, 0); // Restore snapshot (covers entire viewport canvas)
ctx.beginPath(); // Need to beginPath after restoring for the new shape
// Convert document-relative startX/startY to viewport-relative for drawing the preview
ctx.moveTo(viewportStartX, viewportStartY);
if (currentTool === 'rectangle') {
ctx.strokeRect(
viewportStartX,
viewportStartY,
viewportCurrentX - viewportStartX,
viewportCurrentY - viewportStartY
);
} else if (currentTool === 'circle') {
const radius = Math.sqrt(Math.pow(viewportCurrentX - viewportStartX, 2) + Math.pow(viewportCurrentY - viewportStartY, 2));
ctx.arc(viewportStartX, viewportStartY, radius, 0, 2 * Math.PI);
ctx.stroke();
} else if (currentTool === 'line') {
ctx.lineTo(viewportCurrentX, viewportCurrentY);
ctx.stroke();
}
}
}
function stopDrawing(e) {
// Handle mouse events
if (e.type === 'mouseleave' && !isDrawing) return; // Only stop if actually drawing
if (e.type === 'mouseup' && e.button !== 0) return; // Only react to left button
// Handle touch events
if (e.type === 'touchend' || e.type === 'touchcancel') {
// No additional checks needed for touch events
}
if (!isDrawing) {
// If not drawing (e.g. click release without drag after selecting a tool,
// or if text tool was active and handled its own input closure)
return;
}
isDrawing = false;
const docCoords = getDocumentRelativeCoordinates(e);
// Clear the redo stack when a new drawing action is completed
undoStack = [];
if (currentTool === 'pen' || currentTool === 'eraser' || currentTool === 'highlight') {
if (currentPath) {
// Only add point if mouse actually moved, to avoid zero-length segments if possible
// However, a final point is always needed to complete the line segment from the previous point
currentPath.points.push({ x: docCoords.x, y: docCoords.y });
if (currentPath.points.length > 1) { // Ensure there's at least a start and end point
drawingOperations.push(currentPath);
}
currentPath = null;
}
if (currentTool === 'eraser') {
// Reset composite operation for future non-eraser tools on the viewport canvas
ctx.globalCompositeOperation = 'source-over';
}
} else if (['rectangle', 'circle', 'line'].includes(currentTool)) {
if (snapshot) {
// Restore the canvas to the state before this shape's preview started.
// This effectively clears the preview from the viewport canvas.
ctx.putImageData(snapshot, 0, 0);
snapshot = null;
}
let operation = {
tool: currentTool,
color: currentColor,
lineWidth: currentLineWidth,
startX: startX, // Document-relative
startY: startY, // Document-relative
endX: docCoords.x, // Document-relative
endY: docCoords.y, // Document-relative
};
if (currentTool === 'circle') {
const radius = Math.sqrt(Math.pow(docCoords.x - startX, 2) + Math.pow(docCoords.y - startY, 2));
operation.centerX = startX; // Document-relative center
operation.centerY = startY; // Document-relative center
operation.radius = radius;
delete operation.endX; // Not needed as center and radius define the circle
delete operation.endY;
}
// Ensure the shape has some dimension before storing
if (currentTool === 'rectangle' && (startX === docCoords.x || startY === docCoords.y)) { /* no op */ }
else if (currentTool === 'line' && startX === docCoords.x && startY === docCoords.y) { /* no op */ }
else if (currentTool === 'circle' && operation.radius === 0) { /* no op */ }
else {
drawingOperations.push(operation);
}
}
// For 'text', the operation is added in drawTextAndRemoveInput function when text is submitted.
// After any drawing operation is completed and stored, redraw the visible parts.
// Text tool calls redraw from drawTextAndRemoveInput, so skip here for text tool.
if (currentTool !== 'text') {
redrawVisibleAnnotations();
}
ctx.beginPath(); // Prepare for next drawing operation on the viewport canvas
applyToolSettings(); // Re-apply current tool settings (e.g., reset eraser's composite op if switching)
}
function stopDrawingOnLeave(e) { // (Same)
if (isDrawing && e.target.nodeName === 'HTML' && !isDraggingToolbar) {
stopDrawing(e);
}
}
function clearCanvas() { // MODIFIED
// Save current operations to undo stack before clearing
if (drawingOperations.length > 0) {
undoStack = []; // Clear redo stack when making a new action
undoStack.push([...drawingOperations]); // Create a copy of the operations
drawingOperations = []; // Clear all stored operations
redrawVisibleAnnotations(); // Redraw (which will clear the canvas)
}
}
// Undo the last drawing operation
function undoOperation() {
if (drawingOperations.length > 0) {
// Store the last operation for potential redo
const lastOperation = drawingOperations.pop();
// If there's no undoStack or it's a new sequence of undo operations,
// create a new array in the undo stack
if (!undoStack.length || undoStack[undoStack.length - 1].constructor !== Array) {
undoStack.push([]);
}
// Add the operation to the undo stack
undoStack[undoStack.length - 1].unshift(lastOperation);
// Redraw the canvas with remaining operations
redrawVisibleAnnotations();
} else {
}
}
// Redo the last undone operation
function redoOperation() {
if (undoStack.length > 0 && undoStack[undoStack.length - 1].length > 0) {
// Get the last undo stack (which is an array of operations)
const lastUndoStack = undoStack[undoStack.length - 1];
// Take the first operation from the undo stack and add it back to drawing operations
const operationToRedo = lastUndoStack.shift();
drawingOperations.push(operationToRedo);
// If the undo stack is now empty, remove it
if (lastUndoStack.length === 0) {
undoStack.pop();
}
// Redraw the canvas with the restored operation
redrawVisibleAnnotations();
} else {
}
}
function handleResize() { // MODIFIED
if (!canvas || !ctx) return;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// If toolbar goes off screen after resize, reset its position
const toolbar = document.getElementById(TOOLBAR_ID);
if (toolbar) {
const rect = toolbar.getBoundingClientRect();
// If toolbar is off-screen, reposition it
if (rect.right > window.innerWidth || rect.bottom > window.innerHeight ||
rect.left < 0 || rect.top < 0) {
// Check screen width to determine optimal placement
if (window.innerWidth <= 480) {
// For very small screens, position at bottom
toolbar.style.left = '10px';
toolbar.style.right = '10px';
toolbar.style.top = 'auto';
toolbar.style.bottom = '10px';
toolbar.style.transform = 'none';
} else {
// For larger screens, center at top
toolbar.style.left = '50%';
toolbar.style.top = '20px';
toolbar.style.transform = 'translateX(-50%)';
}
}
}
applyToolSettings(); // Re-apply settings like line width, color
redrawVisibleAnnotations(); // Redraw with new dimensions and scroll position
}
function handleKeyPress(e) {
if (e.key === "Escape" && currentTool !== 'navigate') {
selectTool('navigate');
e.preventDefault();
}
// Add more hotkeys here if desired
// e.g. 'p' for pen, 'l' for line, etc.
// if (document.activeElement.tagName === 'INPUT' || document.activeElement.tagName === 'TEXTAREA') return; // Don't hijack typing
}
// --- Text Tool Specific Functions ---
function handleTextToolClick(x, y) {
// Remove any existing input field first
const existingInput = document.getElementById(`${PREFIX}text-input`);
if (existingInput) {
drawTextAndRemoveInput(existingInput, false); // Remove without drawing if user clicks elsewhere to start new text
}
// Create a textarea instead of input for better multi-line text support
const input = document.createElement('textarea');
input.id = `${PREFIX}text-input`;
input.className = `${PREFIX}text-input`;
input.placeholder = 'Type your text here...';
// Since we're using fixed positioning for the input but document coordinates for the click,