Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
2136 lines (1868 loc) · 67 KB
/
Copy pathscript.js
File metadata and controls
2136 lines (1868 loc) · 67 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
// Dynamic Spreadsheet Web App
// Data persists in URL hash for easy sharing
// Import constants from ES6 module
import { DEBOUNCE_DELAY, DEFAULT_COLS, DEFAULT_ROWS, MAX_COLS, MAX_ROWS } from "./modules/constants.js";
import { buildRangeRef, FormulaDropdownManager, FormulaEvaluator, isValidFormula, isVisualFormula } from "./modules/formulaManager.js";
import { DependencyTracer } from "./modules/dependencyTracer.js";
import { PasswordManager } from "./modules/passwordManager.js";
import { CSVManager } from "./modules/csvManager.js";
import { JSONManager } from "./modules/jsonManager.js";
import { ExcelManager } from "./modules/excelManager.js";
import { HashToolManager } from "./modules/hashToolManager.js";
import { P2PManager } from "./modules/p2pManager.js";
import { PresentationManager } from "./modules/presentationManager.js";
import { TemplateManager } from "./modules/templateManager.js";
import { CommandPaletteManager } from "./modules/commandPaletteManager.js";
import { ThemeManager } from "./modules/themeManager.js";
import { UIModeManager } from "./modules/uiModeManager.js";
import { QRCodeManager } from "./modules/qrCodeManager.js";
import { CellFormattingManager } from "./modules/cellFormattingManager.js";
import { SelectionStatusManager } from "./modules/selectionStatusManager.js";
import { getSparklineDisplayText } from "./modules/visualFunctions.js";
import { AppLauncher } from "./modules/app_launcher.js";
import {
addColumn,
addRow,
clearActiveHeaders,
clearSelectedCells,
clearSelection,
clearSpreadsheet,
focusCellAt,
getCellContentElement,
getCellElement,
getSelectionBounds,
getState,
handleMouseDown,
handleMouseLeave,
handleMouseMove,
handleMouseUp,
handleResizeStart,
handleTouchEnd,
handleTouchMove,
handleTouchStart,
hasMultiSelection,
renderGrid,
setActiveHeaders,
setCallbacks,
setState,
updateSparklineForCellElement,
updateSelectionVisuals,
insertRowAt,
insertColumnAt,
} from "./modules/rowColManager.js";
import { escapeHTML, isValidCSSColor, sanitizeHTML } from "./modules/security.js";
import { showToast } from "./modules/toastManager.js";
import {
createDefaultColumnWidths,
createDefaultRowHeights,
createEmptyCellStyle,
createEmptyCellStyles,
createEmptyData,
isCellStylesDefault,
isColWidthsDefault,
isDataEmpty,
isFormulasEmpty,
isRowHeightsDefault,
normalizeAlignment,
normalizeCellStyles,
normalizeColumnWidths,
normalizeFontSize,
normalizeRowHeights,
minifyStateForExport,
URLManager,
validateAndNormalizeState,
} from "./modules/urlManager.js";
(function () {
"use strict";
// Data model - dynamic 2D array (rows/cols managed by rowColManager)
let data = createEmptyData(DEFAULT_ROWS, DEFAULT_COLS);
// Formula storage - parallel array to data
let formulas = createEmptyData(DEFAULT_ROWS, DEFAULT_COLS);
// Cell styles - alignment, colors, and font size
let cellStyles = createEmptyCellStyles(DEFAULT_ROWS, DEFAULT_COLS);
// Read-only mode flag
let isReadOnly = false;
// Embed mode flag
let isEmbedMode = false;
// Zen mode flag
let isZenMode = false;
// Debounce timer
let debounceTimer = null;
let dependencyDrawQueued = false;
// Formula range selection mode (for clicking to select ranges like Google Sheets)
let formulaEditMode = false; // true when typing a formula
let formulaEditCell = null; // { row, col, element } of cell being edited
let formulaRangeStart = null; // Start of range being selected
let formulaRangeEnd = null; // End of range being selected
let editingCell = null; // { row, col } when editing a cell's text
// P2P collaboration state
let isRemoteUpdate = false;
let hasInitialSync = false;
let fullSyncTimer = null;
const FULL_SYNC_DELAY = 300;
const REMOTE_CURSOR_CLASS = "remote-active";
const LEGACY_REMOTE_ID = "remote-peer";
const PEER_ACTIVITY_THROTTLE = 800;
const PEER_ACTIVITY_DECAY = 1600;
let presenceStackEl = null;
let lastActivitySentAt = 0;
let localPeerMeta = null;
const presencePeers = new Map();
const presenceActivityTimers = new Map();
const p2pUI = {
modal: null,
startHostBtn: null,
joinBtn: null,
copyIdBtn: null,
idDisplay: null,
statusEl: null,
myIdInput: null,
remoteIdInput: null,
startHostLabel: "",
joinLabel: "",
};
// Encryption state
// Encryption state handled by PasswordManager
// Toast functions moved to modules/toastManager.js
// Create empty data array with specified dimensions
// Factory functions moved to modules/urlManager.js
// ========== Security Functions ==========
// Security Functions moved to modules/security.js
// Insert text at current cursor position in contentEditable
function insertTextAtCursor(text) {
const selection = window.getSelection();
if (!selection.rangeCount) return;
const range = selection.getRangeAt(0);
range.deleteContents();
const textNode = document.createTextNode(text);
range.insertNode(textNode);
// Move cursor after inserted text
range.setStartAfter(textNode);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
// Move caret to end of contentEditable element
function setCaretToEnd(element) {
const range = document.createRange();
range.selectNodeContents(element);
range.collapse(false);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
function applyFormulaSuggestion(formulaName) {
const target = formulaEditCell ? formulaEditCell.element : document.activeElement;
if (!target || !target.classList.contains("cell-content")) return;
const row = parseInt(target.dataset.row, 10);
const col = parseInt(target.dataset.col, 10);
if (isNaN(row) || isNaN(col)) return;
const newValue = `=${formulaName}(`;
target.innerText = newValue;
setCaretToEnd(target);
formulaEditMode = true;
formulaEditCell = { row, col, element: target };
formulas[row][col] = newValue;
data[row][col] = newValue;
FormulaDropdownManager.hide();
debouncedUpdateURL();
scheduleDependencyDraw();
}
// ========== Formula Evaluation Functions ==========
// Get numeric value from cell (returns 0 for empty/non-numeric)
function getCellValue(row, col) {
const { rows, cols } = getState();
if (row < 0 || row >= rows || col < 0 || col >= cols) return 0;
const val = data[row][col];
if (!val || val === "") return 0;
// Strip HTML tags and parse
const stripped = String(val)
.replace(/<[^>]*>/g, "")
.trim();
const normalized = stripped.replace(/,/g, "");
const num = parseFloat(normalized);
return isNaN(num) ? 0 : num;
}
// Recalculate all formula cells
function recalculateFormulas() {
const { rows, cols } = getState();
const container = document.getElementById("spreadsheet");
const activeElement = document.activeElement;
const maxPasses = rows * cols;
let needsUpdate = false;
// Multiple passes to propagate formulas that depend on other formulas.
for (let pass = 0; pass < maxPasses; pass++) {
let changed = false;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
const formula = formulas[r][c];
if (formula && formula.startsWith("=")) {
if (isVisualFormula(formula)) {
continue;
}
const result = String(FormulaEvaluator.evaluate(formula, { getCellValue, data, rows, cols }));
if (data[r][c] !== result) {
data[r][c] = result;
changed = true;
needsUpdate = true;
}
}
}
}
if (!changed) break;
}
if (!needsUpdate || !container) return;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
const formula = formulas[r][c];
if (formula && formula.startsWith("=")) {
const cellContent = container.querySelector(`.cell-content[data-row="${r}"][data-col="${c}"]`);
if (!cellContent) continue;
const isEditingFormula = cellContent === activeElement && cellContent.innerText.trim().startsWith("=");
if (!isEditingFormula) {
cellContent.innerText = data[r][c];
updateSparklineForCellElement(cellContent, data[r][c], formula);
}
}
}
}
}
// Normalization functions moved to modules/urlManager.js
function getDataArray() {
return data;
}
function setDataArray(newData) {
data = newData;
}
function getFormulasArray() {
return formulas;
}
function setFormulasArray(newFormulas) {
formulas = newFormulas;
}
function getCellStylesArray() {
return cellStyles;
}
function setCellStylesArray(newCellStyles) {
cellStyles = newCellStyles;
}
// Helper functions moved to modules/urlManager.js
// Minify state object keys for smaller URL payload
// State helpers moved to modules/urlManager.js
// ========== Serialization Codec (Wrapper for minify/expand + compression) ==========
// Handles state serialization without encryption concerns
// Codec, validation, and decode functions moved to modules/urlManager.js
// Build current state object (only includes non-empty/non-default values)
function buildCurrentState() {
const { rows, cols, colWidths, rowHeights } = getState();
const stateObj = {
rows,
cols,
theme: ThemeManager.isDarkMode() ? "dark" : "light",
};
// Only include readOnly if true (saves URL bytes)
if (isReadOnly || isEmbedMode) {
stateObj.readOnly = 1;
}
// Only include embed if true (saves URL bytes)
if (isEmbedMode) {
stateObj.embed = 1;
}
// Only include data if not all empty
if (!isDataEmpty(data)) {
stateObj.data = data;
}
// Only include formulas if any exist
if (!isFormulasEmpty(formulas)) {
stateObj.formulas = formulas;
}
// Only include cell styles if any are non-default
if (!isCellStylesDefault(cellStyles)) {
stateObj.cellStyles = cellStyles;
}
// Only include colWidths if not all default
if (!isColWidthsDefault(colWidths, cols)) {
stateObj.colWidths = colWidths;
}
// Only include rowHeights if not all default
if (!isRowHeightsDefault(rowHeights, rows)) {
stateObj.rowHeights = rowHeights;
}
return stateObj;
}
// Update URL hash without page jump
async function updateURL() {
const state = buildCurrentState();
await URLManager.updateURL(state, PasswordManager.getPassword());
}
// Debounced URL update
function debouncedUpdateURL() {
if (debounceTimer) {
clearTimeout(debounceTimer);
}
debounceTimer = setTimeout(updateURL, DEBOUNCE_DELAY);
}
function scheduleDependencyDraw() {
if (!DependencyTracer.isActive) return;
if (dependencyDrawQueued) return;
dependencyDrawQueued = true;
requestAnimationFrame(() => {
dependencyDrawQueued = false;
DependencyTracer.draw(getFormulasArray());
});
}
function refreshDependencyLayer() {
DependencyTracer.init();
scheduleDependencyDraw();
}
// ========== Zen Mode ==========
const ZEN_MODE_CLASS = "zen-mode";
function applyZenMode(enabled) {
isZenMode = enabled;
document.body.classList.toggle(ZEN_MODE_CLASS, enabled);
const toggleZenBtn = document.getElementById("toggle-zen");
if (toggleZenBtn) {
toggleZenBtn.classList.toggle("active", enabled);
toggleZenBtn.setAttribute("aria-pressed", enabled ? "true" : "false");
const icon = toggleZenBtn.querySelector("i");
if (icon) icon.className = enabled ? "fa-solid fa-eye-slash" : "fa-solid fa-eye";
}
}
function toggleZenMode() {
applyZenMode(!isZenMode);
}
function handleZenModeShortcut(event) {
if (event.defaultPrevented) return;
const key = event.key ? event.key.toLowerCase() : "";
if (event.altKey && !event.ctrlKey && !event.metaKey && key === "z") {
event.preventDefault();
toggleZenMode();
}
}
// Handle input changes
function handleInput(event) {
const target = event.target;
if (!target.classList.contains("cell-content")) return;
// GUARD: Block in read-only mode
if (isReadOnly) {
event.preventDefault();
target.blur();
return;
}
const row = parseInt(target.dataset.row, 10);
const col = parseInt(target.dataset.col, 10);
// DON'T clear selection if in formula mode (user may be selecting range)
if (hasMultiSelection() && !formulaEditMode) {
clearSelection();
setActiveHeaders(row, col);
}
const { rows, cols } = getState();
if (!isNaN(row) && !isNaN(col) && row < rows && col < cols) {
setEditingCell(row, col);
const previousFormula = formulas[row] ? formulas[row][col] : "";
const rawValue = target.innerText.trim();
if (rawValue.startsWith("=")) {
// Enter formula edit mode
formulaEditMode = true;
formulaEditCell = { row, col, element: target };
// Store formula but DON'T evaluate during typing
formulas[row][col] = rawValue;
data[row][col] = rawValue;
FormulaDropdownManager.update(target, rawValue);
} else {
// Exit formula edit mode
formulaEditMode = false;
formulaEditCell = null;
// Regular value - clear any existing formula
formulas[row][col] = "";
data[row][col] = sanitizeHTML(target.innerHTML);
FormulaDropdownManager.hide();
// Recalculate dependent formulas when regular values change
recalculateFormulas();
}
debouncedUpdateURL();
if (canBroadcastP2P()) {
P2PManager.broadcastCellUpdate(row, col, data[row][col], formulas[row][col]);
}
notifyLocalActivity(row, col);
SelectionStatusManager.updateStatusBar();
if (previousFormula !== formulas[row][col]) {
scheduleDependencyDraw();
}
}
}
// Selection and hover functions moved to modules/rowColManager.js
// Cell positioning functions moved to modules/rowColManager.js
function setEditingCell(row, col) {
editingCell = { row, col };
}
function clearEditingCell() {
editingCell = null;
}
function isEditingCell(row, col) {
return !!(editingCell && editingCell.row === row && editingCell.col === col);
}
function handleFocusIn(event) {
const target = event.target;
if (!target.classList.contains("cell-content")) return;
const row = parseInt(target.dataset.row, 10);
const col = parseInt(target.dataset.col, 10);
if (isNaN(row) || isNaN(col)) return;
// If we have a multi-selection and focus moves to a cell outside it, clear selection
if (hasMultiSelection()) {
const bounds = getSelectionBounds();
if (bounds && (row < bounds.minRow || row > bounds.maxRow || col < bounds.minCol || col > bounds.maxCol)) {
clearSelection();
}
}
// Update header highlighting for single cell focus (if no multi-selection)
if (!hasMultiSelection()) {
setActiveHeaders(row, col);
}
// Show formula text when focused (for editing)
if (formulas[row][col] && formulas[row][col].startsWith("=")) {
target.innerText = formulas[row][col];
}
if (canBroadcastP2P()) {
const cursorColor = localPeerMeta ? localPeerMeta.color : "#ff0055";
P2PManager.broadcastCursor(row, col, cursorColor);
}
}
function handleFocusOut(event) {
const target = event.target;
if (!target.classList.contains("cell-content")) return;
FormulaDropdownManager.hide();
const row = parseInt(target.dataset.row, 10);
const col = parseInt(target.dataset.col, 10);
// If we're in formula edit mode and currently selecting a range, don't process blur
const { isSelecting, rows, cols } = getState();
if (formulaEditMode && isSelecting) {
return;
}
if (!isNaN(row) && !isNaN(col)) {
notifyLocalActivityEnd(row, col);
}
// Evaluate formula when blurred
if (!isNaN(row) && !isNaN(col)) {
const rawValue = target.innerText.trim();
const previousFormula = formulas[row] ? formulas[row][col] : "";
if (rawValue.startsWith("=")) {
// NOW evaluate the formula
formulas[row][col] = rawValue;
const sparklineDisplay = getSparklineDisplayText(rawValue);
if (sparklineDisplay) {
data[row][col] = sparklineDisplay;
target.innerText = sparklineDisplay;
debouncedUpdateURL();
SelectionStatusManager.updateStatusBar();
if (canBroadcastP2P()) {
P2PManager.broadcastCellUpdate(row, col, data[row][col], formulas[row][col]);
}
if (previousFormula !== formulas[row][col]) {
scheduleDependencyDraw();
}
} else {
const result = FormulaEvaluator.evaluate(rawValue, { getCellValue, data, rows, cols });
data[row][col] = String(result);
target.innerText = String(result);
// Recalculate all dependent formulas
recalculateFormulas();
debouncedUpdateURL();
SelectionStatusManager.updateStatusBar();
if (canBroadcastP2P()) {
P2PManager.broadcastCellUpdate(row, col, data[row][col], formulas[row][col]);
}
if (previousFormula !== formulas[row][col]) {
scheduleDependencyDraw();
}
}
}
const sparklineValue = data[row] ? data[row][col] : rawValue;
updateSparklineForCellElement(target, sparklineValue, formulas[row] ? formulas[row][col] : "");
}
// Exit formula edit mode when focus truly leaves
clearEditingCell();
formulaEditMode = false;
formulaEditCell = null;
formulaRangeStart = null;
formulaRangeEnd = null;
const container = document.getElementById("spreadsheet");
if (!container) return;
const next = event.relatedTarget;
if (next && container.contains(next)) {
return;
}
clearActiveHeaders();
}
function stringToColor(str) {
if (!str) return "#888888";
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
const hex = (hash & 0x00ffffff).toString(16).toUpperCase().padStart(6, "0");
return `#${hex}`;
}
function buildInitials(label) {
if (!label) return "??";
const cleaned = String(label).replace(/[^a-zA-Z0-9]/g, "");
if (!cleaned) return "??";
if (cleaned.length === 1) return `${cleaned}${cleaned}`.toUpperCase();
return cleaned.slice(0, 2).toUpperCase();
}
function buildPeerMeta({ peerId, name, isLocal = false } = {}) {
const resolvedId = peerId || LEGACY_REMOTE_ID;
const displayName = name || resolvedId;
return {
id: resolvedId,
name: displayName,
color: stringToColor(resolvedId),
initials: buildInitials(displayName),
isLocal,
};
}
function ensurePresenceStack() {
if (!presenceStackEl) {
presenceStackEl = document.getElementById("presence-stack");
}
return presenceStackEl;
}
function upsertPeer(peerMeta) {
const stack = ensurePresenceStack();
if (!stack || !peerMeta || !peerMeta.id) return;
const existing = presencePeers.get(peerMeta.id);
if (existing) {
existing.name = peerMeta.name || existing.name;
existing.color = peerMeta.color || existing.color;
existing.initials = peerMeta.initials || existing.initials;
if (typeof peerMeta.isLocal === "boolean") {
existing.isLocal = peerMeta.isLocal;
}
if (existing.el) {
existing.el.style.setProperty("--peer-color", existing.color);
existing.el.textContent = existing.initials;
existing.el.title = existing.name;
existing.el.setAttribute("aria-label", existing.name);
existing.el.classList.toggle("is-local", !!existing.isLocal);
existing.el.style.order = existing.isLocal ? "0" : "1";
}
return;
}
const avatar = document.createElement("div");
avatar.className = "presence-avatar is-entering";
avatar.dataset.peerId = peerMeta.id;
avatar.style.setProperty("--peer-color", peerMeta.color);
avatar.textContent = peerMeta.initials;
avatar.title = peerMeta.name;
avatar.setAttribute("aria-label", peerMeta.name);
avatar.setAttribute("role", "listitem");
avatar.style.order = peerMeta.isLocal ? "0" : "1";
if (peerMeta.isLocal) {
avatar.classList.add("is-local");
}
avatar.addEventListener(
"animationend",
() => {
avatar.classList.remove("is-entering");
},
{ once: true }
);
stack.appendChild(avatar);
presencePeers.set(peerMeta.id, {
...peerMeta,
el: avatar,
isActive: false,
});
}
function removePeer(peerId) {
const peer = presencePeers.get(peerId);
if (!peer) return;
if (peer.el) {
peer.el.classList.add("is-leaving");
peer.el.addEventListener(
"animationend",
() => {
if (peer.el && peer.el.parentNode) {
peer.el.parentNode.removeChild(peer.el);
}
},
{ once: true }
);
}
presencePeers.delete(peerId);
if (presenceActivityTimers.has(peerId)) {
clearTimeout(presenceActivityTimers.get(peerId));
presenceActivityTimers.delete(peerId);
}
}
function clearPresence() {
presencePeers.forEach((peer) => {
if (peer.el && peer.el.parentNode) {
peer.el.parentNode.removeChild(peer.el);
}
});
presencePeers.clear();
presenceActivityTimers.forEach((timer) => clearTimeout(timer));
presenceActivityTimers.clear();
localPeerMeta = null;
lastActivitySentAt = 0;
}
function removeRemotePeers() {
presencePeers.forEach((peer, peerId) => {
if (!peer.isLocal) {
removePeer(peerId);
}
});
}
function setPeerActive(peerId, active, { decay = false } = {}) {
const peer = presencePeers.get(peerId);
if (!peer || !peer.el) return;
if (active) {
peer.el.classList.add("is-active");
} else {
peer.el.classList.remove("is-active");
}
if (presenceActivityTimers.has(peerId)) {
clearTimeout(presenceActivityTimers.get(peerId));
presenceActivityTimers.delete(peerId);
}
if (active && decay) {
const timer = setTimeout(() => {
setPeerActive(peerId, false);
}, PEER_ACTIVITY_DECAY);
presenceActivityTimers.set(peerId, timer);
}
}
function markPeerActivity(peerId) {
const resolvedId = peerId || LEGACY_REMOTE_ID;
if (!presencePeers.has(resolvedId)) {
upsertPeer(buildPeerMeta({ peerId: resolvedId }));
}
setPeerActive(resolvedId, true, { decay: true });
}
function registerLocalPeer(peerId) {
if (!peerId) return;
if (localPeerMeta && localPeerMeta.id !== peerId) {
clearPresence();
}
localPeerMeta = buildPeerMeta({ peerId, name: peerId, isLocal: true });
upsertPeer(localPeerMeta);
}
function sendPeerHello() {
if (!P2PManager.canSend() || !P2PManager.myPeerId) return;
const displayName = localPeerMeta ? localPeerMeta.name : P2PManager.myPeerId;
P2PManager.sendPeerHello({ peerId: P2PManager.myPeerId, name: displayName });
}
function handlePeerHello({ peerId, name } = {}) {
if (!peerId) return;
const isLocal = peerId === P2PManager.myPeerId;
upsertPeer(buildPeerMeta({ peerId, name, isLocal }));
}
function handlePeerActivity({ peerId, active } = {}) {
const resolvedId = peerId || LEGACY_REMOTE_ID;
if (!presencePeers.has(resolvedId)) {
upsertPeer(buildPeerMeta({ peerId: resolvedId }));
}
if (active === false) {
setPeerActive(resolvedId, false);
return;
}
setPeerActive(resolvedId, true, { decay: true });
}
function notifyLocalActivity(row, col) {
const peerId = P2PManager.myPeerId;
if (!peerId) return;
if (!localPeerMeta) {
registerLocalPeer(peerId);
}
setPeerActive(peerId, true, { decay: true });
if (!P2PManager.canSend()) return;
const now = Date.now();
if (now - lastActivitySentAt < PEER_ACTIVITY_THROTTLE) return;
lastActivitySentAt = now;
P2PManager.sendPeerActivity({ peerId, active: true, row, col });
}
function notifyLocalActivityEnd(row, col) {
const peerId = P2PManager.myPeerId;
if (!peerId) return;
setPeerActive(peerId, false);
if (!P2PManager.canSend()) return;
P2PManager.sendPeerActivity({ peerId, active: false, row, col });
}
// ========== P2P Collaboration ==========
function canBroadcastP2P() {
if (isRemoteUpdate) return false;
if (!P2PManager.canSend()) return false;
if (!P2PManager.isHost && !hasInitialSync) return false;
return true;
}
function sendFullSyncNow() {
if (!canBroadcastP2P()) return;
recalculateFormulas();
const fullState = buildCurrentState();
P2PManager.sendFullSync(fullState);
}
function scheduleFullSync() {
if (!canBroadcastP2P()) return;
if (fullSyncTimer) {
clearTimeout(fullSyncTimer);
}
fullSyncTimer = setTimeout(() => {
sendFullSyncNow();
}, FULL_SYNC_DELAY);
}
function handleGridResize() {
scheduleFullSync();
scheduleDependencyDraw();
}
function handleP2PConnection(amIHost) {
hasInitialSync = amIHost;
if (P2PManager.myPeerId) {
registerLocalPeer(P2PManager.myPeerId);
}
sendPeerHello();
if (amIHost) {
recalculateFormulas();
const fullState = buildCurrentState();
P2PManager.sendInitialSync(fullState);
P2PManager.setStatus("Connected. You can now edit together.");
if (p2pUI.modal) {
p2pUI.modal.classList.add("hidden");
}
} else {
P2PManager.setStatus("Connected. Waiting for host data...");
showToast("Waiting for host data...", "info");
}
}
function handleInitialSync(remoteState) {
if (!remoteState) return;
isRemoteUpdate = true;
applyLoadedState(remoteState);
renderGrid();
DependencyTracer.init();
recalculateFormulas();
debouncedUpdateURL();
SelectionStatusManager.updateStatusBar();
scheduleDependencyDraw();
P2PManager.clearRemoteCursor();
isRemoteUpdate = false;
hasInitialSync = true;
P2PManager.setStatus("Synced with host.");
if (p2pUI.modal) {
p2pUI.modal.classList.add("hidden");
}
showToast("Synced with host!", "success");
}
function handleRemoteCellUpdate({ row, col, value, formula, senderId }) {
const rowIndex = parseInt(row, 10);
const colIndex = parseInt(col, 10);
if (isNaN(rowIndex) || isNaN(colIndex)) return;
const { rows, cols } = getState();
if (rowIndex < 0 || colIndex < 0 || rowIndex >= rows || colIndex >= cols) {
P2PManager.requestFullSync();
return;
}
const resolvedSenderId = senderId || LEGACY_REMOTE_ID;
if (resolvedSenderId) {
markPeerActivity(resolvedSenderId);
}
const rawValue = value === undefined || value === null ? "" : String(value);
const rawFormula = formula === undefined || formula === null ? "" : String(formula);
const previousFormula = formulas[rowIndex] ? formulas[rowIndex][colIndex] : "";
const safeValue = sanitizeHTML(rawValue);
const isFormulaCell = rawFormula.startsWith("=");
const isFormulaEdit = isFormulaCell && rawValue.trim().startsWith("=");
isRemoteUpdate = true;
data[rowIndex][colIndex] = isFormulaEdit ? rawFormula : safeValue;
formulas[rowIndex][colIndex] = rawFormula;
const cellContent = getCellContentElement(rowIndex, colIndex);
if (cellContent && document.activeElement !== cellContent) {
if (isFormulaEdit) {
cellContent.innerText = rawFormula;
} else {
cellContent.innerHTML = safeValue;
}
updateSparklineForCellElement(cellContent, data[rowIndex][colIndex], formulas[rowIndex][colIndex]);
}
if (!isFormulaEdit) {
recalculateFormulas();
}
debouncedUpdateURL();
if (previousFormula !== formulas[rowIndex][colIndex]) {
scheduleDependencyDraw();
}
isRemoteUpdate = false;
}
function handleRemoteCursor({ row, col, senderId, color }) {
const rowIndex = parseInt(row, 10);
const colIndex = parseInt(col, 10);
if (isNaN(rowIndex) || isNaN(colIndex)) return;
const { rows, cols } = getState();
if (rowIndex < 0 || colIndex < 0 || rowIndex >= rows || colIndex >= cols) return;
const resolvedSenderId = senderId || LEGACY_REMOTE_ID;
if (!presencePeers.has(resolvedSenderId)) {
const meta = buildPeerMeta({ peerId: resolvedSenderId });
if (!senderId && isValidCSSColor(color)) {
meta.color = color;
}
upsertPeer(meta);
}
const peer = presencePeers.get(resolvedSenderId);
P2PManager.clearRemoteCursor();
const cell = getCellElement(rowIndex, colIndex);
if (cell) {
cell.classList.add(REMOTE_CURSOR_CLASS);
if (peer) {
cell.style.setProperty("--peer-color", peer.color);
cell.dataset.peer = peer.initials;
} else {
cell.dataset.peer = "PE";
}
}
markPeerActivity(resolvedSenderId);
}
function handleSyncRequest() {
if (!P2PManager.canSend()) return;
if (!hasInitialSync && !P2PManager.isHost) return;
sendFullSyncNow();
}
function handleP2PDisconnect() {
hasInitialSync = false;
P2PManager.clearRemoteCursor();
if (P2PManager.myPeerId) {
removeRemotePeers();
} else {
clearPresence();
}
P2PManager.resetControls();
P2PManager.setStatus("Disconnected.");
showToast("Peer disconnected", "warning");
}
// ========== Mouse Selection Handlers ==========
function handleCellDoubleClick(event) {
if (!(event.target instanceof Element)) return;
let cellContent = null;
if (event.target.classList.contains("cell-content")) {
cellContent = event.target;
} else if (event.target.classList.contains("cell")) {
cellContent = event.target.querySelector(".cell-content");
} else {
cellContent = event.target.closest(".cell-content");
}
if (!cellContent || !cellContent.classList.contains("cell-content")) return;