-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
2427 lines (1979 loc) · 98.5 KB
/
index.html
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
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Realtime Editor Testing</title>
<style>
*::selection, .selected {
background-color: #0C9DFF50; /* Same as rgb(180, 225, 255) but with an alpha value of 0.31 */
}
body {
display: flex;
flex-direction: column;
width: 100vw;
height: 100vh;
margin: 0px;
padding: 0px;
align-items: center;
justify-content: center;
}
#editor {
display: inline-block;
padding: 50px;
width: 60vw;
height: 40vh;
overflow-y: auto;
box-shadow: 0px 0px 10px rgb(225, 225, 225);
border-radius: 20px;
font-size: 1.2rem;
font-family: Helvetica;
transition: box-shadow 0.25s;
}
#editor:hover {
box-shadow: 0px 0px 10px rgb(200, 200, 200);
}
#editor:focus {
outline: none;
box-shadow: 0px 0px 10px rgb(200, 200, 200);
}
.buttons {
display: flex;
justify-content: center;
margin-bottom: 20px;
border-radius: 20px;
box-shadow: 0px 0px 10px rgb(225, 225, 225);
padding: 10px 5px;
}
.button {
width: 50px;
height: 50px;
line-height: 50px;
border-radius: 10px;
box-shadow: 0px 0px 10px rgb(225, 225, 225);
font-size: 1.5rem;
font-family: Helvetica;
transition: box-shadow 0.25s;
margin: 0px 5px;
text-align: center;
transition: box-shadow 0.25s;
}
.button:hover {
cursor: pointer;
box-shadow: 0px 0px 10px rgb(200, 200, 200);
}
.button-active {
box-shadow: 0px 0px 10px rgb(50, 150, 225);
}
.button-active:hover {
box-shadow: 0px 0px 10px rgb(25, 125, 200);
}
.bold {
font-weight: bold;
}
.italic {
font-style: italic;
}
.underline {
text-decoration: underline;
}
.strikethrough {
text-decoration: line-through;
}
.underline.strikethrough {
text-decoration: underline line-through;
}
.link {
color: rgb(50, 150, 225);
}
.link-creator {
display: flex;
background-color: rgb(255, 255, 255);
width: 360px;
padding: 20px;
border-radius: 10px;
box-shadow: 0px 0px 10px rgb(225, 225, 225);
font-size: 1.2rem;
font-family: Helvetica;
}
.link-creator-input {
white-space: nowrap;
overflow-x: auto;
flex: 1;
margin-right: 10px;
}
.link-creator-input:focus {
outline: none;
}
.link-creator-preview, .link-creator-cancel {
margin-right: 10px;
}
.link-creator-preview, .link-creator-cancel, .link-creator-confirm {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.link-creator-preview:hover, .link-creator-cancel:hover, .link-creator-confirm:hover {
cursor: pointer;
}
.users {
pointer-events: none;
display: inline-block;
margin-top: 20px;
padding: 20px 50px;
width: 60vw;
overflow-y: auto;
box-shadow: 0px 0px 10px rgb(225, 225, 225);
border-radius: 20px;
font-size: 1.2rem;
font-family: Helvetica;
transition: box-shadow 0.25s;
text-align: center;
}
@keyframes blink {
to {
border-left: 2px solid rgba(0, 0, 0, 0);
}
}
@-webkit-keyframes blink {
to {
border-left: 2px solid rgba(0, 0, 0, 0);
}
}
</style>
</head>
<body>
<div class="buttons"><div class="button bold" id="bold">B</div><div class="button italic" id="italic">I</div><div class="button underline" id="underline">U</div><div class="button strikethrough" id="strikethrough">S</div><div class="button link" id="link">K</div></div>
<div id="editor" contenteditable="plaintext-only"></div>
<div class="users">Active: ...   |   Idle: ...</div>
<script type="module">
/*
Things to make this even better:
[DONE!!] Send data regarding the key that comes before/after it; this can then be used to error check and correctly position keys when pressed at the exact same time
[DONE!!] Maximize the conditions met by checking the score if positioned one char to the right, or one char to the left (having the letters on both sides of the char to insert [2/2] is ideal; otherwise, shoot for [1/2]; if [0/0], leave the char where it is)
[DONE!!] ALSO: periodically (not very often, however) pull the ACTUAl content stored in Firebase(?) perhaps only do this on blur and focus(?) ===> update the text region periodically, assuming that it is not currently being focused (elm !== document.activeElement)
also to implement:
[NOTE] pay attention to [NOTE]s!!!
[NOTE] check for document.activeElement or document.activeElement.id checks; these need to ensure that activeElement is a valid vertex
- [DONE!!] deleting
([DONE!!]including deleting selections of text)
- [DONE!!] pasting
- [DONE!!] selecting text and then typing/pasting/etc. (perhaps handle these events (selecting text + whatever else) separately?)
[DONE!!] spaces (when typed) are not treated as char 160 on the client's end (e.preventDefault() is needed??) [FIXED BY CHANGING ALL TO SPACES]
[CANCELED] sync in the background when not focused (ignore changes, basically)
[DONE!!] periodically check sync(?)
[DONE!! IMPORTANT] ==> remove old "changes" ( > 10 mins old (?)) [remove them if all users have updated to them; check the lastUpdated timestamp in user data and if all are > timestamp for change, delete it]
[DONE!!] display cursor positions + selections => USE SPANS!!!
[DONE!!] update cursors on sync
[DONE!!] store cursor positions locally + update them whenever something is typed/changes come in (maybe)
[DONE!!] don't update a user's cursor unless it has changed
[DONE!!] figure out why sync will randomly go off sometimes??
[DONE!!] if content is synced too many times within a short time frame, assume that something went wrong and kick the client, reloading the page
[DONE!!] figure out why the editor doesn't like "ß"
[DONE!!] figure out why undoing/redoing certain things (such as typing) only has a FitScore of 4 ??? (should be 5)
[DONE!!] test new FitScore implementation
[DONE!!] whenever cursor is changed, update user.changed; then, only update the cursor position if the "user.changed" value has been updated + the other pre-existing if-check is met
[DONE!!] when typing fast at the same pos as other user's cursor, they desync
[TODO] handle Chromebook grammar checker???
[TODO] TEST TEST TEST!!!
[DONE!!] check styling on syncing
[DONE!!] status sometimes not pushed to firebase??? (might be bc laptop fell asleep + ondisconnect was called; see if theres a reconnect function or smth??)
[DONE!!] bold, italics, underlining
[DONE!!] strikethrough
[DONE!!] links!! :D
[DONE!!] implement links themselves
[DONE!!] send link changes
[DONE!!] store links in Firebase
[DONE!!] sync if links are not synced up properly
[DONE!!] undo/redo links
[DONE!!] only apply link styling if typing within a link; check the space to the right as well; if typing directly after a link, the styling should not be applied
[DONE!!] add a button to open links
[DONE!!] \n sometimes changes to \r (???? might've been bc i was screwing around with cursor stuff... might not be an issue but still test anyway)
[DONE!! (MIGHT BE FIXED??)] sometimes when one person is typing and the other is typing / deletes, their cursor will jump to the start of the doc which is kinda annoying
[DONE!!] if text is selected (ctrl + a) and end of selection is end of doc, and someone types something, keep end of selection at end of doc
[DONE!!] handle ctrl + x
[DONE!!] disable ctrl + delete
[DONE!!] implement custom ctrl + delete (replace until previous space with "" [nothing] - note that if character immediately before cursor is a space, that space should be ignored and deleted as well as the rest of the text content, like normal ctrl + delete)
[DONE!!] enters at bottom of doc don't show up until after syncing (sometimes) + sometimes things show up on the wrong bottom line (oof)
[DONE!!] pasting in content with line breaks does not work properly (yikes)
[DONE!!] before and after checking should stop at index -1 (or -2 idk) or at the end of the text content; otherwise, you might get false positives which is not ideal
[DONE!!] HANDLE dragging + dropping text???
[DONE!!] HANDLE CTRL + Z (should be disabled if multiple editors at same time; or immediate sync(?) assuming client is up-to-date)
[NOTE] TO TEST: try out multiple docs!! the code should be setup for it already, just need to change depending on what div is focused :)
[DONE!!] replacing formatted text should copy that text's formatting (first char? idk check what docs does)
[DONE!!] clicking "bold" or "italic" or "underline" should store those values in some variable + apply styles when key is pressed; wipe if arrow key or mouse is clicked
[DONE!!] ctrl + b should bold, ctrl + i should italic, etc.
[DONE!!] send style updates to firebase
[DONE!!] store styling in firebase somewhere
[DONE!!] send undo as a change, rather than the actual event itself LOL [I THINK I FIXED THIS TOO LMAOOOOOOO; test it ig????]
[DONE!!] moving text around still doesn't work (insertFromDrop) [I THINK I FIXED IT??? TEST THIS AND ALSO TEST WHEN EVERYONE IS ABLE TO MOVE STUFF AROUND]
[DONE!!] Get spell corrections working!
[DONE!!] Deny emojis
[DONE!!] handle errors when not focused on anything and a change is sent
*/
// Import Firebase modules:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js";
import { getDatabase, set, get, ref, query, onValue, child, push, remove, onDisconnect } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-database.js";
// Firebase configuration:
const firebaseConfig = {
apiKey: "AIzaSyDChSvCEHSlLxpl-oKr21_kjT3Z_1f-2Nw",
authDomain: "realtime-editor-testing.firebaseapp.com",
projectId: "realtime-editor-testing",
storageBucket: "realtime-editor-testing.appspot.com",
messagingSenderId: "905100052469",
appId: "1:905100052469:web:cfaf1072946694eea342bc"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
let pending = [];
let applied = [];
let uid = "User" + getTime().toString() + Math.floor(Math.random() * Math.pow(10, 5)).toString();
let lastKeyPress;
let lastChange;
let lastUpdated;
let prevContentUpdated = 0;
let contentCheck = 0;
let lastInputTimeStamp = 0;
let activeVertex = false;
let stack = {
undo: [],
redo: []
};
let userCache = {};
let activeStyles = [];
let contentCheckDelay = 5;
let syncCount = 0;
window.addEventListener("load", async function() {
// If the client disconnects, clear their user data:
onDisconnect(ref(db, `users/${uid}`)).remove();
// Get the stored text for the editor:
let content = (await getData("vertexes/editor/content", function(err) { console.error(err); })) || { vertex: "editor", text: "\n", style: { bold: "", italic: "", underline: "", strikethrough: "" }, uid: "", updated: 0 };
let userData = (await getData("users", function(err) { console.error(err); })) || {};
setText(document.getElementById("editor"), content.text + (content.text[content.text.length - 1] !== "\n" ? "\n" : ""), { start: 0, end: 0 }, true);
setStyle(document.getElementById("editor"), content.style);
setLinks(document.getElementById("editor"), content.links);
setCursors(userData);
// Update the "applied" values:
let changesObj = await getData("changes", function(err) { console.error(err); });
for (let i in changesObj) {
applied.push(i);
}
// Set the user data:
set(ref(db, `users/${uid}`), {
status: "active",
vertex: false,
cursor: false,
changed: new Date().getTime(),
updated: new Date().getTime()
});
// Get user data:
onValue(ref(db, "users"), (snapshot) => {
const userData = snapshot.val();
if (uid === "_disconnected")
return;
// Check for disconnects:
if (!userData || !userData[uid] || !userData[uid].status) {
uid = "_disconnected";
alert("You have been disconnected from the server.\n\nIf this is a recurring issue, there might be something wrong with the editor's content or your internet connection."); // [NOTE]
location.reload(true);
return;
}
// Remove disconnected user data:
if (userData["_disconnected"]) {
remove(ref(db, `users/_disconnected`));
delete userData["_disconnected"];
}
// Update user status:
let statusData = {
active: 0,
idle: 0
};
for (let u in userData) {
statusData[userData[u].status]++;
}
document.getElementsByClassName("users")[0].innerHTML = `Active: ${statusData.active}   |   Idle: ${statusData.idle}`;
// Update cursor positions:
setCursors(userData);
});
// Get new changes coming in:
onValue(ref(db, "changes"), (snapshot) => {
const changes = snapshot.val();
checkForChanges(changes);
});
// Check periodically to ensure the clients are all synced properly:
setInterval(async function() {
let content = (await getData("vertexes/editor/content", function(err) { console.error(err); })) || { vertex: "editor", text: "\n", style: { bold: "", italic: "", underline: "", strikethrough: "" }, uid: "", updated: 0 };
sync(document.getElementById("editor"), content);
}, 250);
// Check for idle users and remove disconnected users:
setInterval(async function() {
let users = (await getData("users", function(err) { console.error(err); })) || { vertex: "editor", text: "\n", style: { bold: "", italic: "", underline: "", strikethrough: "" }, uid: "", updated: 0 };
// Check if a user is idle or should be kicked:
for (let u in users) {
// Set status to idle if no changes have been made for more than 5 minutes:
if (users[u].status === "active" && getTime() - users[u].changed >= 5 * 60 * 1000) {
set(ref(db, `users/${u}/status`), "idle");
}
// Remove user from the database if they have not recieved an update for more than 10 minutes [NOTE when implementing into real thing, take the last updated time into consideration (for example, a user should only be kicked if they have not recieved an update 5 minutes after the last time the content itself was updated)]:
if (!users[u].status || getTime() - users[u].updated >= 10 * 60 * 1000) {
remove(ref(db, `users/${u}`));
}
}
}, 5 * 1000);
});
async function sync(el, content) {
// Ignore if the update is old:
if (content.updated >= prevContentUpdated) {
prevContentUpdated = content.updated;
} else {
return;
}
// Don't sync while applying changes:
if (getTime() - lastChange <= 1000)
return;
// Don't sync while the user is typing:
if (getTime() - lastKeyPress <= 1000)
return;
// Ignore if the update was by the same user:
if (content.uid === uid)
return;
// Check if the client is synced (this checks the text, styling, and links):
if (content.text !== el.textContent || content.style.bold !== getMeta(el, "bold") || content.style.italic !== getMeta(el, "italic") || content.style.underline !== getMeta(el, "underline") || content.style.strikethrough !== getMeta(el, "strikethrough") || JSON.stringify(content.links) !== JSON.stringify(getMeta(el, "links"))) {
// Client is not synced; take note of this:
contentCheck++;
// If the client is not synced for 5 times in total (~1.25 seconds), sync them:
if (contentCheck >= contentCheckDelay) {
console.warn("Sync");
// Store the caret position to perserve it for later:
let caretPos = getCaretPosition(document.getElementById("editor"));
// Grab user data to sync cursors:
let userData = (await getData("users", function(err) { console.error(err); })) || {};
// Sync everything:
document.getElementById("editor").textContent = "";
setText(el, content.text + (content.text[content.text.length - 1] !== "\n" ? "\n" : ""), { start: 0, end: 0 }, true);
setStyle(el, content.style);
setLinks(el, content.links);
setCursors(userData);
setCaretPosition(el, caretPos);
contentCheck = 0;
syncCount++;
// Disconnect the user if sync is unable to fix the issue:
if (syncCount >= 10)
remove(ref(db, `users/${uid}`));
}
// Client is synced; reset the counter:
} else {
contentCheck = 0;
syncCount = 0;
}
}
function setButtons() {
// Reset active classes:
while (document.getElementsByClassName("button-active").length > 0)
document.getElementsByClassName("button-active")[0].classList.remove("button-active");
// Add the classes back to any active styles:
for (let i = 0; i < activeStyles.length; i++) {
document.getElementById(activeStyles[i]).classList.add("button-active");
}
}
function getActiveStyles(el) {
let caretPos = getCaretPosition(el);
// Determine what the current active styles should be:
// No text is selected; get the style of the character before:
if (caretPos.start === caretPos.end) {
return (el.childNodes[caretPos.start - 1] && el.childNodes[caretPos.start - 1].classList) ? [...el.childNodes[caretPos.start - 1].classList].filter(cl => (cl.indexOf("cursor") === -1 && cl.indexOf("link") === -1 && cl.indexOf("selected") === -1)) : [];
// Text is being selected; get the styles that apply to all characters in the selection:
} else {
// Get the styles of the first character in the selection:
let styles = (el.childNodes[caretPos.start] && el.childNodes[caretPos.start].classList) ? [...el.childNodes[caretPos.start].classList].filter(cl => (cl.indexOf("cursor") === -1 && cl.indexOf("link") === -1 && cl.indexOf("selected") === -1)) : [];
// Remove the style if it doesn't apply to all of the characters in the selection:
for (let i = caretPos.start + 1; i < caretPos.end; i++) {
let indexedStyles = (el.childNodes[i] && el.childNodes[i].classList) ? [...el.childNodes[i].classList].filter(cl => (cl.indexOf("cursor") === -1 && cl.indexOf("link") === -1 && cl.indexOf("selected") === -1)) : [];
styles = styles.filter(cl => indexedStyles.indexOf(cl) !== -1);
}
return styles;
}
}
document.getElementById("editor").addEventListener("keydown", async function(e) {
// Update cursor position in Firebase (after event finishes):
setTimeout(function() {
set(ref(db, `users/${uid}/cursor`), getCaretPosition(document.getElementById("editor")));
// Handle arrow keys and "Ctrl + A":
if (e.keyCode === 37 || e.keyCode === 38 || e.keyCode === 39 || e.keyCode === 40 || (e.ctrlKey && e.keyCode === 65)) {
activeStyles = getActiveStyles(document.getElementById("editor"));
setButtons();
set(ref(db, `users/${uid}/changed`), getTime());
set(ref(db, `users/${uid}/status`), "active");
}
}, 0);
// Close the link creator:
while (document.getElementsByClassName("link-creator").length > 0) {
document.getElementsByClassName("link-creator")[0].remove();
}
clearSelections();
// Prevent defualt behavior of most keys (alpha-numerical, delete/backspace, undo/redo, styling keys):
if ((!e.ctrlKey && e.key.length === 1) || (e.keyCode === 8 || e.keyCode === 46 || e.keyCode === 13) || (e.ctrlKey && (e.keyCode === 90 || e.keyCode === 89 || e.keyCode === 66 || e.keyCode === 73 || e.keyCode === 85 || e.keyCode === 83 || e.keyCode === 75)))
e.preventDefault();
let caretPos = getCaretPosition(this);
let key;
// Handle enter:
if (e.keyCode === 13)
key = "\n";
// Handle backspace / delete:
if (e.keyCode === 8 && caretPos.end > 0 || e.keyCode === 46 && caretPos.end < this.textContent.length - 1) {
// No selection:
if (caretPos.start === caretPos.end) {
// Handle normal backspace / delete:
if (!e.ctrlKey) {
// Update active styles:
activeStyles = (this.childNodes[caretPos.start - (e.keyCode === 8 ? 1 : 0)] && this.childNodes[caretPos.start - (e.keyCode === 8 ? 1 : 0)].classList) ? [...this.childNodes[caretPos.start - (e.keyCode === 8 ? 1 : 0)].classList].filter(cl => (cl.indexOf("cursor") === -1 && cl.indexOf("link") === -1 && cl.indexOf("selected") === -1)) : [];
setButtons();
buffer({
vertex: "editor",
action: "delete",
contentPre: this.textContent[caretPos.start - (e.keyCode === 8 ? 1 : 0)],
index: {
start: caretPos.start - (e.keyCode === 8 ? 1 : 0),
end: caretPos.start - (e.keyCode === 8 ? 1 : 0)
},
surrounding: {
before: this.textContent[caretPos.start - 1 - (e.keyCode === 8 ? 1 : 0)] || false,
after: ((caretPos.start + (e.keyCode === 46 ? 1 : 0)) === this.textContent.length - 1 && this.textContent[caretPos.start + (e.keyCode === 46 ? 1 : 0)] === "\n") ? false : (this.textContent[caretPos.start + (e.keyCode === 46 ? 1 : 0)] || false)
}
});
lastKeyPress = getTime();
attemptToPushChanges(lastKeyPress);
setText(this, "", { start: caretPos.start - (e.keyCode === 8 ? 1 : 0), end: caretPos.end + (e.keyCode === 46 ? 1 : 0) });
// Handle Ctrl + Backspace / Delete:
} else {
// Determine what index to delete up to:
let breakCharacters = " `~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?\n".split("");
let initialIndex = caretPos.start + (this.textContent[caretPos.start + (e.keyCode === 8 ? -1 : 0)] === " " ? (e.keyCode === 8 ? -2 : 2) : (e.keyCode === 8 ? -1 : 1));
let i = initialIndex;
while (i > 0 && i < this.textContent.length - 1 && (breakCharacters.indexOf(this.textContent[i + (e.keyCode === 8 ? -1 : 0)]) === -1 && breakCharacters.indexOf(this.textContent[i + (e.keyCode === 8 ? 0 : -1)]) === -1 || breakCharacters.indexOf(this.textContent[i + (e.keyCode === 8 ? 0 : -1)]) !== -1 && breakCharacters.indexOf(this.textContent[i + (e.keyCode === 8 ? -1 : 0)]) !== -1)) {
i += (e.keyCode === 8 ? -1 : 1);
}
// Update active styles:
activeStyles = (this.childNodes[i] && this.childNodes[i].classList) ? [...this.childNodes[i].classList].filter(cl => (cl.indexOf("cursor") === -1 && cl.indexOf("link") === -1 && cl.indexOf("selected") === -1)) : [];
setButtons();
let start = Math.min(caretPos.start, i);
let end = Math.max(caretPos.start, i);
buffer({
vertex: "editor",
action: "replace",
contentPre: this.textContent.substring(start, end),
content: "",
index: {
start: start,
end: end
},
surrounding: {
before: this.textContent[start - 1] || false,
after: (end === this.textContent.length - 1 && this.textContent[end] === "\n") ? false : (this.textContent[end] || false)
}
});
lastKeyPress = getTime();
attemptToPushChanges(lastKeyPress);
setText(this, "", { start: start, end: end });
}
// Selection:
} else {
// Update active styles:
activeStyles = (this.childNodes[caretPos.start] && this.childNodes[caretPos.start].classList) ? [...this.childNodes[caretPos.start].classList].filter(cl => (cl.indexOf("cursor") === -1 && cl.indexOf("link") === -1 && cl.indexOf("selected") === -1)) : [];
setButtons();
buffer({
vertex: "editor",
action: "replace",
contentPre: this.textContent.substring(caretPos.start, caretPos.end),
content: "",
index: {
start: caretPos.start,
end: caretPos.end
},
surrounding: {
before: this.textContent[caretPos.start - 1] || false,
after: (caretPos.end === this.textContent.length - 1 && this.textContent[caretPos.end] === "\n") ? false : (this.textContent[caretPos.end] || false)
}
});
lastKeyPress = getTime();
attemptToPushChanges(lastKeyPress);
setText(this, "", caretPos);
}
}
// Handle undo/redo:
// Ctrl + Z (Undo):
if (e.ctrlKey && !e.shiftKey && e.keyCode === 90 && stack.undo.length > 0) {
execUndo();
}
// Ctrl + Shift + Z or Ctrl + Y (Redo):
if ((e.ctrlKey && e.shiftKey && e.keyCode === 90 || e.ctrlKey && e.keyCode === 89) && stack.redo.length > 0) {
execRedo();
}
// Handle styling keys and link keys:
// Ctrl + B (Bold):
if (e.ctrlKey && !e.shiftKey && e.keyCode === 66) {
// No text is selected:
if (caretPos.start === caretPos.end) {
if (activeStyles.indexOf("bold") === -1) {
activeStyles.push("bold");
} else {
activeStyles.splice(activeStyles.indexOf("bold"), 1);
}
setButtons();
// Text is selected:
} else {
applyStyle(document.getElementById("editor"), "bold");
}
}
// Ctrl + I (Italic):
if (e.ctrlKey && !e.shiftKey && e.keyCode === 73) {
// No text is selected:
if (caretPos.start === caretPos.end) {
if (activeStyles.indexOf("italic") === -1) {
activeStyles.push("italic");
} else {
activeStyles.splice(activeStyles.indexOf("italic"), 1);
}
setButtons();
// Text is selected:
} else {
applyStyle(document.getElementById("editor"), "italic");
}
}
// Ctrl + U (Underline):
if (e.ctrlKey && !e.shiftKey && e.keyCode === 85) {
// No text is selected:
if (caretPos.start === caretPos.end) {
if (activeStyles.indexOf("underline") === -1) {
activeStyles.push("underline");
} else {
activeStyles.splice(activeStyles.indexOf("underline"), 1);
}
setButtons();
// Text is selected:
} else {
applyStyle(document.getElementById("editor"), "underline");
}
}
// Ctrl + S (Strikethrough):
if (e.ctrlKey && !e.shiftKey && e.keyCode === 83) {
// No text is selected:
if (caretPos.start === caretPos.end) {
if (activeStyles.indexOf("strikethrough") === -1) {
activeStyles.push("strikethrough");
} else {
activeStyles.splice(activeStyles.indexOf("strikethrough"), 1);
}
setButtons();
// Text is selected:
} else {
applyStyle(document.getElementById("editor"), "strikethrough");
}
}
// Ctrl + K (Link):
if (e.ctrlKey && !e.shiftKey && e.keyCode === 75) {
if (caretPos.start !== caretPos.end) {
createLink(this);
}
}
// If we aren't dealing with a normal key, return now:
if (e.keyCode !== 13 && (e.ctrlKey || e.altKey || e.key.length > 1))
return;
// Handle typing/selecting text and typing:
if (caretPos.start === caretPos.end) {
buffer({
vertex: "editor",
action: "type",
content: key || e.key,
index: {
start: caretPos.end,
end: caretPos.end
},
surrounding: {
before: this.textContent[caretPos.end - 1] || false, // The first part of this conditional is to ignore the last "\n" that HTML sometimes autofills (for whatever reason):
after: (caretPos.end === this.textContent.length - 1 && this.textContent[caretPos.end] === "\n") ? false : (this.textContent[caretPos.end] || false)
}
});
lastKeyPress = getTime();
attemptToPushChanges(lastKeyPress);
} else {
buffer({
vertex: "editor",
action: "replace",
contentPre: this.textContent.substring(caretPos.start, caretPos.end),
content: key || e.key,
index: {
start: caretPos.start,
end: caretPos.end
},
surrounding: {
before: this.textContent[caretPos.start - 1] || false,
after: (caretPos.end === this.textContent.length - 1 && this.textContent[caretPos.end] === "\n") ? false : (this.textContent[caretPos.end] || false)
}
});
lastKeyPress = getTime();
attemptToPushChanges(lastKeyPress);
}
setText(this, key || e.key, caretPos);
});
document.getElementById("editor").addEventListener("input", function(e) {
// Update cursor position in Firebase (after event finishes):
setTimeout(function() {
set(ref(db, `users/${uid}/cursor`), getCaretPosition(document.getElementById("editor")));
}, 0);
// Input was due to a recursive call from insertFromDrop, insertReplacementText, or insertCompositionText and should be ignored:
if (Math.abs(lastInputTimeStamp - e.timeStamp) <= 1000 || lastInputTimeStamp === Infinity) {
return;
}
// Prevent undo/redo from the context menu (since the custom stack should be used instead):
if (e.inputType === "historyUndo") {
// Delete the undo:
let caretPos = getCaretPosition(this);
setText(this, "", caretPos);
// Then alert the user to use "Ctrl + Z" instead:
alert("Undo from the context menu is not supported.\n\nPlease use \"Ctrl + Z\" instead.");
return;
}
if (e.inputType === "historyRedo") {
// Undo the redo:
lastInputTimeStamp = e.timeStamp;
document.execCommand("undo");
// Then alert the user to use "Ctrl + Y" instead:
alert("Redo from the context menu is not supported.\n\nPlease use \"Ctrl + Y\" instead.");
return;
}
// Handle dropped text:
if (e.inputType === "insertFromDrop") {
// Perform the insertion (since the dropped text is selected after the insertion):
let insertCaretPos = getCaretPosition(this);
buffer({
vertex: "editor",
action: "insert",
content: this.textContent.substring(insertCaretPos.start, insertCaretPos.end),
index: {
start: insertCaretPos.start,
end: insertCaretPos.start
},
surrounding: {
before: this.textContent[insertCaretPos.start - 1] || false,
after: (insertCaretPos.end === this.textContent.length - 1 && this.textContent[insertCaretPos.end] === "\n") ? false : (this.textContent[insertCaretPos.end] || false)
}
});
setText(this, this.textContent.substring(insertCaretPos.start, insertCaretPos.end), { start: insertCaretPos.start, end: insertCaretPos.start });
// Then undo the insertion:
lastInputTimeStamp = e.timeStamp;
document.execCommand("undo");
// Then remove where the text originated from (since the original text is selected after the undo):
let preCaretPos = getCaretPosition(this);
if (this.textContent.substring(preCaretPos.start, preCaretPos.end).length > 0) {
buffer({
vertex: "editor",
action: "replace",
contentPre: this.textContent.substring(preCaretPos.start, preCaretPos.end),
content: "",
index: {
start: preCaretPos.start,
end: preCaretPos.end
},
surrounding: {
before: this.textContent[preCaretPos.start - 1] || false,
after: (preCaretPos.end === this.textContent.length - 1 && this.textContent[preCaretPos.end] === "\n") ? false : (this.textContent[preCaretPos.end] || false)
}
});
setText(this, "", preCaretPos, true);
}
setCaretPosition(this, { start: insertCaretPos.end, end: insertCaretPos.end });
lastKeyPress = getTime();
attemptToPushChanges(lastKeyPress);
return;
}
// Handle spelling corrections:
if (e.inputType === "insertReplacementText") {
// Start by undoing the spelling correction (to determine the original text):
lastInputTimeStamp = e.timeStamp;
document.execCommand("undo");
// The original text is now selected:
let preCaretPos = getCaretPosition(this);
let contentPre = this.textContent.substring(preCaretPos.start, preCaretPos.end);
let classes = (this.childNodes[preCaretPos.start] && this.childNodes[preCaretPos.start].classList) ? [...this.childNodes[preCaretPos.start].classList].filter(cl => (cl.indexOf("cursor") === -1 && cl.indexOf("link") === -1 && cl.indexOf("selected") === -1)) : [];
// Then, redo the spelling correction (to determine the new text):
lastInputTimeStamp = e.timeStamp;
document.execCommand("redo");
// The cursor will always be placed after the end of the spelling correction; we know where the spelling correction starts because the spelling correction is always inserted starting at the beginning of the previous selection:
let postCaretPos = { start: preCaretPos.start, end: getCaretPosition(this).end }; // Note that since the spelling correction is stored in just one element, the end node is really the start + 1
let content = this.textContent.substring(postCaretPos.start, postCaretPos.end);
buffer({
vertex: "editor",
action: "replace",
contentPre: contentPre,
content: content,
index: {
start: preCaretPos.start,
end: preCaretPos.end
},
surrounding: {
before: this.textContent[preCaretPos.start - 1] || false,
after: (postCaretPos.end === this.textContent.length - 1 && this.textContent[postCaretPos.end] === "\n") ? false : (this.textContent[postCaretPos.end] || false)
}
});
setText(this, content, { start: preCaretPos.start, end: preCaretPos.start + 1 }, false, classes);
lastKeyPress = getTime();
attemptToPushChanges(lastKeyPress);
return;
}
// Handle emojis:
if (e.inputType === "insertCompositionText") {
lastInputTimeStamp = Infinity;
// Alert the user that this is not supported:
alert("Inserting emojis from the context menu is not supported.\n\nPlease copy and paste the emojis in using \"Ctrl + C\" (copy) and \"Ctrl + V\" (paste) instead.");
// Disconnect the user:
remove(ref(db, `users/${uid}`));
return;
}
});
document.getElementById("editor").addEventListener("paste", function(e) {
// Update cursor position in Firebase (after event finishes):
setTimeout(function() {
set(ref(db, `users/${uid}/cursor`), getCaretPosition(document.getElementById("editor")));
}, 0);
let caretPos = getCaretPosition(this);
// Clean pasted text:
e.preventDefault();
let textToPaste = (e.clipboardData.getData("text/plain")).split("\r\n").join("\n");
// Push pasted text:
if (caretPos.start === caretPos.end) {
buffer({
vertex: "editor",
action: "insert",
content: textToPaste,
index: {
start: caretPos.end,
end: caretPos.end
},
surrounding: {
before: this.textContent[caretPos.end - 1] || false,
after: (caretPos.end === this.textContent.length - 1 && this.textContent[caretPos.end] === "\n") ? false : (this.textContent[caretPos.end] || false)
}
});
lastKeyPress = getTime();
attemptToPushChanges(lastKeyPress);
} else {
buffer({
vertex: "editor",
action: "replace",
contentPre: this.textContent.substring(caretPos.start, caretPos.end),
content: textToPaste,
index: {
start: caretPos.start,
end: caretPos.end
},
surrounding: {
before: this.textContent[caretPos.start - 1] || false,
after: (caretPos.end === this.textContent.length - 1 && this.textContent[caretPos.end] === "\n") ? false : (this.textContent[caretPos.end] || false)
}
});
lastKeyPress = getTime();
attemptToPushChanges(lastKeyPress);
}
// Insert the text:
setText(this, textToPaste, caretPos);
});
document.getElementById("editor").addEventListener("cut", function(e) {
// Update cursor position in Firebase (after event finishes):
setTimeout(function() {
set(ref(db, `users/${uid}/cursor`), getCaretPosition(document.getElementById("editor")));
}, 0);
let caretPos = getCaretPosition(this);
// Push removed text:
if (caretPos.start === caretPos.end)
return;
buffer({
vertex: "editor",
action: "replace",
contentPre: this.textContent.substring(caretPos.start, caretPos.end),
content: "",
index: {
start: caretPos.start,
end: caretPos.end
},
surrounding: {
before: this.textContent[caretPos.start - 1] || false,
after: (caretPos.end === this.textContent.length - 1 && this.textContent[caretPos.end] === "\n") ? false : (this.textContent[caretPos.end] || false)
}
});
lastKeyPress = getTime();
attemptToPushChanges(lastKeyPress);
});
document.getElementById("editor").addEventListener("focus", function(e) {
// Set this to be the active vertex:
activeVertex = "editor";
setTimeout(function() {
set(ref(db, `users/${uid}/cursor`), getCaretPosition(this));
set(ref(db, `users/${uid}/vertex`), "editor");
set(ref(db, `users/${uid}/changed`), getTime());
set(ref(db, `users/${uid}/status`), "active");
}, 0);
});
document.getElementById("editor").addEventListener("blur", function(e) {