-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Expand file tree
/
Copy pathace2_inner.ts
More file actions
3714 lines (3297 loc) · 129 KB
/
ace2_inner.ts
File metadata and controls
3714 lines (3297 loc) · 129 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
// @ts-nocheck
import {Builder} from "./Builder";
/**
* Copyright 2009 Google Inc.
* Copyright 2020 John McLear - The Etherpad Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
let documentAttributeManager;
import AttributeMap from './AttributeMap';
const browser = require('./vendors/browser');
import padutils from './pad_utils'
const Ace2Common = require('./ace2_common');
const $ = require('./rjquery').$;
import {characterRangeFollow, checkRep, cloneAText, compose, deserializeOps, filterAttribNumbers, inverse, isIdentity, makeAText, makeAttribution, mapAttribNumbers, moveOpsToNewPool, mutateAttributionLines, mutateTextLines, oldLen, opsFromAText, pack, splitAttributionLines} from './Changeset'
const isNodeText = Ace2Common.isNodeText;
const getAssoc = Ace2Common.getAssoc;
const setAssoc = Ace2Common.setAssoc;
const noop = Ace2Common.noop;
const hooks = require('./pluginfw/hooks');
import SkipList from "./skiplist";
import Scroll from './scroll'
import AttribPool from './AttributePool'
import {SmartOpAssembler} from "./SmartOpAssembler";
import Op from "./Op";
import {buildKeepRange, buildKeepToStartOfRange, buildRemoveRange} from './ChangesetUtils'
function Ace2Inner(editorInfo, cssManagers) {
const makeChangesetTracker = require('./changesettracker').makeChangesetTracker;
const colorutils = require('./colorutils').colorutils;
const makeContentCollector = require('./contentcollector').makeContentCollector;
const domline = require('./domline').domline;
const linestylefilter = require('./linestylefilter').linestylefilter;
const undoModule = require('./undomodule').undoModule;
const AttributeManager = require('./AttributeManager');
const DEBUG = false;
const THE_TAB = ' '; // 4
const MAX_LIST_LEVEL = 16;
const FORMATTING_STYLES = ['bold', 'italic', 'underline', 'strikethrough'];
const SELECT_BUTTON_CLASS = 'selected';
let thisAuthor = '';
let disposed = false;
const outerWin = document.getElementsByName("ace_outer")[0]
const targetDoc = outerWin.contentWindow.document.getElementsByName("ace_inner")[0].contentWindow.document
const targetBody = targetDoc.body
const focus = () => {
targetBody.focus();
};
const outerDoc = outerWin.contentWindow.document;
const sideDiv = outerDoc.getElementById('sidediv');
const lineMetricsDiv = outerDoc.getElementById('linemetricsdiv');
const sideDivInner = outerDoc.getElementById('sidedivinner');
const appendNewSideDivLine = () => {
const lineDiv = outerDoc.createElement('div');
sideDivInner.appendChild(lineDiv);
const lineSpan = outerDoc.createElement('span');
lineSpan.classList.add('line-number');
lineSpan.appendChild(outerDoc.createTextNode(sideDivInner.children.length));
lineDiv.appendChild(lineSpan);
};
appendNewSideDivLine();
const scroll = new Scroll(outerWin);
let outsideKeyDown = noop;
let outsideKeyPress = (e) => true;
let outsideNotifyDirty = noop;
/**
* Document representation.
*/
const rep = {
/**
* The contents of the document. Each entry in this skip list is an object representing a
* line (actually paragraph) of text. The line objects are created by createDomLineEntry().
*/
lines: new SkipList(),
/**
* Start of the selection. Represented as an array of two non-negative numbers that point to the
* first character of the selection: [zeroBasedLineNumber, zeroBasedColumnNumber]. Notes:
* - There is an implicit newline character (not actually stored) at the end of every line.
* Because of this, a selection that starts at the end of a line (column number equals the
* number of characters in the line, not including the implicit newline) is not equivalent
* to a selection that starts at the beginning of the next line. The same goes for the
* selection end.
* - If there are N lines, [N, 0] is valid for the start of the selection. [N, 0] indicates
* that the selection starts just after the implicit newline at the end of the document's
* last line (if the document has any lines). The same goes for the end of the selection.
* - If a line starts with a line marker, a selection that starts at the beginning of the line
* may start either immediately before (column = 0) or immediately after (column = 1) the
* line marker, and the two are considered to be semantically equivalent. For safety, all
* code should be written to accept either but only produce selections that start after the
* line marker (the column number should be 1, not 0, when there is a line marker). The same
* goes for the end of the selection.
*/
selStart: null,
/**
* End of the selection. Represented as an array of two non-negative numbers that point to the
* character just after the end of the selection: [zeroBasedLineNumber, zeroBasedColumnNumber].
* See the above notes for selStart.
*/
selEnd: null,
/**
* Whether the selection extends "backwards", so that the focus point (controlled with the arrow
* keys) is at the beginning. This is not supported in IE, though native IE selections have that
* behavior (which we try not to interfere with). Must be false if selection is collapsed!
*/
selFocusAtStart: false,
alltext: '',
alines: [],
apool: new AttribPool(),
};
// lines, alltext, alines, and DOM are set up in init()
if (undoModule.enabled) {
undoModule.apool = rep.apool;
}
let isEditable = true;
let doesWrap = true;
let hasLineNumbers = true;
let isStyled = true;
let console = (DEBUG && window.console);
if (!window.console) {
const names = [
'log',
'debug',
'info',
'warn',
'error',
'assert',
'dir',
'dirxml',
'group',
'groupEnd',
'time',
'timeEnd',
'count',
'trace',
'profile',
'profileEnd',
];
console = {};
for (const name of names) console[name] = noop;
}
const scheduler = window; // hack for opera required
const performDocumentReplaceRange = (start, end, newText) => {
if (start === undefined) start = rep.selStart;
if (end === undefined) end = rep.selEnd;
// start[0]: <--- start[1] --->CCCCCCCCCCC\n
// CCCCCCCCCCCCCCCCCCCC\n
// CCCC\n
// end[0]: <CCC end[1] CCC>-------\n
const builder = new Builder(rep.lines.totalWidth());
buildKeepToStartOfRange(rep, builder, start);
buildRemoveRange(rep, builder, start, end);
builder.insert(newText, [
['author', thisAuthor],
], rep.apool);
const cs = builder.toString();
performDocumentApplyChangeset(cs);
};
const changesetTracker = makeChangesetTracker(scheduler, rep.apool, {
withCallbacks: (operationName, f) => {
inCallStackIfNecessary(operationName, () => {
fastIncorp(1);
f(
{
setDocumentAttributedText: (atext) => {
setDocAText(atext);
},
applyChangesetToDocument: (changeset, preferInsertionAfterCaret) => {
const oldEventType = currentCallStack.editEvent.eventType;
currentCallStack.startNewEvent('nonundoable');
performDocumentApplyChangeset(changeset, preferInsertionAfterCaret);
currentCallStack.startNewEvent(oldEventType);
},
});
});
},
});
const authorInfos = {}; // presence of key determines if author is present in doc
const getAuthorInfos = () => authorInfos;
editorInfo.ace_getAuthorInfos = getAuthorInfos;
const setAuthorStyle = (author, info) => {
const authorSelector = getAuthorColorClassSelector(getAuthorClassName(author));
const authorStyleSet = hooks.callAll('aceSetAuthorStyle', {
dynamicCSS: cssManagers.inner,
outerDynamicCSS: cssManagers.outer,
parentDynamicCSS: cssManagers.parent,
info,
author,
authorSelector,
});
// Prevent default behaviour if any hook says so
if (authorStyleSet.some((it) => it)) {
return;
}
if (!info) {
cssManagers.inner.removeSelectorStyle(authorSelector);
cssManagers.parent.removeSelectorStyle(authorSelector);
} else if (info.bgcolor) {
let bgcolor = info.bgcolor;
if ((typeof info.fade) === 'number') {
bgcolor = fadeColor(bgcolor, info.fade);
}
// textColorFromBackgroundColor is WCAG-aware (issue #7377): it returns
// whichever of black/white produces the higher contrast against the
// author's bg, guaranteeing at least AA (4.5:1) for any sRGB colour.
const textColor =
colorutils.textColorFromBackgroundColor(bgcolor, window.clientVars.skinName);
const styles = [
cssManagers.inner.selectorStyle(authorSelector),
cssManagers.parent.selectorStyle(authorSelector),
];
for (const style of styles) {
style.backgroundColor = bgcolor;
style.color = textColor;
style['padding-top'] = '3px';
style['padding-bottom'] = '4px';
}
}
};
const setAuthorInfo = (author, info) => {
if (!author) return; // author ID not set for some reason
if ((typeof author) !== 'string') {
// Potentially caused by: https://github.com/ether/etherpad-lite/issues/2802");
throw new Error(`setAuthorInfo: author (${author}) is not a string`);
}
if (!info) {
delete authorInfos[author];
} else {
authorInfos[author] = info;
}
setAuthorStyle(author, info);
};
const getAuthorClassName = (author) => `author-${author.replace(/[^a-y0-9]/g, (c) => {
if (c === '.') return '-';
return `z${c.charCodeAt(0)}z`;
})}`;
const className2Author = (className) => {
if (className.substring(0, 7) === 'author-') {
return className.substring(7).replace(/[a-y0-9]+|-|z.+?z/g, (cc) => {
if (cc === '-') { return '.'; } else if (cc.charAt(0) === 'z') {
return String.fromCharCode(Number(cc.slice(1, -1)));
} else {
return cc;
}
});
}
return null;
};
const getAuthorColorClassSelector = (oneClassName) => `.authorColors .${oneClassName}`;
const fadeColor = (colorCSS, fadeFrac) => {
let color = colorutils.css2triple(colorCSS);
color = colorutils.blend(color, [1, 1, 1], fadeFrac);
return colorutils.triple2css(color);
};
editorInfo.ace_getRep = () => rep;
editorInfo.ace_getAuthor = () => thisAuthor;
const _nonScrollableEditEvents = {
applyChangesToBase: 1,
};
for (const eventType of hooks.callAll('aceRegisterNonScrollableEditEvents')) {
_nonScrollableEditEvents[eventType] = 1;
}
const isScrollableEditEvent = (eventType) => !_nonScrollableEditEvents[eventType];
let currentCallStack = null;
const inCallStack = (type, action) => {
if (disposed) return;
const newEditEvent = (eventType) => ({
eventType,
backset: null,
});
const submitOldEvent = (evt) => {
if (rep.selStart && rep.selEnd) {
const selStartChar = rep.lines.offsetOfIndex(rep.selStart[0]) + rep.selStart[1];
const selEndChar = rep.lines.offsetOfIndex(rep.selEnd[0]) + rep.selEnd[1];
evt.selStart = selStartChar;
evt.selEnd = selEndChar;
evt.selFocusAtStart = rep.selFocusAtStart;
}
if (undoModule.enabled) {
let undoWorked = false;
try {
if (isPadLoading(evt.eventType)) {
undoModule.clearHistory();
} else if (evt.eventType === 'nonundoable') {
if (evt.changeset) {
undoModule.reportExternalChange(evt.changeset);
}
} else {
undoModule.reportEvent(evt);
}
undoWorked = true;
} finally {
if (!undoWorked) {
undoModule.enabled = false; // for safety
}
}
}
};
const startNewEvent = (eventType, dontSubmitOld) => {
const oldEvent = currentCallStack.editEvent;
if (!dontSubmitOld) {
submitOldEvent(oldEvent);
}
currentCallStack.editEvent = newEditEvent(eventType);
return oldEvent;
};
currentCallStack = {
type,
docTextChanged: false,
selectionAffected: false,
userChangedSelection: false,
domClean: false,
isUserChange: false,
// is this a "user change" type of call-stack
repChanged: false,
editEvent: newEditEvent(type),
startNewEvent,
};
let cleanExit = false;
let result;
try {
result = action();
hooks.callAll('aceEditEvent', {
callstack: currentCallStack,
editorInfo,
rep,
documentAttributeManager,
});
cleanExit = true;
} finally {
const cs = currentCallStack;
if (cleanExit) {
submitOldEvent(cs.editEvent);
if (cs.domClean && cs.type !== 'setup') {
if (cs.selectionAffected) {
updateBrowserSelectionFromRep();
}
if ((cs.docTextChanged || cs.userChangedSelection) && isScrollableEditEvent(cs.type)) {
scrollSelectionIntoView();
}
if (cs.docTextChanged && cs.type.indexOf('importText') < 0) {
outsideNotifyDirty();
}
}
} else if (currentCallStack.type === 'idleWorkTimer') {
idleWorkTimer.atLeast(1000);
}
currentCallStack = null;
}
return result;
};
editorInfo.ace_inCallStack = inCallStack;
const inCallStackIfNecessary = (type, action) => {
if (!currentCallStack) {
inCallStack(type, action);
} else {
action();
}
};
editorInfo.ace_inCallStackIfNecessary = inCallStackIfNecessary;
const dispose = () => {
disposed = true;
if (idleWorkTimer) idleWorkTimer.never();
teardown();
};
const setWraps = (newVal) => {
doesWrap = newVal;
targetBody.classList.toggle('doesWrap', doesWrap);
scheduler.setTimeout(() => {
inCallStackIfNecessary('setWraps', () => {
fastIncorp(7);
recreateDOM();
fixView();
});
}, 0);
};
const setStyled = (newVal) => {
const oldVal = isStyled;
isStyled = !!newVal;
if (newVal !== oldVal) {
if (!newVal) {
// clear styles
inCallStackIfNecessary('setStyled', () => {
fastIncorp(12);
const clearStyles = [];
for (const k of Object.keys(STYLE_ATTRIBS)) {
clearStyles.push([k, '']);
}
performDocumentApplyAttributesToCharRange(0, rep.alltext.length, clearStyles);
});
}
}
};
const setTextFace = (face) => {
targetBody.style.fontFamily = face;
lineMetricsDiv.style.fontFamily = face;
};
const recreateDOM = () => {
// precond: normalized
recolorLinesInRange(0, rep.alltext.length);
};
const setEditable = (newVal) => {
isEditable = newVal;
targetBody.contentEditable = isEditable ? 'true' : 'false';
targetBody.setAttribute('aria-readonly', isEditable ? 'false' : 'true');
targetBody.classList.toggle('static', !isEditable);
};
const enforceEditability = () => setEditable(isEditable);
const importText = (text, undoable, dontProcess) => {
let lines;
if (dontProcess) {
if (text.charAt(text.length - 1) !== '\n') {
throw new Error('new raw text must end with newline');
}
if (/[\r\t\xa0]/.exec(text)) {
throw new Error('new raw text must not contain CR, tab, or nbsp');
}
lines = text.substring(0, text.length - 1).split('\n');
} else {
lines = text.split('\n').map(textify);
}
let newText = '\n';
if (lines.length > 0) {
newText = `${lines.join('\n')}\n`;
}
inCallStackIfNecessary(`importText${undoable ? 'Undoable' : ''}`, () => {
setDocText(newText);
});
if (dontProcess && rep.alltext !== text) {
throw new Error('mismatch error setting raw text in importText');
}
};
const importAText = (atext, apoolJsonObj, undoable) => {
atext = cloneAText(atext);
if (apoolJsonObj) {
const wireApool = (new AttribPool()).fromJsonable(apoolJsonObj);
atext.attribs = moveOpsToNewPool(atext.attribs, wireApool, rep.apool);
}
inCallStackIfNecessary(`importText${undoable ? 'Undoable' : ''}`, () => {
setDocAText(atext);
});
};
const setDocAText = (atext) => {
if (atext.text === '') {
/*
* The server is fine with atext.text being an empty string, but the front
* end is not, and crashes.
*
* It is not clear if this is a problem in the server or in the client
* code, and this is a client-side hack fix. The underlying problem needs
* to be investigated.
*
* See for reference:
* - https://github.com/ether/etherpad-lite/issues/3861
*/
atext.text = '\n';
}
fastIncorp(8);
const oldLen = rep.lines.totalWidth();
const numLines = rep.lines.length();
const upToLastLine = rep.lines.offsetOfIndex(numLines - 1);
const lastLineLength = rep.lines.atIndex(numLines - 1).text.length;
const assem = new SmartOpAssembler();
const o = new Op('-');
o.chars = upToLastLine;
o.lines = numLines - 1;
assem.append(o);
o.chars = lastLineLength;
o.lines = 0;
assem.append(o);
for (const op of opsFromAText(atext)) assem.append(op);
const newLen = oldLen + assem.getLengthChange();
const changeset = checkRep(
pack(oldLen, newLen, assem.toString(), atext.text.slice(0, -1)));
performDocumentApplyChangeset(changeset);
performSelectionChange(
[0, rep.lines.atIndex(0).lineMarker], [0, rep.lines.atIndex(0).lineMarker]);
idleWorkTimer.atMost(100);
if (rep.alltext !== atext.text) {
throw new Error('mismatch error setting raw text in setDocAText');
}
};
const setDocText = (text) => {
setDocAText(makeAText(text));
};
const getDocText = () => {
const alltext = rep.alltext;
let len = alltext.length;
if (len > 0) len--; // final extra newline
return alltext.substring(0, len);
};
const exportText = () => {
if (currentCallStack && !currentCallStack.domClean) {
inCallStackIfNecessary('exportText', () => {
fastIncorp(2);
});
}
return getDocText();
};
const editorChangedSize = () => fixView();
const setOnKeyPress = (handler) => {
outsideKeyPress = handler;
};
const setOnKeyDown = (handler) => {
outsideKeyDown = handler;
};
const setNotifyDirty = (handler) => {
outsideNotifyDirty = handler;
};
const CMDS = {
clearauthorship: (prompt) => {
if ((!(rep.selStart && rep.selEnd)) || isCaret()) {
if (prompt) {
prompt();
} else {
performDocumentApplyAttributesToCharRange(0, rep.alltext.length, [
['author', ''],
]);
}
} else {
setAttributeOnSelection('author', '');
}
},
};
const execCommand = (cmd, ...args) => {
cmd = cmd.toLowerCase();
if (CMDS[cmd]) {
inCallStackIfNecessary(cmd, () => {
fastIncorp(9);
CMDS[cmd](...args);
});
}
};
const replaceRange = (start, end, text) => {
inCallStackIfNecessary('replaceRange', () => {
fastIncorp(9);
performDocumentReplaceRange(start, end, text);
});
};
editorInfo.ace_callWithAce = (fn, callStack, normalize) => {
let wrapper = () => fn(editorInfo);
if (normalize !== undefined) {
const wrapper1 = wrapper;
wrapper = () => {
editorInfo.ace_fastIncorp(9);
wrapper1();
};
}
if (callStack !== undefined) {
return editorInfo.ace_inCallStack(callStack, wrapper);
} else {
return wrapper();
}
};
/**
* This methed exposes a setter for some ace properties
* @param key the name of the parameter
* @param value the value to set to
*/
editorInfo.ace_setProperty = (key, value) => {
// These properties are exposed
const setters = {
wraps: setWraps,
showsauthorcolors: (val) => targetBody.classList.toggle('authorColors', !!val),
showsuserselections: (val) => targetBody.classList.toggle('userSelections', !!val),
showslinenumbers: (value) => {
hasLineNumbers = !!value;
sideDiv.parentNode.classList.toggle('line-numbers-hidden', !hasLineNumbers);
fixView();
},
userauthor: (value) => {
thisAuthor = String(value);
documentAttributeManager.author = thisAuthor;
},
styled: setStyled,
textface: setTextFace,
rtlistrue: (value) => {
targetBody.classList.toggle('rtl', value);
targetBody.classList.toggle('ltr', !value);
document.documentElement.dir = value ? 'rtl' : 'ltr';
},
};
const setter = setters[key.toLowerCase()];
// check if setter is present
if (setter !== undefined) {
setter(value);
}
};
editorInfo.ace_setBaseText = (txt) => {
changesetTracker.setBaseText(txt);
};
editorInfo.ace_setBaseAttributedText = (atxt, apoolJsonObj) => {
changesetTracker.setBaseAttributedText(atxt, apoolJsonObj);
};
editorInfo.ace_applyChangesToBase = (c, optAuthor, apoolJsonObj) => {
changesetTracker.applyChangesToBase(c, optAuthor, apoolJsonObj);
};
editorInfo.ace_prepareUserChangeset = () => changesetTracker.prepareUserChangeset();
editorInfo.ace_applyPreparedChangesetToBase = () => {
changesetTracker.applyPreparedChangesetToBase();
};
editorInfo.ace_setUserChangeNotificationCallback = (f) => {
changesetTracker.setUserChangeNotificationCallback(f);
};
editorInfo.ace_setAuthorInfo = (author, info) => {
setAuthorInfo(author, info);
};
editorInfo.ace_getDocument = () => document;
const now = () => Date.now();
const newTimeLimit = (ms) => {
const startTime = now();
let exceededAlready = false;
let printedTrace = false;
const isTimeUp = () => {
if (exceededAlready) {
if ((!printedTrace)) {
printedTrace = true;
}
return true;
}
const elapsed = now() - startTime;
if (elapsed > ms) {
exceededAlready = true;
return true;
} else {
return false;
}
};
isTimeUp.elapsed = () => now() - startTime;
return isTimeUp;
};
const makeIdleAction = (func) => {
let scheduledTimeout = null;
let scheduledTime = 0;
const unschedule = () => {
if (scheduledTimeout) {
scheduler.clearTimeout(scheduledTimeout);
scheduledTimeout = null;
}
};
const reschedule = (time) => {
unschedule();
scheduledTime = time;
let delay = time - now();
if (delay < 0) delay = 0;
scheduledTimeout = scheduler.setTimeout(callback, delay);
};
const callback = () => {
scheduledTimeout = null;
// func may reschedule the action
func();
};
return {
atMost: (ms) => {
const latestTime = now() + ms;
if ((!scheduledTimeout) || scheduledTime > latestTime) {
reschedule(latestTime);
}
},
// atLeast(ms) will schedule the action if not scheduled yet.
// In other words, "infinity" is replaced by ms, even though
// it is technically larger.
atLeast: (ms) => {
const earliestTime = now() + ms;
if ((!scheduledTimeout) || scheduledTime < earliestTime) {
reschedule(earliestTime);
}
},
never: () => {
unschedule();
},
};
};
const fastIncorp = (n) => {
// normalize but don't do any lexing or anything
incorporateUserChanges();
};
editorInfo.ace_fastIncorp = fastIncorp;
const idleWorkTimer = makeIdleAction(() => {
if (inInternationalComposition) {
// don't do idle input incorporation during international input composition
idleWorkTimer.atLeast(500);
return;
}
inCallStackIfNecessary('idleWorkTimer', () => {
const isTimeUp = newTimeLimit(250);
let finishedImportantWork = false;
let finishedWork = false;
try {
incorporateUserChanges();
if (isTimeUp()) return;
updateLineNumbers(); // update line numbers if any time left
if (isTimeUp()) return;
finishedImportantWork = true;
finishedWork = true;
} finally {
if (finishedWork) {
idleWorkTimer.atMost(1000);
} else if (finishedImportantWork) {
// if we've finished highlighting the view area,
// more highlighting could be counter-productive,
// e.g. if the user just opened a triple-quote and will soon close it.
idleWorkTimer.atMost(500);
} else {
let timeToWait = Math.round(isTimeUp.elapsed() / 2);
if (timeToWait < 100) timeToWait = 100;
idleWorkTimer.atMost(timeToWait);
}
}
});
});
let _nextId = 1;
const uniqueId = (n) => {
// not actually guaranteed to be unique, e.g. if user copy-pastes
// nodes with ids
const nid = n.id;
if (nid) return nid;
return (n.id = `magicdomid${_nextId++}`);
};
const recolorLinesInRange = (startChar, endChar) => {
if (endChar <= startChar) return;
if (startChar < 0 || startChar >= rep.lines.totalWidth()) return;
let lineEntry = rep.lines.atOffset(startChar); // rounds down to line boundary
let lineStart = rep.lines.offsetOfEntry(lineEntry);
let lineIndex = rep.lines.indexOfEntry(lineEntry);
let selectionNeedsResetting = false;
let firstLine = null;
// tokenFunc function; accesses current value of lineEntry and curDocChar,
// also mutates curDocChar
const tokenFunc = (tokenText, tokenClass) => {
lineEntry.domInfo.appendSpan(tokenText, tokenClass);
};
while (lineEntry && lineStart < endChar) {
const lineEnd = lineStart + lineEntry.width;
lineEntry.domInfo.clearSpans();
getSpansForLine(lineEntry, tokenFunc, lineStart);
lineEntry.domInfo.finishUpdate();
markNodeClean(lineEntry.lineNode);
if (rep.selStart && rep.selStart[0] === lineIndex ||
rep.selEnd && rep.selEnd[0] === lineIndex) {
selectionNeedsResetting = true;
}
if (firstLine == null) firstLine = lineIndex;
lineStart = lineEnd;
lineEntry = rep.lines.next(lineEntry);
lineIndex++;
}
if (selectionNeedsResetting) {
currentCallStack.selectionAffected = true;
}
};
// like getSpansForRange, but for a line, and the func takes (text,class)
// instead of (width,class); excludes the trailing '\n' from
// consideration by func
const getSpansForLine = (lineEntry, textAndClassFunc, lineEntryOffsetHint) => {
let lineEntryOffset = lineEntryOffsetHint;
if ((typeof lineEntryOffset) !== 'number') {
lineEntryOffset = rep.lines.offsetOfEntry(lineEntry);
}
const text = lineEntry.text;
if (text.length === 0) {
// allow getLineStyleFilter to set line-div styles
const func = linestylefilter.getLineStyleFilter(
0, '', textAndClassFunc, rep.apool);
func('', '');
} else {
let filteredFunc = linestylefilter.getFilterStack(text, textAndClassFunc, browser);
const lineNum = rep.lines.indexOfEntry(lineEntry);
const aline = rep.alines[lineNum];
filteredFunc = linestylefilter.getLineStyleFilter(
text.length, aline, filteredFunc, rep.apool);
filteredFunc(text, '');
}
};
let observedChanges;
const clearObservedChanges = () => {
observedChanges = {
cleanNodesNearChanges: {},
};
};
clearObservedChanges();
const getCleanNodeByKey = (key) => {
let n = targetDoc.getElementById(key);
// copying and pasting can lead to duplicate ids
while (n && isNodeDirty(n)) {
n.id = '';
n = targetDoc.getElementById(key);
}
return n;
};
const observeChangesAroundNode = (node) => {
// Around this top-level DOM node, look for changes to the document
// (from how it looks in our representation) and record them in a way
// that can be used to "normalize" the document (apply the changes to our
// representation, and put the DOM in a canonical form).
let cleanNode;
let hasAdjacentDirtyness;
if (!isNodeDirty(node)) {
cleanNode = node;
const prevSib = cleanNode.previousSibling;
const nextSib = cleanNode.nextSibling;
hasAdjacentDirtyness = ((prevSib && isNodeDirty(prevSib)) ||
(nextSib && isNodeDirty(nextSib)));
} else {
// node is dirty, look for clean node above
let upNode = node.previousSibling;
while (upNode && isNodeDirty(upNode)) {
upNode = upNode.previousSibling;
}
if (upNode) {
cleanNode = upNode;
} else {
let downNode = node.nextSibling;
while (downNode && isNodeDirty(downNode)) {
downNode = downNode.nextSibling;
}
if (downNode) {
cleanNode = downNode;
}
}
if (!cleanNode) {
// Couldn't find any adjacent clean nodes!
// Since top and bottom of doc is dirty, the dirty area will be detected.
return;
}
hasAdjacentDirtyness = true;
}
if (hasAdjacentDirtyness) {
// previous or next line is dirty
observedChanges.cleanNodesNearChanges[`$${uniqueId(cleanNode)}`] = true;
} else {
// next and prev lines are clean (if they exist)
const lineKey = uniqueId(cleanNode);
const prevSib = cleanNode.previousSibling;
const nextSib = cleanNode.nextSibling;
const actualPrevKey = ((prevSib && uniqueId(prevSib)) || null);
const actualNextKey = ((nextSib && uniqueId(nextSib)) || null);
const repPrevEntry = rep.lines.prev(rep.lines.atKey(lineKey));
const repNextEntry = rep.lines.next(rep.lines.atKey(lineKey));
const repPrevKey = ((repPrevEntry && repPrevEntry.key) || null);
const repNextKey = ((repNextEntry && repNextEntry.key) || null);
if (actualPrevKey !== repPrevKey || actualNextKey !== repNextKey) {
observedChanges.cleanNodesNearChanges[`$${uniqueId(cleanNode)}`] = true;
}
}
};
const observeChangesAroundSelection = () => {
if (currentCallStack.observedSelection) return;
currentCallStack.observedSelection = true;
const selection = getSelection();
if (selection) {
const node1 = topLevel(selection.startPoint.node);
const node2 = topLevel(selection.endPoint.node);
if (node1) observeChangesAroundNode(node1);
if (node2 && node1 !== node2) {
observeChangesAroundNode(node2);
}
}
};
const observeSuspiciousNodes = () => {
// inspired by Firefox bug #473255, where pasting formatted text
// causes the cursor to jump away, making the new HTML never found.
if (targetBody.getElementsByTagName) {
const elts = targetBody.getElementsByTagName('style');
for (const elt of elts) {
const n = topLevel(elt);
if (n && n.parentNode === targetBody) {
observeChangesAroundNode(n);