-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSermonEdit.js
More file actions
3853 lines (3564 loc) · 120 KB
/
JSermonEdit.js
File metadata and controls
3853 lines (3564 loc) · 120 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
// JSermonEdit, for better sermon writing iteration. Copyright 2025 Jibb Smart
// <div contenteditable="true" id="tableOfContents"></div>
// <div contenteditable="true" id="userDoc"></div>
const tableOfContents = document.getElementById("tableOfContents");
const userDoc = document.getElementById("userDoc");
const headingToTOC = new Map();
const headingToDoc = new Map();
const promotionMap = new Map([
["H2", "h1"],
["H3", "h2"],
["H4", "h3"],
["P", "h4"]
]);
const demotionMap = new Map([
["H1", "h2"],
["H2", "h3"],
["H3", "h4"],
["H4", "p"]
]);
const pLevel = 100;
const maxIndentLevel = 8;
const maxShowingLevel = 4;
const nodeNameToLevel = new Map([
["H1", 0], ["h1", 0],
["H2", 1], ["h2", 1],
["H3", 2], ["h3", 2],
["H4", 3], ["h4", 3],
["P", pLevel], ["p", pLevel]
]);
const sanitizeMap = new Map([
["H5", "h4"],
["H6", "h4"],
["SPAN", "."],
["OL", "."],
["UL", "."],
["LI", "p"],
["DIV", "p"]
]);
const nestableSet = new Set([
"UL",
"OL",
"LI",
"SPAN",
"#text"
]);
const orderableSet = new Set([
"H1",
"H2",
"H3",
"H4",
"P"
]);
const safeContentNodeTypes = new Set([
"H1",
"H2",
"H3",
"H4",
"P",
"#text",
"BR"
]);
let showingLevel = maxShowingLevel;
let currentFileHandle = null;
let currentFileName = null;
const lastSessionContentStorageKey = ".SermonEditLastSession";
const sessionNameStorageKey = ".SermonEditLastFileName";
const sessionContentPrefix = ".SermonEditFile";
const savedWithEditorTitle = "Editor Included";
let currentStorageKey = null;
const titleNoFile = "JSermonEdit";
const titleTail = " - " + titleNoFile;
const editorTitleTail = " - " + savedWithEditorTitle;
let isEditorBuiltInSession = false;
let defaultContent = "";
const enableCrossTabSync = true;
const prefixCrossTabUpdate = ".SermonEditCrossTabUpdate";
const prefixCrossTabRequest = ".SermonEditCrossTabRequest";
let crossTabUpdateBroadcastChannel = null;
let crossTabRequestBroadcastChannel = null;
let hasCrossTabFocus = false;
let lastUpdatedMutationNumber = -1;
let mutationCounter = 0;
let caretViewportX = -1;
let caretViewportY = -1;
let topScrollMargin = 100;
let bottomScrollMargin = 100;
let topScrollTrigger = 25;
let bottomScrollTrigger = 25;
const currentSelection = {};
currentSelection.isValid = false;
currentSelection.selectionObject = document.getSelection();
currentSelection.startNode = currentSelection.selectionObject.anchorNode;
currentSelection.startElement = currentSelection.startNode;
currentSelection.startOffset = 0;
currentSelection.endNode = currentSelection.selectionObject.focusNode;
currentSelection.endElement = currentSelection.startNode;
currentSelection.endOffset = 0;
currentSelection.focusBeforeAnchor = false;
currentSelection.charBefore = null;
currentSelection.charAfter = null;
function copyCurrentSelection() {
const newSelection = {};
newSelection.isValid = currentSelection.isValid;
newSelection.startNode = currentSelection.startNode;
newSelection.startElement = currentSelection.startElement;
newSelection.startOffset = currentSelection.startOffset;
newSelection.endNode = currentSelection.endNode;
newSelection.endElement = currentSelection.endElement;
newSelection.endOffset = currentSelection.endOffset;
newSelection.charBefore = currentSelection.charBefore;
newSelection.charAfter = currentSelection.charAfter;
return newSelection;
}
function setCurrentSelection(otherSelection) {
currentSelection.isValid = otherSelection.isValid;
currentSelection.startNode = otherSelection.startNode;
currentSelection.startElement = otherSelection.startElement;
currentSelection.startOffset = otherSelection.startOffset;
currentSelection.endNode = otherSelection.endNode;
currentSelection.endElement = otherSelection.endElement;
currentSelection.endOffset = otherSelection.endOffset;
currentSelection.charBefore = otherSelection.charBefore;
currentSelection.charAfter = otherSelection.charAfter;
}
function isSelection() {
return !currentSelection.isValid ||
currentSelection.startElement !== currentSelection.endElement ||
currentSelection.startNode !== currentSelection.endNode ||
currentSelection.startOffset !== currentSelection.endOffset;
}
function isSingleElementSelection() {
return currentSelection.isValid && currentSelection.startElement === currentSelection.endElement;
}
function getStringIfTextNode(inNode) {
if (inNode.nodeType === Node.TEXT_NODE) {
return inNode.data;
}
return null;
}
function updateSelection() {
const selectionObject = document.getSelection();
currentSelection.selectionObject = selectionObject;
if (currentSelection) {
let focusBeforeAnchor = false;
let selectionOrientationFound = false;
if (selectionObject.anchorNode === selectionObject.focusNode) {
focusBeforeAnchor = selectionObject.focusOffset < selectionObject.anchorOffset;
selectionOrientationFound = true;
} else if (selectionObject.anchorNode && selectionObject.focusNode) {
const relativePosition = selectionObject.anchorNode.compareDocumentPosition(selectionObject.focusNode);
if (relativePosition & Node.DOCUMENT_POSITION_PRECEDING) {
focusBeforeAnchor = true;
selectionOrientationFound = true;
} else if (relativePosition & Node.DOCUMENT_POSITION_FOLLOWING) {
focusBeforeAnchor = false;
selectionOrientationFound = true;
}
}
let startElement;
let endElement;
let startNode = selectionObject.anchorNode;
let endNode = selectionObject.focusNode;
let startOffset = selectionObject.anchorOffset;
let endOffset = selectionObject.focusOffset;
if (!selectionOrientationFound) {
// probably one is a parent of the other
startElement = getOrderableParent(startNode);
endElement = getOrderableParent(endNode);
if (startElement === endElement) {
const startOffset = getOffsetInParentNode(startElement, startNode, startOffset);
const endOffset = getOffsetInParentNode(endElement, endNode, endOffset);
if (endOffset < startOffset) {
focusBeforeAnchor = true;
let temp = startElement;
startElement = endElement;
endElement = temp;
temp = startNode;
startNode = endNode;
endNode = temp;
temp = startOffset;
startOffset = endOffset;
endOffset = temp;
}
currentSelection.isValid = true;
} else {
currentSelection.isValid = false;
}
} else {
if (focusBeforeAnchor) {
startNode = selectionObject.focusNode;
startOffset = selectionObject.focusOffset;
endNode = selectionObject.anchorNode;
endOffset = selectionObject.anchorOffset;
} else {
startNode = selectionObject.anchorNode;
startOffset = selectionObject.anchorOffset;
endNode = selectionObject.focusNode;
endOffset = selectionObject.focusOffset;
}
startElement = getOrderableParent(startNode);
endElement = getOrderableParent(endNode);
currentSelection.isValid = (startElement && endElement);
}
currentSelection.focusBeforeAnchor = focusBeforeAnchor;
currentSelection.startNode = startNode;
currentSelection.startElement = startElement;
currentSelection.startOffset = startOffset;
currentSelection.endNode = endNode;
currentSelection.endElement = endElement;
currentSelection.endOffset = endOffset;
currentSelection.charBefore = null;
currentSelection.charAfter = null;
if (currentSelection.isValid && currentSelection.startNode.nodeType === Node.TEXT_NODE) {
const startOffset = currentSelection.startOffset;
const textData = currentSelection.startNode.data;
if (startOffset <= textData.length) {
if (startOffset > 0) {
currentSelection.charBefore = textData[startOffset - 1];
}
if (startOffset < textData.length) {
currentSelection.charAfter = textData[startOffset];
}
}
}
} else {
currentSelection.isValid = false;
currentSelection.startNode = null;
currentSelection.startElement = null;
currentSelection.endNode = null;
currentSelection.endElement = null;
currentSelection.startOffset = 0;
currentSelection.endOffset = 0;
currentSelection.focusBeforeAnchor = false;
currentSelection.charBefore = null;
currentSelection.charAfter = null;
}
return currentSelection.startElement;
}
function restoreSelection(pauseAndUnpauseUndo = false) {
if (currentSelection.startNode && currentSelection.startNode.isConnected && currentSelection.endNode && currentSelection.endNode.isConnected) {
if (pauseAndUnpauseUndo) {
pauseUndoUpdates();
}
const newRange = document.createRange();
newRange.setStart(currentSelection.startNode, currentSelection.startOffset);
newRange.setEnd(currentSelection.endNode, currentSelection.endOffset);
const newSelection = document.getSelection();
newSelection.removeAllRanges();
newSelection.addRange(newRange);
if (pauseAndUnpauseUndo) {
unpauseUndoUpdates();
}
return true;
}
return false;
}
function setSelectionFromMutatedNodes() {
let earliestNode = null;
let earliestOffset = 0;
let latestNode = null;
let latestOffset = 0;
for (const [node, selection] of nodesAndOffsetsMutatedForSelection) {
if (!node.isConnected) {
continue;
}
if (!earliestNode) {
earliestNode = node;
earliestOffset = selection.start;
} else {
const relativePosition = earliestNode.compareDocumentPosition(node);
if ((relativePosition & Node.DOCUMENT_POSITION_CONTAINED_BY) | (relativePosition & Node.DOCUMENT_POSITION_CONTAINS)) {
// should share a common parent
const earliestOrderable = getOrderableParent(earliestNode);
const newOrderable = getOrderableParent(node);
const earliestOffsetInOrderable = getOffsetInParentNode(earliestOrderable, earliestNode, earliestOffset);
const newOffsetInOrderable = getOffsetInParentNode(newOrderable, node, selection.start);
if (newOffsetInOrderable < earliestOffsetInOrderable) {
earliestNode = node;
earliestOffset = selection.start;
} else if (newOffsetInOrderable === earliestOffsetInOrderable) {
// favour more granular selection
if (relativePosition & Node.DOCUMENT_POSITION_CONTAINED_BY) {
earliestNode = node;
earliestOffset = selection.start;
}
}
} else if (relativePosition & Node.DOCUMENT_POSITION_PRECEDING) {
// new earliest!
earliestNode = node;
earliestOffset = selection.start;
}
}
if (!latestNode) {
latestNode = node;
latestOffset = selection.end;
} else {
const relativePosition = latestNode.compareDocumentPosition(node);
if ((relativePosition & Node.DOCUMENT_POSITION_CONTAINED_BY) | (relativePosition & Node.DOCUMENT_POSITION_CONTAINS)) {
// should share a common parent
const latestOrderable = getOrderableParent(latestNode);
const newOrderable = getOrderableParent(node);
const latestOffsetInOrderable = getOffsetInParentNode(latestOrderable, latestNode, latestOffset);
const newOffsetInOrderable = getOffsetInParentNode(newOrderable, node, selection.end);
if (newOffsetInOrderable > latestOffsetInOrderable) {
latestNode = node;
latestOffset = selection.end;
} else if (newOffsetInOrderable === latestOffsetInOrderable) {
// favour more granular selection
if (relativePosition & Node.DOCUMENT_POSITION_CONTAINED_BY) {
latestNode = node;
latestOffset = selection.end;
}
}
} else if (relativePosition & Node.DOCUMENT_POSITION_FOLLOWING) {
// new latest!
latestNode = node;
latestOffset = selection.end;
}
}
}
if (earliestNode && latestNode) {
const newRange = document.createRange();
if (earliestOffset !== 0) {
// sanitize
earliestOffset = Math.min(earliestOffset, earliestNode.data.length);
}
if (latestOffset !== 0) {
// sanitize
latestOffset = Math.min(latestOffset, latestNode.data.length);
}
newRange.setStart(earliestNode, earliestOffset);
newRange.setEnd(latestNode, latestOffset);
const newSelection = document.getSelection();
newSelection.removeAllRanges();
newSelection.addRange(newRange);
}
updateSelection();
updateCaretViewportPosition();
scrollToSelectedElementIfNeeded();
}
// Syncing
function sendCrossTabUpdate() {
if (enableCrossTabSync && crossTabUpdateBroadcastChannel) {
// Tell everyone who cares to know what our content is
clearParagraphHighlights();
crossTabUpdateBroadcastChannel.postMessage(userDoc.innerHTML);
addParagraphHighlights();
lastUpdatedMutationNumber = mutationCounter;
}
}
function sendCrossTabUpdateIfFocused() {
if (hasCrossTabFocus) {
sendCrossTabUpdate();
}
}
function claimCrossTabFocus() {
if (enableCrossTabSync && crossTabRequestBroadcastChannel) {
// Let everyone else know we're claiming focus
crossTabRequestBroadcastChannel.postMessage({ IsClaimingFocus: true });
hasCrossTabFocus = true;
}
}
function claimCrossTabFocusIfNeeded() {
if (!hasCrossTabFocus) {
// Let everyone else know we're claiming focus
claimCrossTabFocus();
}
}
function otherClaimedCrossTabFocus() {
if (enableCrossTabSync) {
const hadCrossTabFocus = hasCrossTabFocus;
hasCrossTabFocus = false; // Update right away before sending any messages
if (hadCrossTabFocus) {
// If we had cross tab focus, update with our state
sendCrossTabUpdate();
}
}
}
function requestCrossTabUpdate() {
if (enableCrossTabSync && crossTabRequestBroadcastChannel) {
// Request an update from the current focused tab (if it exists)
crossTabRequestBroadcastChannel.postMessage({ IsRequestingUpdate: true });
}
}
function requestCrossTabUpdateIfNeeded() {
if (enableCrossTabSync && crossTabRequestBroadcastChannel) {
// Request an update from the current focused tab (if it exists)
crossTabRequestBroadcastChannel.postMessage({ IsRequestingUpdate: true, OnlyIfChanged: true });
}
}
function otherRequestedCrossTabUpdate(onlyIfChanged) {
if (enableCrossTabSync && hasCrossTabFocus) {
// Someone else requested an update, so update if needed
if (!onlyIfChanged || mutationCounter !== lastUpdatedMutationNumber) {
sendCrossTabUpdateIfFocused();
}
}
}
function otherMadeCrossTabRequest(event) {
if (event.data.IsClaimingFocus) {
otherClaimedCrossTabFocus();
}
if (event.data.IsRequestingUpdate) {
otherRequestedCrossTabUpdate(event.data.OnlyIfChanged);
}
}
function otherSentCrossTabUpdate(event) {
if (enableCrossTabSync) {
// Receive content from another tab
userDoc.innerHTML = event.data;
addParagraphHighlights();
lastUpdatedMutationNumber = mutationCounter;
}
}
function storageKeyFromFileName(fileName) {
return fileName ? sessionContentPrefix + "." + fileName : null;
}
function setStorageKeyAndUpdateChannelsIfNeeded(storageKey) {
if (currentStorageKey === storageKey) {
// No changes needed!
return;
}
currentStorageKey = storageKey;
if (crossTabUpdateBroadcastChannel) {
crossTabUpdateBroadcastChannel.close();
crossTabUpdateBroadcastChannel = null;
}
if (crossTabRequestBroadcastChannel) {
crossTabRequestBroadcastChannel.close();
crossTabRequestBroadcastChannel = null;
}
if (currentStorageKey && enableCrossTabSync) {
hasCrossTabFocus = document.hasFocus();
crossTabUpdateBroadcastChannel = new BroadcastChannel(prefixCrossTabUpdate + currentStorageKey);
crossTabRequestBroadcastChannel = new BroadcastChannel(prefixCrossTabRequest + currentStorageKey);
crossTabUpdateBroadcastChannel.onmessage = otherSentCrossTabUpdate;
crossTabRequestBroadcastChannel.onmessage = otherMadeCrossTabRequest;
requestCrossTabUpdate();
if (hasCrossTabFocus) {
claimCrossTabFocus();
}
}
}
// Undo/Redo
function pauseUndoUpdates() {
userDoc.dataset.undoPaused = "true";
}
function unpauseUndoUpdates() {
delete userDoc.dataset.undoPaused;
}
function updateCaretViewportPosition() {
if (currentSelection && currentSelection.selectionObject) {
const selectionRange = currentSelection.selectionObject.getRangeAt(0);
if (selectionRange) {
const selectionRects = selectionRange.getClientRects();
const selectionRect = selectionRects.length > 0 ? selectionRects[0] : null;
if (selectionRect && (selectionRect.left > 0 || selectionRect.bottom > 0)) {
caretViewportX = (selectionRect.left + selectionRect.right) * 0.5;
caretViewportY = Math.min(Math.max(selectionRect.bottom, 0), window.innerHeight);
} else {
caretViewportX = -1;
caretViewportY = -1;
}
} else {
caretViewportX = -1;
caretViewportY = -1;
}
} else {
caretViewportX = -1;
caretViewportY = -1;
}
}
function scrollToMaintainCaretViewportPosition() {
if (caretViewportX > 0 || caretViewportY > 0) {
// get difference in position
let diffX = 0;
let diffY = 0;
const selectionObject = document.getSelection();
if (selectionObject) {
const selectionRange = selectionObject.getRangeAt(0);
if (selectionRange) {
const selectionRect = selectionRange.getBoundingClientRect();
if (selectionRect && (selectionRect.left > 0 || selectionRect.bottom > 0)) {
caretX = (selectionRect.left + selectionRect.right) * 0.5;
caretY = selectionRect.bottom;
diffX = caretX - caretViewportX;
diffY = caretY - caretViewportY;
}
}
}
window.scrollBy({
top: diffY,
left: diffX,
behavior: "instant",
});
caretViewportX = -1;
caretViewportY = -1;
}
}
function scrollToSelectedElementIfNeeded() {
if (currentSelection && currentSelection.startElement) {
let foundValidCaretInfo = false;
const selectionRange = currentSelection.selectionObject.getRangeAt(0);
if (selectionRange) {
const selectionRect = selectionRange.getBoundingClientRect();
if (selectionRect && (selectionRect.left != 0 || selectionRect.bottom != 0)) {
const triggerTop = selectionRect.top < topScrollTrigger;
const triggerBottom = selectionRect.bottom > window.innerHeight - bottomScrollTrigger;
const safeSelectionSize = window.innerHeight - topScrollMargin - bottomScrollMargin;
if (selectionRect.height >= safeSelectionSize) {
if (currentSelection.focusBeforeAnchor) {
if (triggerTop) {
window.scrollBy({
top: selectionRect.top - topScrollMargin,
left: 0,
behavior: "smooth",
});
}
} else if (triggerBottom) {
window.scrollBy({
top: selectionRect.bottom - window.innerHeight + bottomScrollMargin,
left: 0,
behavior: "smooth",
});
}
} else {
if (triggerTop) {
window.scrollBy({
top: selectionRect.top - topScrollMargin,
left: 0,
behavior: "smooth",
});
} else if (triggerBottom) {
window.scrollBy({
top: selectionRect.bottom - window.innerHeight + bottomScrollMargin,
left: 0,
behavior: "smooth",
});
}
}
foundValidCaretInfo = true;
}
}
if (!foundValidCaretInfo) {
// just scroll to the element
currentSelection.startElement.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "nearest" });
}
}
caretViewportX = -1;
caretViewportY = -1;
}
const undoStack = new Array();
const redoStackA = new Array();
const redoStackB = new Array();
let redoStack = redoStackA;
let redoAnchor = null;
let currentDoingMutation = null;
const inputEventNoCategory = 0;
const inputEventText = 1;
const inputEventEnter = 2;
const inputEventBackspace = 3;
const inputEventDel = 4;
const inputEventRemove = 5;
const inputEventMove = 6;
const inputEventPromote = 7;
const inputEventHide = 8;
const inputEventPaste = 9;
const inputEventMoveCaret = 10;
const inputEventUndoRedo = 11;
const inputEventToggleAltA = 12;
const inputEventToggleAltB = 13;
let currentInputType = inputEventNoCategory;
let previousInputType = inputEventNoCategory;
let doingUndo = false;
let doingRedo = false;
let undoPaused = false;
let needsNewUndo = true;
let needsNewRedo = true;
let undoId = 0;
const nodeStatesRecordedForUndo = new Set();
const nodesAndOffsetsMutatedForSelection = new Map();
function queueNewUndo() {
undoId += 1;
userDoc.dataset.undoId = undoId;
}
function finishUndo() {
needsNewUndo = true;
needsNewRedo = true;
currentDoingMutation = null;
nodeStatesRecordedForUndo.clear();
}
function undoMutations(mutationList) {
let wasSubstantial = false;
const numMutations = mutationList.length;
let mutationIdx = numMutations - 1;
for (; mutationIdx >= 0; mutationIdx--) {
const mutation = mutationList[mutationIdx];
if (mutation.type === "childList") {
wasSubstantial = true;
let nodeBeforeRemove = null;
let nodeAfterRemove = null;
// remove the addeds...
for (addedNode of mutation.addedNodes) {
if (addedNode.parentNode === mutation.target) {
if (!nodeBeforeRemove || nodeBeforeRemove === addedNode) {
nodeBeforeRemove = addedNode.previousSibling;
}
if (!nodeAfterRemove || nodeAfterRemove === addedNode) {
nodeAfterRemove = addedNode.nextSibling;
}
addedNode.remove();
}
}
// ...then add the removeds
if (mutation.removedNodes.length > 0) {
if (mutation.previousSibling) {
mutation.previousSibling.after(...mutation.removedNodes);
} else if (mutation.nextSibling) {
mutation.nextSibling.before(...mutation.removedNodes);
} else {
mutation.target.append(...mutation.removedNodes);
}
}
if (mutation.removedNodes.length > 0) {
const numRemovedNodes = mutation.removedNodes.length;
// we added nodes! These should be our selection!
let foundNodeForSelection = findNodeAndOffset(mutation.removedNodes[0], 0);
if (foundNodeForSelection && foundNodeForSelection.leafNode) {
let nodeSelection = nodesAndOffsetsMutatedForSelection.get(foundNodeForSelection.leafNode);
if (nodeSelection) {
nodeSelection.start = Math.min(nodeSelection.start, foundNodeForSelection.offset);
} else {
nodesAndOffsetsMutatedForSelection.set(foundNodeForSelection.leafNode, {start: foundNodeForSelection.offset, end: foundNodeForSelection.offset});
}
}
foundNodeForSelection = findNodeAndOffset(mutation.removedNodes[numRemovedNodes-1], Infinity);
if (foundNodeForSelection && foundNodeForSelection.leafNode) {
nodeSelection = nodesAndOffsetsMutatedForSelection.get(foundNodeForSelection.leafNode);
if (nodeSelection) {
nodeSelection.end = Math.max(nodeSelection.end, foundNodeForSelection.offset);
} else {
nodesAndOffsetsMutatedForSelection.set(foundNodeForSelection.leafNode, {start: foundNodeForSelection.offset, end: foundNodeForSelection.offset});
}
}
} else if (nodeBeforeRemove) {
let foundNodeForSelection = findNodeAndOffset(nodeBeforeRemove, Infinity);
let foundNode, foundOffset;
if (foundNodeForSelection && foundNodeForSelection.leafNode) {
foundNode = foundNodeForSelection.leafNode;
foundOffset = foundNodeForSelection.offset;
} else {
foundNode = nodeBeforeRemove;
foundOffset = 0;
}
let nodeSelection = nodesAndOffsetsMutatedForSelection.get(foundNode);
if (nodeSelection) {
nodeSelection.start = Math.min(nodeSelection.start, foundOffset);
} else {
nodesAndOffsetsMutatedForSelection.set(foundNode, {start: foundOffset, end: foundOffset});
}
} else if (nodeAfterRemove) {
let foundNodeForSelection = findNodeAndOffset(nodeAfterRemove, 0);
let foundNode, foundOffset;
if (foundNodeForSelection && foundNodeForSelection.leafNode) {
foundNode = foundNodeForSelection.leafNode;
foundOffset = foundNodeForSelection.offset;
} else {
foundNode = nodeAfterRemove;
foundOffset = 0;
}
let nodeSelection = nodesAndOffsetsMutatedForSelection.get(foundNode);
if (nodeSelection) {
nodeSelection.start = Math.min(nodeSelection.start, foundOffset);
} else {
nodesAndOffsetsMutatedForSelection.set(foundNode, {start: foundOffset, end: foundOffset});
}
}
} else if (mutation.type === "characterData") {
wasSubstantial = true;
// Find first and last difference
let firstDifferenceIndex;
const oldString = mutation.target.data;
const newString = mutation.oldValue;
const oldLength = oldString.length;
const newLength = newString.length;
const minLength = Math.min(oldLength, newLength);
const maxLength = Math.max(oldLength, newLength);
for (firstDifferenceIndex = 0; firstDifferenceIndex < minLength; ++firstDifferenceIndex) {
if (oldString[firstDifferenceIndex] !== newString[firstDifferenceIndex]) {
break;
}
}
let lastDifferenceIndexFromEnd;
for (lastDifferenceIndexFromEnd = 0; lastDifferenceIndexFromEnd < minLength; ++lastDifferenceIndexFromEnd) {
if (oldString[oldLength - 1 - lastDifferenceIndexFromEnd] !== newString[newLength - 1 - lastDifferenceIndexFromEnd]) {
break;
}
}
// If the string has changed in length, the selection must be at least as big as that change in length, up to the end of the changed string.
// If we don't do this, common letters between the end of the new string and the old string (eg: the ending 'e' in "Maybe we" and "Maybe")
// can give us an incorrect selection, and even an end-of-selection before our start-of-selection.
let lastDifferenceIndex = newLength - lastDifferenceIndexFromEnd;
{
const lengthDifference = maxLength - minLength;
lastDifferenceIndex = Math.min(newLength, Math.max(lastDifferenceIndex, firstDifferenceIndex + lengthDifference));
}
mutation.target.data = mutation.oldValue;
let nodeSelection = nodesAndOffsetsMutatedForSelection.get(mutation.target);
if (nodeSelection) {
nodeSelection.start = Math.min(nodeSelection.start, firstDifferenceIndex);
nodeSelection.end = Math.max(nodeSelection.end, lastDifferenceIndex);
} else {
nodesAndOffsetsMutatedForSelection.set(mutation.target, {start: firstDifferenceIndex, end: lastDifferenceIndex});
}
} else if (mutation.attributeName) {
if (mutation.attributeName === "class") {
wasSubstantial = true;
if (!nodesAndOffsetsMutatedForSelection.get(mutation.target)) {
nodesAndOffsetsMutatedForSelection.set(mutation.target, {start: 0, end: 0});
}
}
if (mutation.oldValue) {
mutation.target.setAttribute(mutation.attributeName, mutation.oldValue);
} else {
mutation.target.removeAttribute(mutation.attributeName);
}
}
}
return wasSubstantial;
}
function getAndPrepCurrentUndoRedoState(putInRedo = false, isSubstantial = true) {
if (putInRedo) {
// add to redo stack
if (needsNewRedo || redoStack.length === 0) {
const newRedo = new Array();
redoStack.push(newRedo);
needsNewRedo = false;
return newRedo;
} else {
const topRedo = redoStack[redoStack.length - 1];
return topRedo;
}
} else {
// clear redo stack
if (!doingRedo && isSubstantial) {
clearRedo();
}
// add to undo stack
if (needsNewUndo || undoStack.length === 0) {
const newUndo = new Array();
undoStack.push(newUndo);
needsNewUndo = false;
return newUndo;
} else {
const topUndo = undoStack[undoStack.length - 1];
return topUndo;
}
}
}
// Events on changes for undo/redo
const mutationCallback = (mutationList, observer) => {
// Do any needed processing here
++mutationCounter;
// Create undo/redo events as needed
for (const mutation of mutationList) {
// Get the info
if (!undoPaused && mutation.type === "childList") {
getAndPrepCurrentUndoRedoState(doingUndo).push(mutation);
if (currentInputType === inputEventText) {
currentDoingMutation = mutation;
}
} else if (mutation.type === "attributes") {
if (mutation.target === userDoc) {
if (mutation.attributeName === "data-undo") {
// This data attribute dictates writing changes to redo stack instead of undo stack
if (mutation.oldValue === "undo") {
doingUndo = false;
finishUndo();
} else {
doingUndo = true;
finishUndo();
}
} else if (mutation.attributeName === "data-redo") {
// This data attribute dictates whether redo stack gets cleared on new changes
if (mutation.oldValue === "redo") {
doingRedo = false;
finishUndo();
} else {
doingRedo = true;
finishUndo();
}
} else if (mutation.attributeName === "data-undo-paused") {
// This data attribute dictates whether undo/redo updates do anything at all
if (mutation.oldValue === "true") {
undoPaused = false;
} else {
undoPaused = true;
}
} else if (mutation.attributeName === "data-undo-id") {
// This data attribute is used to break up changes that might otherwise be combined
finishUndo();
}
} else if (!undoPaused) {
if (mutation.attributeName === "data-selected" || mutation.attributeName === "data-selection-child") {
// skip
} else {
getAndPrepCurrentUndoRedoState(doingUndo, mutation.attributeName === "class").push(mutation);
nodeStatesRecordedForUndo.add(mutation.target);
}
}
} else if (!undoPaused && mutation.type === "characterData") {
let canConsolidate = false;
if (!doingUndo && !doingRedo) {
if (currentDoingMutation && currentDoingMutation.target === mutation.target) {
const currentDoingMutationPreviousLength = currentDoingMutation.oldValue.length;
const mutationPreviousLength = mutation.oldValue.length;
const mutationDataLength = mutation.target.data.length;
if (mutationDataLength === mutationPreviousLength + 1) {
if (mutationPreviousLength > currentDoingMutationPreviousLength) {
// continuing to increase by 1
canConsolidate = true;
}
} else if (mutationDataLength === mutationPreviousLength - 1) {
if (mutationPreviousLength < currentDoingMutationPreviousLength) {
// continuing to decrease by 1
canConsolidate = true;
}
} else if (mutation.oldValue === mutation.target.data) {
// not even changing the content -- I don't know why it gets here
canConsolidate = true;
}
}
currentDoingMutation = mutation;
}
if (!canConsolidate) {
getAndPrepCurrentUndoRedoState(doingUndo).push(mutation);
}
// if (!nodeStatesRecordedForUndo.has(mutation.target)) {
// getAndPrepCurrentUndoRedoState(doingUndo).push(mutation);
// nodeStatesRecordedForUndo.add(mutation.target);
// }
}
}
};
const mutationObserver = new MutationObserver(mutationCallback);
function startUndoRedoObserver() {
mutationObserver.observe(userDoc, { attributes: true, attributeOldValue: true, characterData: true, characterDataOldValue: true, childList: true, subtree: true });
}
function stopUndoRedoObserver() {
mutationObserver.disconnect();
}
function diffWithCachedElements(cachedElements, cachedCopies) {
let currentNode;
let startDiffOffset = -1;
let endDiffOffset = -1;
const numCachedElements = cachedElements.length;
let firstDifferenceIndex = 0;
let firstDifference = null;
let differenceFound = false;
let lastDifferenceFound = false;
let undoDiv = null;
let firstDifferenceNode = null;
for (; firstDifferenceIndex < numCachedElements; firstDifferenceIndex++) {
firstDifference = findFirstDifference(cachedElements[firstDifferenceIndex], cachedCopies[firstDifferenceIndex]);
if (firstDifference.differenceFound) {
differenceFound = true;
firstDifferenceNode = cachedElements[firstDifferenceIndex];
break;
}
}
if (differenceFound) {
// find last difference
let lastDifference = null;
let lastDifferenceIndex = numCachedElements - 1;
for (; lastDifferenceIndex >= firstDifferenceIndex; lastDifferenceIndex--) {
if (lastDifference) {
if (lastDifferenceIndex !== firstDifferenceIndex) {
undoDiv.prepend(cachedCopies[lastDifferenceIndex]);
} else {
const finalCachedDifference = splitAtOffset(cachedCopies[firstDifferenceIndex], firstDifference.offset);
undoDiv.prepend(finalCachedDifference);
return undoDiv;
}
} else {
lastDifference = findLastDifference(cachedElements[lastDifferenceIndex], cachedCopies[lastDifferenceIndex]);
if (lastDifference.differenceFound) {
lastDifferenceFound = true;
undoDiv = document.createElement("div");
undoDiv.dataset.indexA = cachedStartIndex + firstDifferenceIndex;
undoDiv.dataset.offsetA = firstDifference.offset;
undoDiv.dataset.indexB = cachedStartIndex + lastDifferenceIndex;
undoDiv.dataset.offsetB = lastDifference.offset;
// split this one:
const lastCachedSplit = splitAtOffset(cachedCopies[lastDifferenceIndex], lastDifference.offset, false);
if (lastDifferenceIndex === firstDifferenceIndex) {
// and split at the beginning, too:
const finalCachedDifference = splitAtOffset(lastCachedSplit, firstDifference.offset);
undoDiv.append(finalCachedDifference);
return undoDiv;
} else {
undoDiv.append(lastCachedSplit);
}
} else {
lastDifference = null;
}
}
}
}
return null;
}
function doDiffUndoGetRedo(inUndoDiv) {
const indexA = inUndoDiv.dataset.indexA;
const offsetA = inUndoDiv.dataset.offsetA;
const indexB = inUndoDiv.dataset.indexB;
const offsetB = inUndoDiv.dataset.offsetB;
if (isNaN(indexA) || isNaN(offsetA) || isNaN(indexB) || isNaN(offsetB)) {
return null;
}