-
Notifications
You must be signed in to change notification settings - Fork 4
/
server-elm-script.js
5750 lines (5491 loc) · 279 KB
/
server-elm-script.js
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
editor = typeof editor == "undefined" ? {} : editor;
(function(editor) {
// Default configuration.
editor.config = typeof editor.config == "undefined" ? {} : editor.config;
editor.config = {
EDITOR_VERSION: 1,
path: location.pathname,
varedit: location.search.match(/(^\?|&)edit(?:=true)?(&|$)/),
varls: location.search.match(/(^\?|&)ls(?:=true)?(&|$)/),
askQuestions: location.search.match(/(^\?|&)question(?:=true)?(&|$)/),
autosave: location.search.match(/(^\?|&)autosave(?:=true)?(&|$)/),
canEditPage: false,
editIsFalseButDefaultIsTrue : false,
thaditor: false,
userName: typeof userName === "string" ? userName : "anonymous",
...editor.config};
var mbEditQ = editor.config.fast ? "" : "?edit&fast=false";
var mbEditA = editor.config.fast ? "" : "&edit&fast=false";
var _internals = {};
editor._internals = _internals;
// function(Time in ms, key, callback)
// If the time elapses, calls the callback. Reset the timer every time the same callback is called, thanks to the key.
editor._internals.ifIdleAfter = (() => {
let waiting = {};
return function(ms, key, callback) {
if(key in waiting) {
clearTimeout(waiting[key]);
}
waiting[key] = setTimeout(() => {
delete waiting[key];
callback();
}, ms);
}
})();
// Overwrite the entire document (head and body)
// I'm not sure there is a better way.
function writeDocument(NC) {
let {scrollX, scrollY} = window;
document.open();
document.write(NC);
document.close();
setTimeout(() => {
window.scrollTo(scrollX, scrollY);
}, 0)
}
_internals.writeDocument = writeDocument;
// Asynchronous if onOk is defined and readServer is defined. and asynchronous and returns result otherwise.
// Could be overriden so that Editor could work with a local file system, Git, or anything else.
_internals.doReadServer = function doReadServer(action, name, onOk, onErr) {
if (typeof thaditor != "undefined") { // apache_server, everything goes through thaditor
return thaditor._internals.readServer(action, name, onOk, onErr);
} else {
var request = new XMLHttpRequest();
var url = "/";
request.open('GET', url, false); // `false` makes the request synchronous
request.setRequestHeader("action", action);
request.setRequestHeader("name", name);
request.send(null);
if(request.status == 200) {
return request.responseText || "";
} else {
console.log("error while reading " + url, request);
return undefined;
}
}
};
// Returns a promise after performing a direct GET action on the server.
function getServer(action, name) {
return new Promise(function(resolve, reject) {
_internals.doReadServer(action, name, resolve, reject);
});
}
editor.getServer = getServer;
// Asynchronous if onOk is defined and writeServer is defined. and asynchronous and returns result otherwise.
function doWriteServer(action, name, content, onOk, onErr) {
if (typeof thaditor != "undefined") {
return thaditor._internals.writeServer(action, name, content, onOk, onErr);
} else {
var request = new XMLHttpRequest();
var url = "/";
request.open('POST', url, false); // `false` makes the request synchronous
request.setRequestHeader("action", action);
request.setRequestHeader("name", name);
request.send(content);
if(request.status == 200) {
return request.responseText;
} else if(request.status == 500) {
return request.responseText;
} else {
console.log("error while writing " + url, request);
return "";
}
}
}
_internals.doWriteServer = doWriteServer;
// Returns a promise after performing a direct POST action on the server.
function postServer(action, name, content) {
return new Promise(function(resolve, reject) {
_internals.doWriteServer(action, name, content, resolve, reject);
});
}
editor.postServer = postServer;
// Page reloading without trying to recover the editor's state.
function doReloadPage(url, replaceState) {
function finish(text, newLocalURL) {
writeDocument(text);
if(newLocalURL) {
window.history[replaceState ? "replaceState" : "pushState"]({localURL: newLocalURL}, "Nav. to " + newLocalURL, newLocalURL);
}
}
if(editor.config.thaditor) { // Ask the worker to recompute the page
thaditor.do({action:"sendRequest",
toSend: "{\"a\":1}",
loc: location.pathname + location.search,
requestHeaders: {reload: true, url: url},
what: undefined}).then(data => {
if (data.action == "confirmDone") {
finish(data.text, data.newLocalURL);
}
});
} else { // Ask Editor's web server to recompute the page.
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = (xmlhttp => () => {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
finish(xmlhttp.responseText, xmlhttp.getResponseHeader("New-Local-URL"));
}
})(xmlhttp);
xmlhttp.open("POST", location.pathname + location.search);
xmlhttp.setRequestHeader("reload", "true");
xmlhttp.setRequestHeader("url", url);
console.log("setting url to ", url);
xmlhttp.send("{\"a\":1}");
}
}
editor._internals.doReloadPage = doReloadPage;
// Uploads a file
// targetPathName: The path where to upload the file
// file: The file to upload (typically from a drop event or a input[type=file] change)
// onOk: Callback when upload is complete, with targetPathName and file
// onErr: callback if upload fails, with targetPathName and file
// onProgress: callback every progress made, with targetPathName, file and percentage
function uploadFile(targetPathName, file, onOk, onError, onProgress) {
if(editor.config.thaditor) {
thaditor.postServer("write", targetPathName, file, onProgress).then(() => {
if(onOk) onOk(targetPathName, file);
}).catch(() => {
if(onError) onError(targetPathName, file);
})
} else { // Editor webserver
var xhr = new XMLHttpRequest();
xhr.onprogress = (e) => {
if(onProgress) {
onProgress(targetPathName, file, e && (e.loaded * 100.0 / e.total) || 100)
}
}
xhr.onreadystatechange = ((xhr, file) => () => {
if (xhr.readyState == XMLHttpRequest.DONE) {
if (xhr.status == 200 || xhr.status == 201) {
onOk ? onOk(targetPathName, file) : 0;
} else {
console.log("Error while uploading picture or file", xhr);
onError ? onError(targetPathName, file) : 0;
}
}
})(xhr, file);
xhr.open("POST", targetPathName, false);
xhr.setRequestHeader("write-file", file.type);
xhr.send(file);
}
}
editor.uploadFile = uploadFile;
function pasteHtmlAtCaret(html) {
var sel, range;
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
// do not paste html into modify menu
if (sel.anchorNode.offsetParent && sel.anchorNode.offsetParent.id === "modify-menu") {
return;
}
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
// Range.createContextualFragment() would be useful here but is
// only relatively recently standardized and is not supported in
// some browsers (IE9, for one)
var div = document.createElement("div");
div.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while ( (node = div.firstChild) ) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
// Preserve the selection
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != "Control") {
// IE < 9
document.selection.createRange().pasteHTML(html);
}
}
editor.pasteHtmlAtCaret = pasteHtmlAtCaret;
// Given some files, uploads them and place them at cursor. Images are inserted as <img>, whereas other files just have the <a href=>)
function uploadFilesAtCursor(files) {
// files is a FileList of File objects. List some properties.
for (var i = 0, file; file = files[i]; i++) {
var targetPathName = editor.getStorageFolder(file) + file.name;
// if(file.size < 30000000)
editor.uploadFile(targetPathName, file, (targetPathName, file) => {
if(file.type.indexOf("image") == 0) {
editor.pasteHtmlAtCaret(`<img src="${targetPathName}" alt="${file.name}">`);
} else {
editor.pasteHtmlAtCaret(`<a href="${targetPathName}">${targetPathName}</a>`);
}
});
}
}
editor.uploadFilesAtCursor = uploadFilesAtCursor;
// Returns the storage folder that will prefix a file name on upload (initial slash excluded, final slash included)
editor.getStorageFolder = function(file) {
var storageOptions = document.querySelectorAll("meta[editor-storagefolder]");
for(let s of storageOptions) {
if(file.type.startsWith(s.getAttribute("file-type") || "")) {
let sf = storageOptions.getAttribute("editor-storagefolder") || "";
if(!sf.endsWith("/")) sf = sf + "/";
return sf;
}
}
let extension = "";
if(file && file.type.startsWith("image")) {
var otherImages = document.querySelectorAll("img[src]");
for(let i of otherImages) {
extension = (i.getAttribute("src") || "").replace(/[^\/]*$/, "");
break;
}
if(extension[0] == "/") { // Absolute URL
return extension;
}
}
if(extension != "" && extension[extension.length-1] != "/") {
extension = extension + "/";
}
// extension ends with a / or is empty
var tmp = location.pathname.split("/");
tmp = tmp.slice(0, tmp.length - 1);
storageFolder = tmp.join("/") + (extension != "" ? "/" + extension : "/");
return storageFolder;
}
editor.fs = {
listdir:
async function(dirname) {
return JSON.parse(await getServer("listdir", dirname) || "[]");
}
};
function getSelectorOf(clickedElem) {
let curSelector = clickedElem.tagName.toLowerCase();
if(curSelector === "html" || curSelector === "body" || curSelector === "head") return curSelector;
if(clickedElem.getAttribute("id")) {
curSelector += "#" + clickedElem.getAttribute("id");
}
if (clickedElem.getAttribute("class") && clickedElem.getAttribute("class") != "") {
curSelector += (" " + clickedElem.getAttribute("class").trim()).replace(/\s+/g, ".");
}
return curSelector;
}
function getBareSelectorOf(t) {
return t.nodeType === document.ELEMENT_NODE ? t.tagName.toLowerCase() : "/*" + t.nodeType + "*/";
}
// Given a node, computes a way to retrieve this node if the page was reloaded.
// That's a treasure map.
// TreasureMap.bareSelectorArray does not contain "~" and they'll need to be reinserted in case we use the selector as a CSS selector
editor.toTreasureMap = function toTreasureMap(oldNode, ancestorToStopAt) {
if(!oldNode) return undefined;
let foundParentWithId = false;
let tentativeSelector = [];
let bareSelectorArray = [];
let t = oldNode;
while(t) {
let bareSelector = getBareSelectorOf(t);
let extSelector = undefined;
if(!foundParentWithId && !bareSelector.startsWith("/*")) {
if(tentativeSelector.length) {
tentativeSelector.unshift(">");
}
extSelector = getSelectorOf(t);
tentativeSelector.unshift(extSelector); // We pile more information in the tentativeSelector to find the elemnt
}
if(bareSelectorArray.length) {
bareSelectorArray.unshift(">");
}
bareSelectorArray.unshift(bareSelector);
if(ancestorToStopAt == t || t == document.head.parentElement) break;
// Emulate :nth-of-type but for a class of siblings having the same selector.
let s = t.previousSibling;
foundParentWithId = foundParentWithId || t.nodeType === document.ELEMENT_NODE && t.hasAttribute("id");
let gotOneElementBefore = t.nodeType === document.ELEMENT_NODE;
while(s) {
let isSimilarSibling = typeof s.matches == "function" && t.nodeType === document.ELEMENT_NODE && s.matches(extSelector);
let selector = isSimilarSibling ? extSelector : getBareSelectorOf(s);
if(isSimilarSibling && !foundParentWithId) {
tentativeSelector.unshift(extSelector, "~");
} else if(s.nodeType != document.ELEMENT_NODE && !foundParentWithId) {
tentativeSelector.unshift(selector);
}
bareSelectorArray.unshift(getBareSelectorOf(s));
gotOneElementBefore = gotOneElementBefore || s.nodeType === document.ELEMENT_NODE;
s = s.previousSibling;
}
t = t.parentElement;
}
return {tentativeSelector: tentativeSelector, bareSelectorArray: bareSelectorArray};
}
// Given a tentative selector and the element to start from, returns the precise element designated by this selector if it exists.
function queryBareSelector(bareSelectorArray, fromElement) {
var i = 0;
var n = bareSelectorArray.length;
while(fromElement && i < n) {
let selector = bareSelectorArray[i];
let m = selector.match(/\/\*(\d+)\*\//);
// In case there is no match with the expected selector, let's try to go further.
while(fromElement && !(!m && fromElement.matches && fromElement.matches(selector) || m && Number(m[1]) == fromElement.nodeType)) {
fromElement = fromElement.nextSibling;
}
if(fromElement) {
i++;
if(i >= n) {
return fromElement;
} else if(bareSelectorArray[i] == ">") {
fromElement = fromElement.firstChild;
i++;
} else {
fromElement = fromElement.nextSibling;
}
} else {
return null;
}
}
return null;
}
editor._internals.queryBareSelector = queryBareSelector;
// Returns the new node that matches the old node the closest.
// For text nodes, try to recover the text node, if not, returns the parent node;
editor.fromTreasureMap = function(data, source) {
if(!data) return undefined;
if(typeof data === "object" && data.id) {
return document.getElementById(data.id);
}
if(typeof data == "object" && Array.isArray(data.tentativeSelector)) {
let tentativeSelector = [...data.tentativeSelector];
let result = queryBareSelector(data.bareSelectorArray, source || document.head.parentElement);
if(result) {
return result;
}
// Fallback, we try to reduce the tentative selector until we find the node.
while(tentativeSelector.length >= 1) {
if(tentativeSelector[0] !== "~" && tentativeSelector[0] !== ">") {
let result = document.querySelector(tentativeSelector.join(" "));
if(result) {
let x = tentativeSelector.length - 1;
while(result && tentativeSelector[x].match(/\/\*(\d+)\*\//)) {
result = result.previousSibling;
x--;
}
return result;
}
}
tentativeSelector.shift();
}
return undefined;
}
}
// Helper to create an element with attributes, children and properties
function el(tag, attributes, children, properties) {
let tagClassIds = tag.split(/(?=#|\.)/g);
let x;
for(let attr of tagClassIds) {
if(x && attr.startsWith(".")) {
x.classList.toggle(attr.substring(1), true);
} else if(x && attr.startsWith("#")) {
x.setAttribute("id", attr.substring(1));
} else if(!x) {
x = document.createElement(attr);
}
}
if(typeof attributes == "object") {
for(let k in attributes) {
let v = attributes[k];
if(typeof v != "undefined") {
x.setAttribute(k, v);
}
}
}
if(Array.isArray(children)) {
for(let child of children) {
if(typeof child === "string") {
x.append(child)
} else if(typeof child !== "undefined")
x.appendChild(child);
}
} else if(typeof children !== "undefined") {
x.append(children);
}
if(typeof properties == "object") {
for(let k in properties) {
x[k] = properties[k];
}
}
return x;
}
editor.el = el;
// Returns true if the element matches the selector
// Equivalent curried call: editor.matches(selector)(elem)
editor.matches = function(elem, selector) {
if(typeof selector == "undefined") { // Then selector is in the elem variable
return (selector => function(elem) {
return editor.matches(elem, selector);
})(elem);
}
if(elem && elem.matches) {
try {
return elem.matches(selector);
} catch(e) {
console.log("error while matching selector " + selector, e);
return false;
}
}
return false;
}
// An array of (node => {innerHTML, attributes, properties}) that can be defined by plug-ins.
editor.customContextMenuButtons = [];
// Creates an SVG icon from the given path. If fill is true, will have the path filled.
function svgFromPath(path, fill, width, height, viewBox) {
return `<svg class="context-menu-icon${fill ? " fill": ""}"
width="${width ? width : 40}" height="${height ? height : 30}"
${viewBox ? "viewBox=\"" + viewBox[0] + " "+ viewBox[1] + " "+ viewBox[2] + " "+ viewBox[3] +"\"" : "viewBox=\"0 0 40 30\""}>
<path d="${path}"></path></svg>`
}
editor.svgFromPath = svgFromPath;
/***************************
* Ghost & ignored API
****************************/
// Returns true if this element is marked as ghost
function isGhostNode(elem) {
return elem && (elem.isghost || (elem.nodeType == 1 &&
(elem.tagName == "GHOST" || elem.getAttribute("isghost") == "true")));
}
editor.isGhostNode = isGhostNode;
// Returns the child's index among its parent, not counting ghost nodes.
function childToInsertionIndex(parent, element) {
while(isGhostNode(element)) {
element = element.nextSibling;
}
var i = 0;
var tmp = parent.firstChild;
while(tmp) {
if(!isGhostNode(tmp)) {
if(tmp === element) {
return i;
}
i += 1;
}
tmp = tmp.nextSibling;
}
return i;
}
// Returns the child associated to the index, not counting ghost nodes.
function insertionIndexToChild(parent, index) {
var tmp = parent.firstChild;
while(index != 0) {
if(!isGhostNode(tmp)) {
index--;
}
tmp = tmp.nextSibling;
}
return tmp;
}
// Returns true if all children of this elements are marked as ghosts
function areChildrenGhosts(n) {
return n && n.getAttribute && (
n.getAttribute("children-are-ghosts") == "true" ||
n.getAttribute("children-are-ghost") == "true"
) ||
editor.ghostChildNodes.find(f => f(n));
}
editor.areChildrenGhosts = areChildrenGhosts;
// Returns true if this element has a node which implicitly marks it as a ghost
function hasGhostAncestor(htmlElem) {
if(htmlElem == null) return false;
if(isGhostNode(htmlElem)) return true;
return areChildrenGhosts(htmlElem.parentNode) ||
/*(htmlElem.parentNode == null && htmlElem.nodeType !== document.DOCUMENT_NODE) || */hasGhostAncestor(htmlElem.parentNode);
}
editor.hasGhostAncestor = hasGhostAncestor;
function isGhostAttributeKey(name) {
return name.startsWith("ghost-");
}
editor.isGhostAttributeKey = isGhostAttributeKey;
// Array of functions on nodes returning an array of attributes that should be ghosts (i.e. removed on back-propagation)
editor.ghostAttrs = [];
editor.ghostAttrs.push(n =>
((n && n.getAttribute && n.getAttribute("list-ghost-attributes")) || "").split(" ").concat(
((n && n.getAttribute && n.getAttribute("save-ghost-attributes")) || "").split(" ")).filter(a => a != "")
);
// attribute of some chrome extensions
editor.ghostAttrs.push(n => ["bis_skin_checked"]);
// Array of functions on nodes returning an array of predicates such that if one is true, the children of this element will be ignored (i.e. their old value is always returned on back-propagation)
editor.ignoredChildNodes = [];
// Returns truesy if the element n is ignoring child nodes.
function isIgnoringChildNodes(n) {
return editor.ignoredChildNodes.find(f => f(n));
}
editor.isIgnoringChildNodes = isIgnoringChildNodes;
// Assuming that n is ignoring children, stores the encoding of the original children
function storeIgnoredChildNodes(n) {
let res = [];
for(let k = 0; k < n.childNodes.length; k++) {
res.push(domNodeToNativeValue(n.childNodes[k]));
}
// Let's store this element's array of children
n.__editor__ = n.__editor__ || {};
n.__editor__.ignoredChildNodes = res;
}
editor.storeIgnoredChildNodes = storeIgnoredChildNodes;
// Return true if this htmlElem is inside an element that ignores its children.
function hasIgnoringAncestor(htmlElem) {
if(htmlElem == null) return false;
return isIgnoringChildNodes(htmlElem.parentNode) || hasIgnoringAncestor(htmlElem.parentNode);
}
editor.hasIgnoringAncestor = hasIgnoringAncestor;
// Array of functions on nodes returning an array of attributes that should be ignored (i.e. old value returned on back-propagation)
editor.ignoredAttrs = [];
editor.ignoredAttrs.push(n =>
((n && n.getAttribute && n.getAttribute("list-ignored-attributes")) || "").split(" ").concat(
((n && n.getAttribute && n.getAttribute("save-ignored-attributes")) || "").split(" ")).filter(a => a != "")
);
editor.ignoredAttrs.push(n => editor.matches(n, "body") ? ["contenteditable", "data-gr-c-s-loaded"] : []);
editor.ignoredAttrs.push(n => editor.matches(n, "html") ? ["class"] : []);
// Returns a method that, for each key name, return true if it is a ghost attribute for the node
function isSpecificGhostAttributeKeyFromNode(n) {
var additionalGhostAttributes = [];
for(let k = 0; k < editor.ghostAttrs.length; k++) {
additionalGhostAttributes = additionalGhostAttributes.concat(editor.ghostAttrs[k](n))
}
return (a => name => a.indexOf(name) != -1)(additionalGhostAttributes);
}
editor.isSpecificGhostAttributeKeyFromNode = isSpecificGhostAttributeKeyFromNode;
// Returns a method that, for each key name, return true if it is an ignored attribute for the node
function isIgnoredAttributeKeyFromNode(n) {
var additionalIgnoredAttributes = [];
for(var k = 0; k < editor.ignoredAttrs.length; k++) {
additionalIgnoredAttributes = additionalIgnoredAttributes.concat(editor.ignoredAttrs[k](n))
}
return ((a, n) => (name, oldValue) => {
let result = a.indexOf(name) != -1;
if(result) { // let's store the previous attribute's value, even if it did not exist.
n.__editor__ = n.__editor__ || {};
n.__editor__.ignoredAttrMap = n.__editor__.ignoredAttrMap || {};
if(!(name in n.__editor__.ignoredAttrMap)) {
n.__editor__.ignoredAttrMap[name] = oldValue;
}
}
return result;
})(additionalIgnoredAttributes, n);
}
editor.isIgnoredAttributeKeyFromNode = isIgnoredAttributeKeyFromNode;
function ignoredAttributeValue(n, name) {
let result = n.__editor__.ignoredAttrMap[name];
if(name in n.__editor__.ignoredAttrMap) {
return result;
}
return n.getAttribute(name);
}
// Array of predicates that, if they return true on a node, Editor will mark this node as ghost.
editor.ghostNodes = [];
// Array of predicates that, if they return true on a node, Editor will mark all the children of this node as ghosts
editor.ghostChildNodes = [];
// Analytics scripts
editor.ghostNodes.push(insertedNode =>
editor.matches(insertedNode, "script[src]") &&
(insertedNode.getAttribute("src").indexOf("google-analytics.com/analytics.js") != -1 ||
insertedNode.getAttribute("src").indexOf("google-analytics.com/gtm/js") != -1 ||
insertedNode.getAttribute("src").indexOf("googletagmanager.com/gtm.js") != -1)
);
// For for ace styles in header
editor.ghostNodes.push(insertedNode => {
if(insertedNode.tagName == "STYLE" && typeof insertedNode.getAttribute("id") == "string" &&
(insertedNode.getAttribute("id").startsWith("ace-") ||
insertedNode.getAttribute("id").startsWith("ace_"))) {
insertedNode.setAttribute("save-ghost", "true");
return true;
} else {
return false;
}
}
);
// For Google sign-in buttons and i-frames
editor.ghostNodes.push(
editor.matches("div.abcRioButton, iframe#ssIFrame_google")
);
// For anonymous styles inside HEAD (e.g. ace css themes and google sign-in)
editor.ghostNodes.push(insertedNode =>
insertedNode.tagName == "STYLE" && insertedNode.getAttribute("id") == null && insertedNode.attributes.length == 0 &&
insertedNode.parentElement.tagName == "HEAD" && typeof insertedNode.isghost === "undefined"&& insertedNode.textContent.match("error_widget\\.ace_warning")
&& (insertedNode.setAttribute("save-ghost", "true") || true)
);
// For ace script for syntax highlight
editor.ghostNodes.push(insertedNode =>
editor.matches(insertedNode, "script[src]") &&
insertedNode.getAttribute("src").startsWith("https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.6/mode-j")
);
// For ace script for syntax highlight
editor.ghostNodes.push(insertedNode =>
insertedNode.tagName == "ACE_OUTER"
);
// For the grammarly extension
editor.ghostNodes.push(
editor.matches(".gr-top-z-index, .gr-top-zero")
);
function domNodeToNativeValue(n, postProcessing) {
let result;
if(n.nodeType == document.TEXT_NODE) {
result = ["TEXT", n.textContent];
} else if(n.nodeType == document.COMMENT_NODE) {
result = ["COMMENT", n.textContent];
} else if(n.nodeType === document.DOCUMENT_TYPE_NODE) {
result = ["!DOCTYPE", n.name, n.publicId ? n.publicId : "", n.systemId ? n.systemId : ""];
} else {
var attributes = [];
var tagName = n.nodeType === document.DOCUMENT_NODE ? "#document" : n.tagName.toLowerCase();
if(n.nodeType == 1) {
var isSpecificGhostAttributeKey = isSpecificGhostAttributeKeyFromNode(n);
var isIgnoredAttributeKey = isIgnoredAttributeKeyFromNode(n); // TODO recover ignored value
for(var i = 0; i < n.attributes.length; i++) {
var key = n.attributes[i].name;
var ignored = isIgnoredAttributeKey(key);
if(!isGhostAttributeKey(key) && !isSpecificGhostAttributeKey(key) || ignored) {
var value = ignored ? ignoredAttributeValue(n, key) : n.attributes[i].value;
if(typeof value == "undefined") continue;
if(key == "style") {
value = value.split(";").map(x => x.split(":")).filter(x => x.length == 2)
}
attributes.push([key, value]);
}
}
}
var children = [];
if(n.__editor__ && n.__editor__.ignoredChildNodes) {
children = n.__editor__.ignoredChildNodes;
} else {
var childNodes = n.childNodes;
if(tagName.toLowerCase() === "noscript" && n.childNodes.length === 1 && n.childNodes[0].nodeType === 3) {
// We'll recover the associated HTML node
childNodes = el("div", {}, [], {innerHTML: n.childNodes[0].textContent, parentNode: n}).childNodes;
}
if(!areChildrenGhosts(n)) {
for(i = 0; i < childNodes.length; i++) {
if(!isGhostNode(childNodes[i])) {
children.push(domNodeToNativeValue(childNodes[i], postProcessing));
}
}
}
}
result = [tagName, attributes, children];
}
if(postProcessing) { result = postProcessing(result, n) || result }
return result;
}
editor.domNodeToNativeValue = domNodeToNativeValue;
// Returns the closest ancestor of the selection having the given tagName
function getElementArCaret(tagName) {
var node = document.getSelection().anchorNode;
var w = node != null && node.nodeType == 3 ? node.parentNode : node;
if(!tagName) return w;
while(w != null && w.tagName.toLowerCase() != tagName.toLowerCase()) {
w = w.parentNode;
}
return w;
}
editor.getElementArCaret = getElementArCaret;
// Removes all the text from a node (not the text nodes themselves)
function emptyTextContent(node) {
editor.userModifies();
if(node != null) {
if(node.nodeType == 3) {
node.textContent = "";
} else {
for(let i = 0; i < node.childNodes.length; i++) {
emptyTextContent(node.childNodes[i]);
}
}
}
return node;
}
editor.emptyTextContent = emptyTextContent;
// Duplicates a node. Returns the cloned element that has been inserted.
// options: {
// onBeforeInsert: callback to transform cloned element before it is inserted (identity by default)
// target: Node before which to place the duplicated node (original node by default)
// after: If true, place the cloned node after the target node. (false by default)
// ignoreText: if true, will not attempt to duplicate text / indentation. (false by default)
// }
function duplicate(node, options) {
editor.userModifies();
if(typeof options == "undefined") options = {}
if(typeof options.onBeforeInsert != "function") options.onBeforeInsert = e => e;
if(node != null && node.parentNode != null) {
var parentInsertion = options.target ? options.target.parentElement : node.parentElement;
var insertBeforeNode = options.after ? options.target ? options.target.nextSibling : node.nextSibling :
options.target ? options.target : node;
if(node.nextSibling != null && !options.target && !options.ignoreText) {
var next = node.nextSibling;
if(next.nodeType == 3 && next.nextSibling != null &&
next.nextSibling.tagName == node.tagName && (node.tagName == "TR" || node.tagName == "TH" || node.tagName == "LI" || node.tagName == "TD")) {
var textElement = next.cloneNode(true);
node.parentNode.insertBefore(textElement, options.after ? node.nextSibling : node);
if(options.after) {
insertBeforeNode = textElement.nextSibling;
} else {
insertBeforeNode = textElement
}
}
}
var duplicated = node.cloneNode(true);
function removeEditorAttributes(node) {
if(node.nodeType != 1) return;
let attrs = [...node.attributes];
for(var i = 0; i < attrs.length; i++) {
if(attrs[i].name.match(/^ghost-clicked$|^translate-id.*$/)) {
node.removeAttribute(attrs[i].name);
}
}
for(var i = 0; i < node.childNodes; i++) {
removeEditorAttributes(node.childNodes[i]);
}
}
removeEditorAttributes(duplicated);
var cloned = options.onBeforeInsert(duplicated);
parentInsertion.insertBefore(cloned, insertBeforeNode);
return cloned;
}
}
editor.duplicate = duplicate;
// Removes a node from the DOM
// Attempts to remove the associated text element in the case of table elements or list items unless options.ignoreText is true
function remove(node, options) {
editor.userModifies();
if(typeof options == "undefined") options = {}
if(node.previousSibling != null && !options.ignoreText) { // Remove whitespace as well
var next = node.nextSibling;
if(next.nodeType == 3 && next.nextSibling != null &&
next.nextSibling.tagName == node.tagName && (node.tagName == "TR" || node.tagName == "TH" || node.tagName == "LI" || node.tagName == "TD")) {
next.remove();
}
}
node.remove();
}
editor.remove = remove;
editor._internals.mutationCallbacks = {};
// TODO: In the future, only determine if the user was either using the interface, or modifying a selected element.
// And then mark the mutation as computer or user. No more ghosts.
editor._internals.mutationCallbacks.handleScriptInsertion =
// Mark nodes as ghost on insertion, if they are so.
function handleScriptInsertion(mutations) {
for(var i = 0; i < mutations.length; i++) {
// A mutation is a ghost if either
// -- The attribute starts with 'ghost-'
// -- It is the insertion of a node whose tag is "ghost" or that contains an attribute "isghost=true"
// -- It is the modification of a node or an attribute inside a ghost node.
var mutation = mutations[i];
if(editor.hasGhostAncestor(mutation.target) || editor.hasIgnoringAncestor(mutation.target)) continue;
if(mutation.type == "childList") {
for(var j = 0; j < mutation.addedNodes.length; j++) {
var insertedNode = mutation.addedNodes[j];
if(editor.hasGhostAncestor(insertedNode)) {
insertedNode.isghost = true;
} else {
if(typeof insertedNode.isghost === "undefined" && (insertedNode.nodeType == 1 && insertedNode.getAttribute("isghost") != "true" || insertedNode.nodeType == 3 && !insertedNode.isghost) && editor.ghostNodes.find(pred => pred(insertedNode, mutation))) {
if(insertedNode.nodeType == 1) insertedNode.setAttribute("isghost", "true");
insertedNode.isghost = true;
} else { // Record ignored attributes
if(insertedNode.nodeType == 1) {
var isIgnoredAttributeKey = editor.isIgnoredAttributeKeyFromNode(insertedNode);
for(var k = 0; k < insertedNode.attributes.length; k++) {
var attr = insertedNode.attributes[k];
isIgnoredAttributeKey(attr.name, attr.value);
}
}
}
}
}
}
}
}
editor.ui = typeof editor.ui == "object" ? editor.ui : { _internals: {}, model: undefined };
editor.ui._internals.getLosslessCssParser = new Promise((resolve, reject) => {
editor.ui._internals.setLosslessCssParser = x => { editor.ui.CSSparser = new x(); resolve(x) };
});
// Display an box to switch to edit mode.
// This is the only item available for UI even if edit=false
editor.ui._internals.switchEditBox =
function switchEditBox(toEdit) {
let prev = toEdit ? "=false" : "(=true|=?$|=?(?=&))",
next = toEdit ? "" : "=false",
icon = toEdit ? editor.svgFromPath("M 30.85,10.65 19.56,21.95 19.56,21.95 16.96,19.34 28.25,8.05 30.85,10.65 30.85,10.65 Z M 31.56,9.94 33.29,8.21 C 33.68,7.82 33.67,7.19 33.28,6.8 L 32.1,5.62 C 31.71,5.23 31.08,5.22 30.68,5.62 L 28.96,7.34 31.56,9.94 31.56,9.94 Z M 16.31,20.11 15.67,23.22 18.81,22.61 16.31,20.11 16.31,20.11 16.31,20.11 Z M 26.41,16.5 26.41,26.5 C 26.41,27.61 25.51,28.5 24.41,28.5 L 9.4,28.5 C 8.3,28.5 7.41,27.6 7.41,26.49 L 7.41,3.51 C 7.41,2.4 8.31,1.5 9.41,1.5 L 19.41,1.5 19.41,7.5 C 19.41,8.61 20.3,9.5 21.41,9.5 L 25.41,9.5 29.99,4.92 C 30.78,4.13 32.04,4.13 32.82,4.91 L 34,6.09 C 34.77,6.87 34.77,8.14 33.99,8.92 L 26.41,16.5 26.41,16.5 Z M 20.41,1.5 20.41,7.5 C 20.41,8.05 20.86,8.5 21.4,8.5 L 26.41,8.5 20.41,1.5 20.41,1.5 Z", true, 40, 40) : "x",
title = toEdit ? "Edit this page" : "Preview this page";
return el("div#editbox.editor-interface", {title: title}, [
el("style.editor-interface", {}, `
#editbox {
${toEdit ?
`position: fixed;
${editor.config.onMobile() ? "bottom" : "top"}: 0px;
right: 0px;
margin-${editor.config.onMobile() ? "bottom" : "top"}: 25px;
margin-right: 25px;
border-radius: 60px;
background: var(--context-button-color);
` :
`display: none`
}z-index: 2000000;
opacity: 1;
cursor: pointer;
}
#editbox svg.context-menu-icon.fill>path {
fill: #ffffff;
fill-rule: evenodd;
stroke: #FFFFFF;
stroke-width: 0px;
stroke-linecap: none;
-linejoin: miter;
stroke-opacity: 0;
}
#editbox:hover {
background: var(--context-button-color-hover)
}`),
el("div.editor-interface", {}, [], { innerHTML: icon })
], {
isghost: true,
onclick(event) {
if(!location.search.match(new RegExp("edit" + prev))) {
if(editor.ui.init) {
editor.config.canEditPage = true;
editor.ui.init();
document.body.setAttribute("contenteditable", "true");
document.querySelector("#editbox").remove();
if(typeof editor.config.onInit == "function") {
editor.config.onInit()
}
setTimeout(() => {
editor.ui._internals.restoreUndoRedo();
}, 100);
} else {
location.search = location.search.startsWith("?") ? location.search + "&" + "edit" + next : "?edit" + next
}
} else {
location.search = location.search.replace(new RegExp("edit" + prev, "g"), "edit" + next);
}
}
});
} // editor.ui._internals.switchEditBox
// Hook Editor's core to the web window, add event listeners.
editor.init = function() {
/*
Pretend loading a page using Editor's commands.
Does not attempt to load Editor's interface.
*/
window.onpopstate = function(e){
console.log("onpopstate", e);
if(e.state && e.state.localURL) {
editor._internals.doReloadPage(String(location), true);
} else {
editor._internals.doReloadPage(location.pathname + location.search, true);
}
};
var onCopy = function(event) {
const selection = document.getSelection();
if(selection.rangeCount && (!document.activeElement || (!document.activeElement.matches("#modify-menu *") && !document.activeElement.matches("textarea.ace_text-input") && !document.activeElement.matches("textarea, input")))) {
let range = selection.getRangeAt(0); // Let's put the correct stuff in the clipboardData.
let contents = range.cloneContents();
let newHtmlData = "";
for(let i = 0; i < contents.childNodes.length; i++) {
let n = contents.childNodes[i];
newHtmlData += n.nodeType == 1 ? n.outerHTML : el("div", {}, n.textContent).innerHTML;
}
let textContent = el("div", {}, [], {innerHTML: newHtmlData}).textContent;
event.clipboardData.setData('text/plain', textContent);
event.clipboardData.setData('text/html', newHtmlData);
event.preventDefault();
}
};
var onPaste = function(e) {
if(editor.userModifies && e.clipboardData.types.indexOf("text/html") >= 0 && (!document.activeElement || !document.activeElement.matches("#modify-menu *, textarea, input"))) {
e.preventDefault();
e.stopPropagation();
let content = e.clipboardData.getData("text/html").replace(/^\s*<html>\s*<body>\s*(<!--[^\-]*-->\s*)?|(\s*<!--[^\-]*-->)?\s*<\/body>\s*<\/html>\s*$/g, "");
pasteHtmlAtCaret(content);
return true;
}
};
var onDocLoad = function(event) {
document.body.addEventListener("copy", onCopy);
document.body.addEventListener("paste", onPaste, {capture: true});
if(typeof editor.config.canEditPage == "boolean" && !editor.config.canEditPage && !editor.config.varls) {
document.body.insertBefore(editor.ui._internals.switchEditBox(true), document.body.childNodes[0]);
}
if(!editor.config.thaditor && editor.config.editIsFalseButDefaultIsTrue) {
// Special case when ?edit=false but the default behavior is edit=true if nothing is set.
// Happens only in editor webserver.
// It continues to add edit=false to any clicked links.
document.onclick = function (e) {
var addEditEqualToUrl = function(href, what) {
if(href.indexOf("://") == -1) { // Instrument the relative link so that it is edit=true
if(href.indexOf("?") >= 0) {
if(href.endsWith("?")) {
href = href + "edit=" + what
} else {
href = href + "&edit=" + what
}
} else {
href = href + "?edit=" + what
}
}
return href;
}
e = e || window.event;
var node = e.target || e.srcElement;
while(node) {
if(node.tagName == "A" && node.getAttribute("href") && !node.onclick && !node.getAttribute("onclick")) {
var newLocation = addEditEqualToUrl(node.getAttribute("href"), "false");
console.log(newLocation);
window.location.href = newLocation;
e.stopPropagation();
return false;
} else {
node = node.parentNode;
}