-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwhiteboard.js
More file actions
1286 lines (1097 loc) · 44.2 KB
/
whiteboard.js
File metadata and controls
1286 lines (1097 loc) · 44.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
const canvas = document.getElementById('whiteboard');
const ctx = canvas.getContext('2d');
const drawingCanvas = document.createElement('canvas'); // Offscreen drawing layer
const drawingCtx = drawingCanvas.getContext('2d');
const status = document.getElementById('status');
// Username elements
const usernameModal = document.getElementById('username-modal');
const usernameInput = document.getElementById('username-input');
const saveUsernameBtn = document.getElementById('save-username-btn');
const usernameDisplay = document.getElementById('username-display');
const changeUsernameBtn = document.getElementById('change-username-btn');
// Get references to the clear options modal elements
const clearOptionsModal = document.getElementById('clear-options-modal');
const clearOwnBtn = document.getElementById('clear-own-btn');
const clearAllBtn = document.getElementById('clear-all-btn');
const cancelClearBtn = document.getElementById('cancel-clear-btn');
// Board management variables
let currentBoardId = 'default';
let boards = [];
let username = ''; // Current username
let tool = 'pen';
let color = '#000000';
let size = 2;
let drawing = false;
let currentStroke = null;
let history = [];
let redoStack = [];
let scale = 1;
let offsetX = 0, offsetY = 0;
let prevOffsetX = 0, prevOffsetY = 0;
let panVelocityX = 0, panVelocityY = 0;
let isPanning = false;
let lastMouseX, lastMouseY; // Variables to track mouse position for panning
const GRID_SIZE = 20;
const FRICTION = 0.92;
let rafId = null;
let socket; // WebSocket connection
// Admin panel elements
let adminPanel = null;
let isAdmin = false;
let connectedUsers = [];
let boardAccessRights = {};
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
drawingCtx.lineCap = 'round';
drawingCtx.lineJoin = 'round';
const penTool = document.getElementById('penTool');
const eraserTool = document.getElementById('eraserTool');
const panTool = document.getElementById('panTool');
// Username functions
function generateRandomUsername() {
const adjectives = ['Creative', 'Artistic', 'Clever', 'Bright', 'Colorful', 'Dazzling', 'Elegant', 'Fancy', 'Glowing', 'Happy'];
const nouns = ['Artist', 'Painter', 'Creator', 'Designer', 'Sketcher', 'Drawer', 'Illustrator', 'Doodler', 'Visionary', 'Genius'];
const randomNumber = Math.floor(Math.random() * 1000);
const randomAdjective = adjectives[Math.floor(Math.random() * adjectives.length)];
const randomNoun = nouns[Math.floor(Math.random() * nouns.length)];
return `${randomAdjective}${randomNoun}${randomNumber}`;
}
function setCookie(name, value, days) {
const expires = new Date();
expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
document.cookie = `${name}=${value};expires=${expires.toUTCString()};path=/`;
}
function getCookie(name) {
const nameEQ = `${name}=`;
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function showUsernameModal() {
// Generate a random username as a suggestion
usernameInput.value = generateRandomUsername();
usernameModal.classList.add('show');
usernameInput.focus();
usernameInput.select(); // Select the text for easy editing
}
function hideUsernameModal() {
usernameModal.classList.remove('show');
}
function saveUsername() {
const newUsername = usernameInput.value.trim();
if (newUsername) {
username = newUsername;
usernameDisplay.textContent = username;
setCookie('whiteboard_username', username, 30); // Store for 30 days
hideUsernameModal();
// Send username to server
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({
type: 'username',
username: username
}));
}
}
}
function initUsername() {
// Check if username cookie exists
const savedUsername = getCookie('whiteboard_username');
if (savedUsername) {
username = savedUsername;
usernameDisplay.textContent = username;
} else {
// Show modal for first-time visitors
showUsernameModal();
}
// Set up event listeners
saveUsernameBtn.addEventListener('click', saveUsername);
changeUsernameBtn.addEventListener('click', showUsernameModal);
// Allow pressing Enter to save username
usernameInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
saveUsername();
}
});
}
// Board management functions
function switchBoard(boardId) {
if (boardId === currentBoardId) return;
if (socket && socket.readyState === WebSocket.OPEN) {
// Send board switch request to server
socket.send(JSON.stringify({
type: 'switch_board',
boardId: boardId
}));
// Update admin panel if admin
if (isAdmin && adminPanel) {
setTimeout(() => {
updateAdminPanel();
}, 500);
}
}
}
function createBoard() {
if (!isAdmin) {
alert('You do not have permission to create a board.');
return;
}
const boardName = prompt('Enter a name for the new board:', `Board ${boards.length + 1}`);
if (boardName) {
// Send create board command to server
socket.send(JSON.stringify({
type: 'create_board',
name: boardName
}));
}
}
function renameBoard(boardId) {
if (!isAdmin) {
alert('You do not have permission to rename a board.');
return;
}
const board = boards.find(b => b.id === boardId);
if (!board) return;
const newName = prompt('Enter a new name for the board:', board.name);
if (newName && newName !== board.name) {
// Send rename board command to server
socket.send(JSON.stringify({
type: 'rename_board',
boardId: boardId,
name: newName
}));
}
}
function deleteBoard(boardId) {
if (boardId === 'default') {
alert('Cannot delete the default board');
return;
}
const board = boards.find(b => b.id === boardId);
if (!board) return;
if (confirm(`Are you sure you want to delete the board "${board.name}"?`)) {
// Send delete board command to server
socket.send(JSON.stringify({
type: 'delete_board',
boardId: boardId
}));
}
}
function updateBoardSelector() {
const boardSelector = document.getElementById('board-selector');
if (!boardSelector) return;
// Check if the toggle button exists, if not create it
if (!document.querySelector('#board-panel .panel-toggle')) {
const boardPanel = document.getElementById('board-panel');
if (boardPanel) {
const externalToggle = document.createElement('button');
externalToggle.className = 'panel-toggle';
externalToggle.innerHTML = '<i class="fas fa-th-list"></i>';
externalToggle.setAttribute('data-tooltip', 'Open Boards Panel');
externalToggle.addEventListener('click', () => {
boardPanel.classList.remove('collapsed');
const toggleBtn = boardPanel.querySelector('.panel-header .tool-button');
if (toggleBtn) {
toggleBtn.querySelector('i').className = 'fas fa-chevron-right';
}
});
boardPanel.appendChild(externalToggle);
}
}
// Clear existing options
boardSelector.innerHTML = '';
// Add each board as an option
boards.forEach(board => {
const boardItem = document.createElement('div');
boardItem.className = 'board-item';
if (board.id === currentBoardId) {
boardItem.classList.add('active');
}
// Add access indicator if admin
if (isAdmin && boardAccessRights[board.id]) {
const accessIndicator = document.createElement('span');
accessIndicator.className = 'access-indicator';
if (boardAccessRights[board.id].writeAccess.includes('*')) {
accessIndicator.textContent = '👥'; // Public write
accessIndicator.title = 'Public Write Access';
} else if (boardAccessRights[board.id].readAccess.includes('*')) {
accessIndicator.textContent = '👁️'; // Public read
accessIndicator.title = 'Public Read Access';
} else {
accessIndicator.textContent = '🔒'; // Private
accessIndicator.title = 'Private Access';
}
boardItem.appendChild(accessIndicator);
}
const boardName = document.createElement('span');
boardName.className = 'board-name';
boardName.textContent = board.name;
boardItem.appendChild(boardName);
// Add action buttons
const actionButtons = document.createElement('div');
actionButtons.className = 'board-actions';
// Switch button
const switchButton = document.createElement('button');
switchButton.className = 'board-action-btn';
switchButton.innerHTML = '<i class="fas fa-arrow-right"></i>';
switchButton.title = 'Switch to this board';
switchButton.addEventListener('click', (e) => {
e.stopPropagation();
switchBoard(board.id);
});
actionButtons.appendChild(switchButton);
// Rename button (admin only or if current board)
if (isAdmin || board.id === currentBoardId) {
const renameButton = document.createElement('button');
renameButton.className = 'board-action-btn';
renameButton.innerHTML = '<i class="fas fa-edit"></i>';
renameButton.title = 'Rename board';
renameButton.addEventListener('click', (e) => {
e.stopPropagation();
const newName = prompt('Enter new board name:', board.name);
if (newName && newName.trim() !== '') {
socket.send(JSON.stringify({
type: 'rename_board',
boardId: board.id,
name: newName.trim()
}));
}
});
actionButtons.appendChild(renameButton);
}
// Delete button (admin only)
if (isAdmin && board.id !== 'default') {
const deleteButton = document.createElement('button');
deleteButton.className = 'board-action-btn delete-btn';
deleteButton.innerHTML = '<i class="fas fa-trash"></i>';
deleteButton.title = 'Delete board';
deleteButton.addEventListener('click', (e) => {
e.stopPropagation();
if (confirm(`Are you sure you want to delete the board "${board.name}"?`)) {
socket.send(JSON.stringify({
type: 'delete_board',
boardId: board.id
}));
}
});
actionButtons.appendChild(deleteButton);
}
// Manage access button (admin only)
if (isAdmin) {
const accessButton = document.createElement('button');
accessButton.className = 'board-action-btn';
accessButton.innerHTML = '<i class="fas fa-users"></i>';
accessButton.title = 'Manage access rights';
accessButton.addEventListener('click', (e) => {
e.stopPropagation();
// Switch to this board and open admin panel
switchBoard(board.id);
// Open admin panel if it's collapsed
if (adminPanel && adminPanel.classList.contains('collapsed')) {
adminPanel.classList.remove('collapsed');
const toggleBtn = adminPanel.querySelector('.panel-header .tool-button');
if (toggleBtn) {
toggleBtn.querySelector('i').className = 'fas fa-chevron-left';
}
}
// Scroll to access rights section
setTimeout(() => {
const accessSection = document.querySelector('#admin-panel .admin-section:nth-child(2)');
if (accessSection) {
accessSection.scrollIntoView({ behavior: 'smooth' });
}
}, 300);
});
actionButtons.appendChild(accessButton);
}
boardItem.appendChild(actionButtons);
// Add click handler for the whole item
boardItem.addEventListener('click', () => {
switchBoard(board.id);
});
boardSelector.appendChild(boardItem);
});
// Add "Create New Board" button
const createBoardItem = document.createElement('div');
createBoardItem.className = 'board-item create-board';
createBoardItem.innerHTML = '<i class="fas fa-plus"></i> Create New Board';
createBoardItem.addEventListener('click', createBoard);
boardSelector.appendChild(createBoardItem);
}
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight - document.getElementById('toolbar').offsetHeight;
drawingCanvas.width = canvas.width;
drawingCanvas.height = canvas.height;
redraw();
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
function setTool(newTool) {
tool = newTool;
canvas.style.cursor = tool === 'pan' ? 'grab' : 'crosshair';
penTool.classList.toggle('active', tool === 'pen');
eraserTool.classList.toggle('active', tool === 'eraser');
panTool.classList.toggle('active', tool === 'pan');
}
function setColor(newColor) {
color = newColor;
}
function setSize(newSize) {
size = parseInt(newSize);
}
function zoom(factor) {
const oldScale = scale;
scale *= factor;
// Send zoom update to server
socket.send(JSON.stringify({
type: 'zoom',
scale
}));
redraw();
}
// Add event listeners for the clear options buttons
clearOwnBtn.addEventListener('click', () => {
hideClearOptionsModal();
clearUserContent();
});
function showClearOptionsModal() {
const clearAllBtn = document.getElementById('clear-all-btn');
// Only show the "Clear All Content" button for admins
if (clearAllBtn) {
clearAllBtn.style.display = isAdmin ? 'block' : 'none';
}
if (clearOptionsModal) {
clearOptionsModal.classList.add('show');
}
}
function hideClearOptionsModal() {
const clearOptionsModal = document.getElementById('clear-options-modal');
if (clearOptionsModal) {
clearOptionsModal.classList.remove('show');
}
}
function clearBoardWithConfirm() {
// Show the clear options modal
showClearOptionsModal();
}
function clearUserContent() {
if (socket && socket.readyState === WebSocket.OPEN && username) {
console.log(`Clearing content for user: ${username}`);
socket.send(JSON.stringify({
type: 'clear_user',
username: username
}));
} else {
console.error('Cannot clear user content: socket not connected or username not set');
}
}
function clearAllContent() {
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({
type: 'clear'
}));
}
}
canvas.addEventListener('pointerdown', startDrawing);
canvas.addEventListener('pointermove', draw);
canvas.addEventListener('pointerup', stopDrawing);
canvas.addEventListener('pointerleave', stopDrawing);
canvas.addEventListener('wheel', (e) => {
e.preventDefault();
zoom(e.deltaY > 0 ? 0.9 : 1.1);
});
document.addEventListener('keydown', (e) => {
if (e.ctrlKey && e.key === 'z') undo();
if (e.ctrlKey && e.key === 'y') redo();
if (e.key === 'p') setTool('pen');
if (e.key === 'e') setTool('eraser');
if (e.key === ' ') setTool('pan');
if (e.key === 'ArrowLeft') offsetX += 20;
if (e.key === 'ArrowRight') offsetX -= 20;
if (e.key === 'ArrowUp') offsetY += 20;
if (e.key === 'ArrowDown') offsetY -= 20;
if (e.key === '+' || e.key === '=') zoom(1.2); // Zoom in
if (e.key === '-') zoom(0.8); // Zoom out
redraw();
});
function startDrawing(e) {
e.preventDefault();
if (tool === 'pan') {
// For pan tool, set panning state and update cursor
isPanning = true;
canvas.style.cursor = 'grabbing';
// Initialize mouse position for panning
const rect = canvas.getBoundingClientRect();
lastMouseX = e.clientX - rect.left;
lastMouseY = e.clientY - rect.top;
return;
}
// For drawing tools (pen/eraser)
drawing = true;
const { x, y } = getVirtualCoords(e);
currentStroke = {
type: 'draw',
tool,
color,
size,
points: [{ x, y, pressure: 1 }] // Always use pressure 1 instead of e.pressure || 1
};
ctx.beginPath();
ctx.moveTo(x * scale + offsetX, y * scale + offsetY);
}
function draw(e) {
e.preventDefault();
// For drawing tools, check if we're drawing and mouse button is down
if ((tool === 'pen' || tool === 'eraser') && (!drawing || !e.buttons)) return;
// For pan tool, check if we're panning
if (tool === 'pan' && !isPanning) return;
if (tool === 'pen' || tool === 'eraser') {
const { x, y } = getVirtualCoords(e);
const pressure = 1; // Always use pressure 1 instead of e.pressure || 1
if (tool === 'pen') {
ctx.strokeStyle = color;
ctx.lineWidth = size * scale; // Remove pressure from the calculation
const lastPoint = currentStroke.points[currentStroke.points.length - 1];
const midX = (lastPoint.x + x) / 2;
const midY = (lastPoint.y + y) / 2;
ctx.quadraticCurveTo(lastPoint.x * scale + offsetX, lastPoint.y * scale + offsetY, midX * scale + offsetX, midY * scale + offsetY);
ctx.stroke();
currentStroke.points.push({ x, y, pressure });
} else if (tool === 'eraser') {
const eraserSize = size * 2; // Make eraser slightly larger than pen
// Only apply eraser to the drawing canvas
drawingCtx.save();
drawingCtx.globalCompositeOperation = 'destination-out';
drawingCtx.beginPath();
// Draw a path between points for continuous erasing
if (currentStroke.points.length > 0) {
const lastPoint = currentStroke.points[currentStroke.points.length - 1];
drawingCtx.moveTo(lastPoint.x * scale + offsetX, lastPoint.y * scale + offsetY);
drawingCtx.lineTo(x * scale + offsetX, y * scale + offsetY);
drawingCtx.lineWidth = eraserSize * scale; // Remove pressure from the calculation
drawingCtx.lineCap = 'round';
drawingCtx.stroke();
}
// Add circular cap at current point for better erasing
drawingCtx.beginPath();
drawingCtx.arc(x * scale + offsetX, y * scale + offsetY, (eraserSize/2) * scale, 0, Math.PI * 2); // Remove pressure from the calculation
drawingCtx.fill();
drawingCtx.restore();
// Clear the main canvas and redraw from drawing canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(drawingCanvas, 0, 0);
currentStroke.type = 'erase'; // Make sure type is set to erase
currentStroke.size = eraserSize; // Store the larger eraser size
currentStroke.points.push({ x, y, pressure });
}
} else if (tool === 'pan') {
// Only call panBoard if we're actually panning (mouse button is down)
panBoard(e);
// throttleRedraw() is now called inside panBoard
// Send pan updates to other clients (throttled)
throttleSendPanUpdate();
}
}
// Throttle pan updates to reduce network traffic
let panUpdateTimeout = null;
function throttleSendPanUpdate() {
if (!panUpdateTimeout) {
panUpdateTimeout = setTimeout(() => {
socket.send(JSON.stringify({
type: 'pan',
offsetX,
offsetY
}));
panUpdateTimeout = null;
}, 100); // Send at most every 100ms
}
}
function stopDrawing() {
drawing = false;
if (tool === 'pen' || tool === 'eraser') {
if (currentStroke && currentStroke.points.length > 1) {
// Only send strokes with at least 2 points
history.push(currentStroke);
redoStack = [];
drawingCtx.drawImage(canvas, 0, 0); // Update offscreen canvas with current state
// Send the stroke to the server
socket.send(JSON.stringify({
type: currentStroke.tool === 'eraser' ? 'erase' : 'draw',
tool: currentStroke.tool,
color: currentStroke.color,
size: currentStroke.size,
points: currentStroke.points,
username: username // Include username with the stroke
}));
redraw(); // Full redraw to sync grid and drawing
currentStroke = null;
}
} else if (tool === 'pan') {
canvas.style.cursor = 'grab';
if (isPanning) {
isPanning = false;
// Reset mouse tracking variables
lastMouseX = undefined;
lastMouseY = undefined;
// Send final pan position
socket.send(JSON.stringify({
type: 'pan',
offsetX,
offsetY
}));
requestAnimationFrame(applyPanInertia);
}
}
}
function throttleRedraw() {
if (!rafId) {
rafId = requestAnimationFrame(() => {
redraw();
rafId = null;
});
}
}
function applyPanInertia() {
if (Math.abs(panVelocityX) > 0.1 || Math.abs(panVelocityY) > 0.1) {
offsetX += panVelocityX;
offsetY += panVelocityY;
panVelocityX *= FRICTION;
panVelocityY *= FRICTION;
socket.send(JSON.stringify({ type: 'update', history, scale, offsetX, offsetY }));
throttleRedraw();
requestAnimationFrame(applyPanInertia);
}
}
function undo() {
if (history.length === 0) return;
// Send undo command to server
socket.send(JSON.stringify({ type: 'undo' }));
// Local undo (will be overwritten when server responds)
const action = history.pop();
redoStack.push(action);
redraw();
}
function redo() {
if (redoStack.length === 0) return;
// Local redo (will be overwritten when server responds)
const action = redoStack.pop();
history.push(action);
// Send redo command to server
socket.send(JSON.stringify({ type: 'redo' }));
redraw();
}
// Initialize the whiteboard
function initWhiteboard() {
// Resize canvas to fill window
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
// Initialize board panel
initBoardPanel();
// Setup WebSocket connection
setupWebSocket();
// Set up event listeners
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('mouseout', stopDrawing);
// Touch support
canvas.addEventListener('touchstart', (e) => {
e.preventDefault();
const touch = e.touches[0];
startDrawing({
clientX: touch.clientX,
clientY: touch.clientY,
preventDefault: () => {}
});
});
canvas.addEventListener('touchmove', (e) => {
e.preventDefault();
const touch = e.touches[0];
draw({
clientX: touch.clientX,
clientY: touch.clientY,
preventDefault: () => {}
});
});
canvas.addEventListener('touchend', stopDrawing);
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
if (e.key === 'p' || e.key === 'P') {
setTool('pen');
} else if (e.key === 'e' || e.key === 'E') {
setTool('eraser');
} else if (e.key === ' ') {
// Space bar for pan tool
e.preventDefault(); // Prevent page scroll
setTool('pan');
} else if (e.ctrlKey && (e.key === 'z' || e.key === 'Z')) {
e.preventDefault();
undo();
} else if (e.ctrlKey && (e.key === 'y' || e.key === 'Y')) {
e.preventDefault();
redo();
}
});
document.addEventListener('keyup', (e) => {
if (e.key === ' ' && tool === 'pan') {
// Return to previous tool when space is released
setTool(prevTool || 'pen');
}
});
// Set up animation loop for smooth panning
function animate() {
if (isPanning) {
applyPanInertia();
}
rafId = requestAnimationFrame(animate);
}
animate();
// Set up clear options modal buttons
if (clearOwnBtn) {
clearOwnBtn.addEventListener('click', () => {
clearUserContent();
hideClearOptionsModal();
});
}
if (clearAllBtn) {
clearAllBtn.addEventListener('click', () => {
clearAllContent();
hideClearOptionsModal();
});
}
if (cancelClearBtn) {
cancelClearBtn.addEventListener('click', hideClearOptionsModal);
}
}
// Function to initialize the board panel
function initBoardPanel() {
const boardPanel = document.getElementById('board-panel');
if (!boardPanel) return;
// Add toggle button to panel header
const panelHeader = boardPanel.querySelector('.panel-header');
if (panelHeader) {
const toggleButton = panelHeader.querySelector('.tool-button');
if (!toggleButton) {
const newToggleButton = document.createElement('button');
newToggleButton.className = 'tool-button';
newToggleButton.setAttribute('data-tooltip', 'Toggle Board Panel');
newToggleButton.innerHTML = '<i class="fas fa-chevron-right"></i>';
newToggleButton.addEventListener('click', () => {
boardPanel.classList.toggle('collapsed');
// Update the icon
const icon = newToggleButton.querySelector('i');
if (boardPanel.classList.contains('collapsed')) {
icon.className = 'fas fa-chevron-left';
} else {
icon.className = 'fas fa-chevron-right';
}
});
panelHeader.appendChild(newToggleButton);
}
}
// Set up the board panel tab for reopening
const boardPanelTab = document.getElementById('board-panel-tab');
if (boardPanelTab) {
boardPanelTab.addEventListener('click', () => {
boardPanel.classList.remove('collapsed');
const toggleBtn = boardPanel.querySelector('.panel-header .tool-button');
if (toggleBtn) {
toggleBtn.querySelector('i').className = 'fas fa-chevron-right';
}
});
}
}
function setupWebSocket() {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${protocol}//${window.location.host}`;
console.log(`Connecting to WebSocket at ${wsUrl}`);
socket = new WebSocket(wsUrl);
socket.onopen = () => {
console.log('WebSocket connection established');
status.textContent = 'Connected';
status.className = 'connected';
// Send username if available
if (username) {
socket.send(JSON.stringify({
type: 'username',
username: username
}));
}
};
socket.onclose = () => {
console.log('WebSocket connection closed');
status.textContent = 'Disconnected';
status.className = 'disconnected';
// Try to reconnect after a delay
setTimeout(() => {
console.log('Attempting to reconnect...');
setupWebSocket();
}, 3000);
};
socket.onerror = (error) => {
console.error('WebSocket error:', error);
status.textContent = 'Error';
status.className = 'error';
};
socket.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
if (data.type === 'init') {
// Handle initial state
currentBoardId = data.boardId;
boards = data.boards || [];
// Set client ID
clientId = data.clientId;
// Apply the initial state
if (data.state && data.state.actions) {
history = data.state.actions;
redraw();
}
// Update board selector
updateBoardSelector();
// Request users list if admin
if (isAdmin) {
socket.send(JSON.stringify({
type: 'get_users'
}));
}
} else if (data.type === 'boards_list') {
// Update the list of boards
boards = data.boards || [];
updateBoardSelector();
} else if (data.type === 'board_state') {
// Handle board state update
if (data.boardId) {
currentBoardId = data.boardId;
// Apply the board state
if (data.state && data.state.actions) {
history = data.state.actions;
redoStack = []; // Clear redo stack when switching boards
redraw();
updateBoardSelector();
// Update UI based on write access
updateWriteAccessUI(data.canWrite);
}
}
} else if (data.type === 'draw') {
// Handle drawing from other clients
history.push(data);
redraw();
} else if (data.type === 'erase') {
// Handle erasing from other clients
history.push(data);
redraw();
} else if (data.type === 'clear') {
// Handle board clear
if (data.boardId === currentBoardId) {
history = [];
redoStack = [];
redraw();
}
} else if (data.type === 'clear_user') {
// Handle clearing a specific user's content
if (data.boardId === currentBoardId) {
console.log(`Clearing content for user: ${data.username}`);
history = history.filter(action => action.username !== data.username);
redraw();
}
} else if (data.type === 'update') {
// Handle full state update
if (data.boardId === currentBoardId && data.state && data.state.actions) {
history = data.state.actions;
redraw();
}
} else if (data.type === 'user_update') {
// Handle user updates (e.g., username changes)
console.log(`User ${data.username} (${data.clientId}) updated`);
// You could update a users list if you add that feature
} else if (data.type === 'user_disconnect') {
// Handle user disconnection
console.log(`User ${data.username} (${data.clientId}) disconnected`);
// You could update a users list if you add that feature
} else if (data.type === 'admin_status') {
isAdmin = data.isAdmin;
// Show admin panel if user is admin
if (isAdmin) {
createAdminPanel();
// Request users list
socket.send(JSON.stringify({
type: 'get_users'
}));
}
} else if (data.type === 'users_list') {
// Update connected users list for admin
connectedUsers = data.users;
updateAdminPanel();
} else if (data.type === 'access_rights') {
// Update access rights for admin
boardAccessRights = data.boardAccess;
updateAdminPanel();
} else if (data.type === 'write_access') {
// Update UI based on write access
updateWriteAccessUI(data.canWrite);
} else if (data.type === 'error') {
// Display error message
console.error(`Server error: ${data.message}`);
alert(data.message);
}
} catch (error) {
console.error('Error parsing message:', error);
}
};
}
// Function to create admin panel
function createAdminPanel() {
// Check if admin panel already exists
if (document.getElementById('admin-panel')) {
return;
}
// Create admin panel
adminPanel = document.createElement('div');
adminPanel.id = 'admin-panel';
adminPanel.className = 'panel';
// Create panel header
const panelHeader = document.createElement('div');
panelHeader.className = 'panel-header';
const panelTitle = document.createElement('h3');
panelTitle.textContent = 'Admin Panel';
const toggleButton = document.createElement('button');