-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy patheditor.js
More file actions
2546 lines (2328 loc) · 85.7 KB
/
Copy patheditor.js
File metadata and controls
2546 lines (2328 loc) · 85.7 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
// editor.js 2026-06-17
// dwachss/historystack/history.js commit 806bac52
// Implements the History interface for use with things other than browser history. I don't know why they won't let us use
'use strict';
function History (inititalstate){
this._length = 1;
this._index = 1;
this._states = [undefined, inititalstate]; // easiest on the math to use 1-index array
}
History.prototype = {
back() { return this.go(-1) },
forward() {return this.go(1) },
go(n) {
this._index += n;
if (this._index < 1 ) this._index = 1;
if (this._index > this._length ) this._index = this._length;
return this.state;
},
pushState(state) {
this._length = ++this._index;
return this.replaceState(state);
},
replaceState (state) { return this._states[this._index] = state },
get length() { return this._length },
get state() { return this._states[this._index] },
// not part of the interface but useful nonetheless
get atStart() { return this._index == 1 },
get atEnd() { return this._index == this._length }
}
// dwachss/keymap/keymap.js commit 383f82cc
// allows mapping specific key sequences to actions
'use strict';
(()=>{
const canonicalSpellings = 'ArrowDown ArrowLeft ArrowRight ArrowUp Backspace CapsLock Delete End Enter Escape Home Insert NumLock PageDown PageUp Pause ScrollLock Space Tab'.split(' ');
const lowercaseSpellings = canonicalSpellings.map(s => new RegExp(`\\b${s}\\b`, 'gi'));
// Microsoft SendKeys notation, https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/sendkeys-statement
// 'Return' is from VIM, https://vimhelp.org/intro.txt.html#%3CReturn%3E
const alternateSpellings = 'Down Left Right Up BS CapsLock Del End Return Esc Home Ins NumLock PGDN PGUP Break ScrollLock Spacebar Tab'.split(' ').map(s => new RegExp(`\\b${s}\\b`, 'gi'));
// modifier keys. VIM uses '-', jquery.hotkeys uses '+', https://github.com/jresig/jquery.hotkeys
// Not using meta-
const modifiers = [[/s(hift)?[+-]/gi, '+'], [/c(trl)?[+-]/gi, '^'], [/a(lt)?[+-]/gi, '%']];
function normalize (keyDescriptor){
keyDescriptor = keyDescriptor.trim().replaceAll(/ +/g, ' '); // collapse multiple spaces
lowercaseSpellings.forEach( (re, i) => { keyDescriptor = keyDescriptor.replaceAll(re, canonicalSpellings[i]) } );
alternateSpellings.forEach( (re, i) => { keyDescriptor = keyDescriptor.replaceAll(re, canonicalSpellings[i]) } );
// VIM key descriptors are enclosed in angle brackets; sendkeys are enclosed in braces
keyDescriptor = keyDescriptor.replaceAll(/(?<= |^)<([^>]+)>(?= |$)/g, '$1');
keyDescriptor = keyDescriptor.replaceAll(/{([^}]+|})}/g, '$1');
// uppercase function keys
keyDescriptor = keyDescriptor.replaceAll(/f(\d+)/g, 'F$1');
// it's easiest to turn modifiers into single keys, then reorder them and rename them
modifiers.forEach( pair => { keyDescriptor = keyDescriptor.replaceAll(...pair) } );
// normalize the order of ctrl-alt-shift
keyDescriptor = keyDescriptor.replaceAll(
/[+^%]+(?! |$)/g, // don't match a final [+^%], since that will be an actual character
match => (/\^/.test(match) ? 'ctrl-' : '') + (/%/.test(match) ? 'alt-' : '') + (/\+/.test(match) ? 'shift-' : '')
)
keyDescriptor = keyDescriptor.replaceAll(/shift-([a-zA-Z])\b/g, (match, letter) => letter.toUpperCase() );
return keyDescriptor;
}
// generates successive prefixes of lists of keyDescriptors
// turns 'alt-f x Enter' into [/^alt-f$/, /^alt-f x$/, /^alt-f x Enter$/]
// and /alt-x f\d+ (Enter|Escape)/i into [/^alt-x$/i, /^alt-x f\d+$/i, /^alt-x f\d+ (Enter|Escape)$/i]
function prefixREs(strOrRE){
let sources, ignoreCase;
if (!strOrRE.source){
// escape RegExp from https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
sources = strOrRE.toString().trim().split(/\s+/).
map(normalize).
map(s => s.replaceAll(/[.*+?^=!:${}()|\[\]\/\\]/g, "\\$&"));
ignoreCase = '';
}else{
sources = strOrRE.source.trim().split(/\s+/);
ignoreCase = strOrRE.ignoreCase ? 'i' : '';
}
return sources.reduce ( (accumulator, currentValue, i) => {
if (i == 0) return [RegExp(`^${currentValue}$`, ignoreCase)]; // ^...$ to match the entire key
const source = accumulator[i-1].source.replaceAll(/^\^|\$$/g,''); // strip off the previous ^...$
accumulator.push( new RegExp( `^${source} ${currentValue}$`, ignoreCase ) );
return accumulator;
}, []);
};
// ANSI keyboard codes
const specialKeys = {
'Backquote': '`',
'shift-Backquote': '~',
'shift-1': '!',
'shift-2': '@',
'shift-3': '#',
'shift-4': '$',
'shift-5': '%',
'shift-6': '^',
'shift-7': '&',
'shift-8': '*',
'shift-9': '(',
'shift-0': ')',
'Minus': '-',
'shift-Minus': '_',
'Equal': '=',
'shift-Equal': '+',
'BracketRight': '[',
'shift-BracketRight': '{',
'BracketLeft': ']',
'shift-BracketLeft': '}',
'Backslash': '\\',
'shift-Backslash': '|',
'Semicolon': ';',
'shift-Semicolon': ':',
'Quote': "'",
'shift-Quote': '"',
'Comma': ',',
'shift-Comma': '<',
'Period': '.',
'shift-Period': '>',
'Slash': '/',
'shift-Slash': '?',
};
function addKeyDescriptor(evt){
// create a "keyDescriptor" field in evt that represents the keystroke as a whole: "ctrl-alt-Delete" for instance.
const {code, shiftKey, ctrlKey, altKey} = evt;
let key = evt.key; // needs to be variable
if (!key || /^(?:shift|control|meta|alt)$/i.test(key)) return evt; // ignore undefined or modifier keys alone
// we use spaces to delimit keystrokes, so this needs to be changed; use the code
if (key == ' ') key = 'Space';
// In general, use the key field. However, modified letters (ctrl- or alt-) use the code field
// so that ctrl-A is the A key even on non-English keyboards.
if (ctrlKey || altKey){
if (/^(Key|Digit)\w$/.test(code)){
evt.keyDescriptor = code.charAt(code.length-1)[shiftKey ? 'toUpperCase' : 'toLowerCase']();
}else if (/^Numpad/.test(code)){
evt.keyDescriptor = key;
}else{
evt.keyDescriptor = code;
}
if (!/^[a-zA-Z]$/.test(evt.keyDescriptor) && shiftKey) evt.keyDescriptor = 'shift-'+evt.keyDescriptor;
if (evt.keyDescriptor in specialKeys) evt.keyDescriptor = specialKeys[evt.keyDescriptor];
}else{
evt.keyDescriptor = key;
// printable characters should ignore the shift; that's incorporated into the key generated
if (key.length !== 1 && shiftKey) evt.keymap = 'shift-'+evt.keymap;
}
if (altKey) evt.keyDescriptor = 'alt-'+evt.keyDescriptor;
if (ctrlKey) evt.keyDescriptor = 'ctrl-'+evt.keyDescriptor;
return evt;
}
function keymap (keyDescriptorTarget, handler, prefixHandler = ( evt => { evt.preventDefault() } )){
const prefixes = prefixREs(keyDescriptorTarget);
const prefixSymbol = Symbol();
const newHandler = function (evt){
const keyDescriptorSource = addKeyDescriptor(evt).keyDescriptor;
if (!keyDescriptorSource) return; // it is a modifier key
evt.keymapFilter = keyDescriptorTarget;
const el = evt.currentTarget;
let currentSequence = keyDescriptorSource;
if (el[prefixSymbol]) currentSequence = `${el[prefixSymbol]} ${currentSequence}`;
while (currentSequence){
const length = currentSequence.split(' ').length;
if ( prefixes[length-1].test(currentSequence) ){
// we have a match
evt.keymapSequence = el[prefixSymbol] = currentSequence;
prefixHandler.apply(this, arguments);
if (length == prefixes.length){
// we have a match for the whole thing
delete el[prefixSymbol];
return handler.apply(this, arguments);
}
return;
}
// if we get here, then we do not have a match. Maybe we started too soon (looking for 'a b c', got 'a a b c' and matched the beginning of the
// sequence at the first 'a', but that was wrong, so take off the first 'a' and try again
currentSequence = currentSequence.replace(/^\S+[ ]?/, '');
}
delete el[prefixSymbol]; // no matches at all.
};
newHandler.keymapPrefix = prefixSymbol;
newHandler.keymapFilter = keyDescriptorTarget;
return newHandler;
}
globalThis.keymap = keymap;
keymap.normalize = normalize;
keymap.addKeyDescriptor = addKeyDescriptor;
})();
// dwachss/status/status.js commit 6a9da212
// Promise.alert and Promise.prompt allow for creating a "status bar" for interacting with the user
'use strict';
Promise.alert = (message, container = globalThis) => {
return Promise.resolve(message).then( message => {
if (message instanceof Error) throw message;
if (container instanceof HTMLElement){
displayMessage(container, message, Promise.alert.classes.success);
}else{
(container.log ?? container.alert)(message);
}
return message;
}).catch(error => {
if (container instanceof HTMLElement){
displayMessage(container, error, Promise.alert.classes.failure);
}else{
const message = container.error ? error : `\u26A0\uFE0F ${error}`; // add warning emoji
(container.error ?? container.alert)(message);
}
return error; // create a fulfilled promise with the error, if the user wants to do something more
});
function displayMessage (container, message, classname = Promise.alert.classes.success){
const span = document.createElement('span');
span.classList.add(classname);
span.textContent = message;
span.setAttribute('role', 'alert');
span.ontransitionend = evt => span.remove();
container.prepend(span);
setTimeout(()=>span.classList.add(Promise.alert.classes.hidden), 10);
}
}
Object.defineProperty( Promise.prototype, 'alert', {
value: function (container) { return Promise.alert(this, container) }
});
Promise.alert.classes = {
success: 'success',
failure: 'failure',
hidden: 'hidden'
};
Promise.prompt = (promptMessage = '', container = globalThis, defaultValue = '') => {
if (container instanceof HTMLElement){
return new Promise ((resolve, reject) => displayPrompt(resolve, reject)).
finally( () => container.querySelectorAll('label.prompt').forEach( el => el.remove() ) );
}else{
return new Promise ((resolve, reject) => {
const response = container.prompt(promptMessage, defaultValue);
if (response === null) reject (new Error(Promise.prompt.cancelMessage));
resolve(response);
});
}
function history(){
const key = Symbol.for('Promise.prompt.history');
if (key in container) return container[key];
try{
return container[key] = new History(defaultValue);
}catch{
// if my history stack is not implemented, the original History constructor will throw a TypeError
return null;
}
}
function displayPrompt(resolve, reject){
container.querySelectorAll('label.prompt').forEach( el => el.remove() ); // remove any old elements
const label = document.createElement('label');
label.className = 'prompt';
label.append(document.createElement('strong'), document.createElement('input'));
label.querySelector('strong').textContent = promptMessage;
label.querySelector('input').value = defaultValue;
label.querySelector('input').addEventListener('keydown', function(evt) {
switch (evt.key){
case 'Enter':
evt.preventDefault();
resolve(this.value);
break;
case 'Escape':
evt.preventDefault();
reject (new Error(Promise.prompt.cancelMessage));
break;
}
});
const h = history();
if (h) label.querySelector('input').addEventListener('keydown', function(evt) {
switch (evt.key){
case 'Enter':
h.pushState(this.value);
break;
case 'ArrowUp':
if (h.atEnd){
h.pushState(this.value);
h.back();
}
this.value = h.state;
h.back();
evt.preventDefault();
break;
case 'ArrowDown':
this.value = h.forward();
evt.preventDefault();
break;
}
});
container.prepend(label);
label.querySelector('input').focus();
}
}
Promise.prompt.cancelMessage = "User Cancelled";
// dwachss/toolbar/toolbar.js commit 0164cf02
'use strict';
function Toolbar (container, target, func, label){
this._container = container;
this._func = func.bind(target);
container.setAttribute('role', 'toolbar');
if (label) container.setAttribute('aria-label', label);
// use ARIA (https://www.w3.org/TR/wai-aria-practices/examples/toolbar/toolbar.html ) to
// tie the toolbar to the target
let id = target.getAttribute('id');
if (!id) {
id = 'toolbar-target-'+Math.random().toString(36).slice(2); // random enough string
target.setAttribute('id', id);
}
let otherToolbar = document.querySelector(`[aria-controls=${id}]`);
container.setAttribute('aria-controls', id);
// only have one toolbar capturing the context menu
if (!otherToolbar){
target.addEventListener('keyup', evt => {
if (evt.key == 'ContextMenu'){
if ( container.children.length == 0 ) return;
container.querySelector('[tabindex="0"]').focus();
evt.preventDefault();
return false;
}
});
container.addEventListener('contextmenu', evt => {
// Firefox fires the context menu on the *container* when focused with the event listener above.
// Just disable the keyboard menu button (right-click works fine)
if (evt.button == 0) evt.preventDefault();
});
container.classList.add('capturing-menu');
}
container.addEventListener('keydown', evt => {
if (evt.key == 'Escape') target.focus();
if (/^Key[A-Z]$/.test(evt.code)){
const index = evt.code.charCodeAt(3) - 'A'.charCodeAt(0) + 1;
const button = container.querySelector(`button:nth-of-type(${index})`);
if (button) {
button.dispatchEvent (new MouseEvent('click'));
button.classList.add('highlight');
setTimeout( ()=> button.classList.remove('highlight'), 400);
}
}
// https://www.w3.org/TR/wai-aria-practices/#kbd_roving_tabindex
let focusedButton = container.querySelector('[tabindex="0"]');
if (!focusedButton) return;
let tabbables = container.querySelectorAll('[tabindex]');
let i = [].indexOf.call(tabbables, focusedButton);
if (evt.key == 'ArrowRight') {
++i;
if (i >= tabbables.length ) i = 0; // ahould be at least one element, the focused one
focusedButton.setAttribute ('tabindex', -1);
tabbables[i].setAttribute ('tabindex', 0);
tabbables[i].focus();
}
if (evt.key == 'ArrowLeft') {
--i;
if (i < 0 ) i = tabbables.length - 1; // ahould be at least one element, the focused one
focusedButton.setAttribute ('tabindex', -1);
tabbables[i].setAttribute ('tabindex', 0);
tabbables[i].focus();
}
// Firefox wants to insert the key into the *target*
// So any printable character (length == 1) is to be ignored.
if (evt.key.length == 1) evt.preventDefault();
});
}
Toolbar.for = function(el){
const id = el.getAttribute('id');
if (!id) return null;
return document.querySelector(`[aria-controls=${id}]`);
}
Toolbar.getAttribute = function (el, attr) {
if (/^style\./.test(attr)){
attr = attr.slice(6).replace (/-[a-z]/g, x => x.toUpperCase() ); // make sure it's camel case
return el.ownerDocument.defaultView.getComputedStyle(el)[attr];
}else{
return el.getAttribute(attr);
}
}
Toolbar.setAttribute = function (el, attr, state) {
if (/^style\./.test(attr)){
attr = attr.slice(6).replace (/-[a-z]/g, x => x.toUpperCase() ); // make sure it's camel case
el.style[attr] = state;
}else{
el.setAttribute(attr, state);
}
};
Toolbar.toggleAttribute = function (el, attr, states){
Toolbar.setAttribute (el, attr, Toolbar.getAttribute(el, attr) == states[0] ? states[1] : states[0])
};
Toolbar.prototype = {
button(name, command = name, title) {
let button = this._container.querySelector(`button[name=${JSON.stringify(name)}]`);
if (!button){
this._container.insertAdjacentHTML('beforeend', '<button>');
button = this._container.lastChild;
}
button.setAttribute('name', name);
button.classList.add(name.replace(/\s/g,''));
button.setAttribute('title', title ?? name);
button.setAttribute('data-command', command);
let focusedButton = this._container.querySelector('[tabindex="0"]');
button.setAttribute('tabindex', focusedButton ? -1 : 0 ); // roving tab index. https://www.w3.org/TR/wai-aria-practices/#kbd_roving_tabindex
button.addEventListener ('click', evt => {
this._container.querySelector('[tabindex="0"]').setAttribute('tabindex', -1);
button.setAttribute ('tabindex', 0);
this._func(button.getAttribute('data-command'));
});
return button;
},
toggleButton(){
const button = this.button(...arguments);
button.addEventListener('click',
evt => Toolbar.toggleAttribute (evt.target, 'aria-pressed', ['true', 'false'])
);
return button;
},
observerButton (name, command = name, attr, title){
return this.observerElement (this.button(name, command, title), attr);
},
buttons (buttons){
return buttons.forEach(button => this.button(...button));
},
element (el) {
if (el.nodeType){
this._container.appendChild(el);
}else{
this._container.insertAdjacentHTML('beforeend', el);
el = this._container.lastChild;
}
return el;
},
observerElement (el, attr){
el = this.element(el);
let styleRE = undefined;
if (/^style\./.test(attr)){
// keeping track of what needs camel case and what needs snake case is hard!
attr = attr.slice(6).replace (/-[a-z]/g, x => x.toUpperCase() );
// the existence of styleRE is a flag that we are looking for styles.
styleRE = new RegExp (`${attr.replace (/[A-Z]/g, x => '-' + x.toLowerCase() )}:\\s*([^;]+)\\s*;`);
}
const observer = new MutationObserver( mutations => {
mutations.forEach ( mutation => {
let newValue = mutation.target.getAttribute(attr);
if (styleRE) newValue = mutation.target.style[attr];
let oldValue = mutation.oldValue;
if (styleRE) {
oldValue = styleRE.exec(mutation.oldValue);
if (oldValue) oldValue = oldValue[1];
}
// if we are observing 'style', then *any* change to inline styles will trigger this.
// we only want to do anything if *our* CSS property changed.
if (newValue == oldValue) return;
el.classList.remove (oldValue);
if (newValue) el.classList.add (newValue.replace(/\s/g,''));
});
});
observer.observe (
document.querySelector(`#${this._container.getAttribute('aria-controls')}`),
{ attribute: true, attributeOldValue: true, attributeFilter: [ styleRE ? 'style' : attr ] }
);
return el;
}
};
// bililiteRange.js commit a4e44e6
'use strict';
let bililiteRange; // create one global variable
(function(){
const datakey = Symbol(); // use as the key to modify elements.
bililiteRange = function(el){
var ret;
if (el.setSelectionRange){
// Element is an input or textarea
// note that some input elements do not allow selections
try{
el.selectionStart = el.selectionStart;
ret = new InputRange();
}catch(e){
ret = new NothingRange();
}
}else{
// Standards, with any other kind of element
ret = new W3CRange();
}
ret._el = el;
// determine parent document, as implemented by John McLear <john@mclear.co.uk>
ret._doc = el.ownerDocument;
ret._win = ret._doc.defaultView;
ret._bounds = [0, ret.length];
if (!(el[datakey])){ // we haven't processed this element yet
const data = createDataObject (el);
startupHooks.forEach ( hook => hook (el, ret, data) );
}
return ret;
}
bililiteRange.version = 3.2;
const startupHooks = new Set();
bililiteRange.addStartupHook = fn => startupHooks.add(fn);
startupHooks.add (trackSelection);
startupHooks.add (fixInputEvents);
startupHooks.add (correctNewlines);
// selection tracking. We want clicks to set the selection to the clicked location but tabbing in or element.focus() should restore
// the selection to what it was.
// There's no good way to do this. I just assume that a mousedown (or a drag and drop
// into the element) within 100 ms of the focus event must have caused the focus, and
// therefore we should not restore the selection.
function trackSelection (element, range, data){
data.selection = [0,0];
range.listen('focusout', evt => data.selection = range._nativeSelection() );
range.listen('mousedown', evt => data.mousetime = evt.timeStamp );
range.listen('drop', evt => data.mousetime = evt.timeStamp );
range.listen('focus', evt => {
if ('mousetime' in data && evt.timeStamp - data.mousetime < 100) return;
range._nativeSelect(range._nativeRange(data.selection))
});
}
function fixInputEvents (element, range, data){
// DOM 3 input events, https://www.w3.org/TR/input-events-1/
// have a data field with the text inserted, but that isn't enough to fully describe the change;
// we need to know the old text (or at least its length)
// and *where* the new text was inserted.
// So we enhance input events with that information.
// the "newText" should always be the same as the 'data' field, if it is defined
data.oldText = range.all();
data.liveRanges = new Set();
range.listen('input', evt => {
const newText = range.all();
if (!evt.bililiteRange){
evt.bililiteRange = diff (data.oldText, newText);
if (evt.bililiteRange.unchanged){
// no change. Assume that whatever happened, happened at the selection point (and use whatever data the browser gives us).
evt.bililiteRange.start = range.clone().bounds('selection')[1] - (evt.data || '').length;
}
}
data.oldText = newText;
// Also update live ranges on this element
data.liveRanges.forEach( rng => {
const start = evt.bililiteRange.start;
const oldend = start + evt.bililiteRange.oldText.length;
const newend = start + evt.bililiteRange.newText.length;
// adjust bounds; this tries to emulate the algorithm that Microsoft Word uses for bookmarks
let [b0, b1] = rng.bounds();
if (b0 <= start){
// no change
}else if (b0 > oldend){
b0 += newend - oldend;
}else{
b0 = newend;
}
if (b1 < start){
// no change
}else if (b1 >= oldend){
b1 += newend - oldend;
}else{
b1 = start;
}
rng.bounds([b0, b1]);
})
});
}
function diff (oldText, newText){
// Try to find the changed text, assuming it was a continuous change
if (oldText == newText){
return {
unchanged: true,
start: 0,
oldText,
newText
}
}
const oldlen = oldText.length;
const newlen = newText.length;
for (var i = 0; i < newlen && i < oldlen; ++i){
if (newText.charAt(i) != oldText.charAt(i)) break;
}
const start = i;
for (i = 0; i < newlen && i < oldlen; ++i){
let newpos = newlen-i-1, oldpos = oldlen-i-1;
if (newpos < start || oldpos < start) break;
if (newText.charAt(newpos) != oldText.charAt(oldpos)) break;
}
const oldend = oldlen-i;
const newend = newlen-i;
return {
start,
oldText: oldText.slice(start, oldend),
newText: newText.slice(start, newend)
}
};
bililiteRange.diff = diff; // expose
function correctNewlines (element, range, data){
// we need to insert newlines rather than create new elements, so character-based calculations work
range.listen('paste', evt => {
if (evt.defaultPrevented) return;
// windows adds \r's to clipboard!
range.clone().bounds('selection').
text(evt.clipboardData.getData("text/plain").replace(/\r/g,''), {inputType: 'insertFromPaste'}).
bounds('endbounds').
select().
scrollIntoView();
evt.preventDefault();
});
range.listen('keydown', function(evt){
if (evt.ctrlKey || evt.altKey || evt.shiftKey || evt.metaKey) return;
if (evt.defaultPrevented) return;
if (evt.key == 'Enter'){
range.clone().bounds('selection').
text('\n', {inputType: 'insertLineBreak'}).
bounds('endbounds').
select().
scrollIntoView();
evt.preventDefault();
}
});
}
// convenience function for defining input events
function inputEventInit(type, oldText, newText, start, inputType){
return {
type,
inputType,
data: newText,
bubbles: true,
bililiteRange: {
unchanged: (oldText == newText),
start,
oldText,
newText
}
};
}
// base class
function Range(){}
Range.prototype = {
// allow use of range[0] and range[1] for start and end of bounds
get 0(){
return this.bounds()[0];
},
set 0(x){
this.bounds([x, this[1]]);
return x;
},
get 1(){
return this.bounds()[1];
},
set 1(x){
this.bounds([this[0], x]);
return x;
},
all: function(text){
if (arguments.length){
return this.bounds('all').text(text, {inputType: 'insertReplacementText'});
}else{
return this._el[this._textProp];
}
},
bounds: function(s){
if (typeof s === 'number'){
this._bounds = [s,s];
}else if (bililiteRange.bounds[s]){
this.bounds(bililiteRange.bounds[s].apply(this, arguments));
}else if (s && s.bounds){
this._bounds = s.bounds(); // copy bounds from an existing range
}else if (s){
this._bounds = s; // don't do error checking now; things may change at a moment's notice
}else{
// constrain bounds now
var b = [
Math.max(0, Math.min (this.length, this._bounds[0])),
Math.max(0, Math.min (this.length, this._bounds[1]))
];
b[1] = Math.max(b[0], b[1]);
return b;
}
return this; // allow for chaining
},
clone: function(){
return bililiteRange(this._el).bounds(this.bounds());
},
get data(){
return this._el[datakey];
},
dispatch: function(opts = {}){
var event = new Event (opts.type, opts);
event.view = this._win;
for (let prop in opts) try { event[prop] = opts[prop] } catch(e){}; // ignore read-only errors for properties that were copied in the previous line
this._el.dispatchEvent(event); // note that the event handlers will be called synchronously, before the "return this;"
return this;
},
get document() {
return this._doc;
},
dontlisten: function (type, func = console.log, target){
target ??= this._el;
target.removeEventListener(type, func);
return this;
},
get element() {
return this._el
},
get length() {
return this._el[this._textProp].length;
},
live (on = true){
this.data.liveRanges[on ? 'add' : 'delete'](this);
return this;
},
listen: function (type, func = console.log, target){
target ??= this._el;
target.addEventListener(type, func);
return this;
},
scrollIntoView() {
var top = this.top();
// note that for TEXTAREA's, this.top() will do the scrolling and the following is irrelevant.
// scroll into position if necessary
if (this._el.scrollTop > top || this._el.scrollTop+this._el.clientHeight < top){
this._el.scrollTop = top;
}
return this;
},
select: function(){
var b = this.data.selection = this.bounds();
if (this._el === this._doc.activeElement){
// only actually select if this element is active!
this._nativeSelect(this._nativeRange(b));
}
this.dispatch({type: 'select', bubbles: true});
return this; // allow for chaining
},
selection: function(text){
if (arguments.length){
return this.bounds('selection').text(text).bounds('endbounds').select();
}else{
return this.bounds('selection').text();
}
},
sendkeys: function (text){
this.data.sendkeysOriginalText = this.text();
this.data.sendkeysBounds = undefined;
function simplechar (rng, c){
if (/^{[^}]*}$/.test(c)) c = c.slice(1,-1); // deal with unknown {key}s
rng.text(c).bounds('endbounds');
}
text.replace(/{[^}]*}|[^{]+|{/g, part => (bililiteRange.sendkeys[part] || simplechar)(this, part, simplechar) );
this.bounds(this.data.sendkeysBounds);
this.dispatch({type: 'sendkeys', detail: text});
return this;
},
text: function(text, {inputType = 'insertText'} = {}){
if ( text !== undefined ){
let eventparams = [this.text(), text, this[0], inputType];
this.dispatch (inputEventInit('beforeinput',...eventparams));
this._nativeSetText(text, this._nativeRange(this.bounds()));
this[1] = this[0]+text.length;
this.dispatch (inputEventInit('input',...eventparams));
return this; // allow for chaining
}else{
return this._nativeGetText(this._nativeRange(this.bounds()));
}
},
top: function(){
return this._nativeTop(this._nativeRange(this.bounds()));
},
get window() {
return this._win;
},
wrap: function (n){
this._nativeWrap(n, this._nativeRange(this.bounds()));
return this;
},
};
// allow extensions ala jQuery
bililiteRange.prototype = Range.prototype;
bililiteRange.extend = function(fns){
Object.assign(bililiteRange.prototype, fns);
};
bililiteRange.override = (name, fn) => {
const oldfn = bililiteRange.prototype[name];
bililiteRange.prototype[name] = function(){
const oldsuper = this.super;
this.super = oldfn;
const ret = fn.apply(this, arguments);
this.super = oldsuper;
return ret;
};
}
//bounds functions
bililiteRange.bounds = {
all: function() { return [0, this.length] },
start: function() { return 0 },
end: function() { return this.length },
selection: function() {
if (this._el === this._doc.activeElement){
this.bounds ('all'); // first select the whole thing for constraining
return this._nativeSelection();
}else{
return this.data.selection;
}
},
startbounds: function() { return this[0] },
endbounds: function() { return this[1] },
union: function (name,...rest) {
const b = this.clone().bounds(...rest);
return [ Math.min(this[0], b[0]), Math.max(this[1], b[1]) ];
},
intersection: function (name,...rest) {
const b = this.clone().bounds(...rest);
return [ Math.max(this[0], b[0]), Math.min(this[1], b[1]) ];
}
};
// sendkeys functions
bililiteRange.sendkeys = {
'{tab}': function (rng, c, simplechar){
simplechar(rng, '\t'); // useful for inserting what would be whitespace
},
'{newline}': function (rng){
rng.text('\n', {inputType: 'insertLineBreak'}).bounds('endbounds');
},
'{backspace}': function (rng){
var b = rng.bounds();
if (b[0] == b[1]) rng.bounds([b[0]-1, b[0]]); // no characters selected; it's just an insertion point. Remove the previous character
rng.text('', {inputType: 'deleteContentBackward'}); // delete the characters and update the selection
},
'{del}': function (rng){
var b = rng.bounds();
if (b[0] == b[1]) rng.bounds([b[0], b[0]+1]); // no characters selected; it's just an insertion point. Remove the next character
rng.text('', {inputType: 'deleteContentForward'}).bounds('endbounds'); // delete the characters and update the selection
},
'{rightarrow}': function (rng){
var b = rng.bounds();
if (b[0] == b[1]) ++b[1]; // no characters selected; it's just an insertion point. Move to the right
rng.bounds([b[1], b[1]]);
},
'{leftarrow}': function (rng){
var b = rng.bounds();
if (b[0] == b[1]) --b[0]; // no characters selected; it's just an insertion point. Move to the left
rng.bounds([b[0], b[0]]);
},
'{selectall}': function (rng){
rng.bounds('all');
},
'{selection}': function (rng){
// insert the characters without the sendkeys processing
rng.text(rng.data.sendkeysOriginalText).bounds('endbounds');
},
'{mark}': function (rng){
rng.data.sendkeysBounds = rng.bounds();
},
'{ctrl-Home}': (rng, c, simplechar) => rng.bounds('start'),
'{ctrl-End}': (rng, c, simplechar) => rng.bounds('end')
};
// Synonyms from the DOM standard (http://www.w3.org/TR/DOM-Level-3-Events-key/)
bililiteRange.sendkeys['{Enter}'] = bililiteRange.sendkeys['{enter}'] = bililiteRange.sendkeys['{newline}'];
bililiteRange.sendkeys['{Backspace}'] = bililiteRange.sendkeys['{backspace}'];
bililiteRange.sendkeys['{Delete}'] = bililiteRange.sendkeys['{del}'];
bililiteRange.sendkeys['{ArrowRight}'] = bililiteRange.sendkeys['{rightarrow}'];
bililiteRange.sendkeys['{ArrowLeft}'] = bililiteRange.sendkeys['{leftarrow}'];
// an input element in a standards document. "Native Range" is just the bounds array
function InputRange(){}
InputRange.prototype = new Range();
InputRange.prototype._textProp = 'value';
InputRange.prototype._nativeRange = function(bounds) {
return bounds || [0, this.length];
};
InputRange.prototype._nativeSelect = function (rng){
this._el.setSelectionRange(rng[0], rng[1]);
};
InputRange.prototype._nativeSelection = function(){
return [this._el.selectionStart, this._el.selectionEnd];
};
InputRange.prototype._nativeGetText = function(rng){
return this._el.value.substring(rng[0], rng[1]);
};
InputRange.prototype._nativeSetText = function(text, rng){
var val = this._el.value;
this._el.value = val.substring(0, rng[0]) + text + val.substring(rng[1]);
};
InputRange.prototype._nativeEOL = function(){
this.text('\n');
};
InputRange.prototype._nativeTop = function(rng){
if (rng[0] == 0) return 0; // the range starts at the top
const el = this._el;
if (el.nodeName == 'INPUT') return 0;
const text = el.value;
const selection = [el.selectionStart, el.selectionEnd];
// hack from https://code.google.com/archive/p/proveit-js/source/default/source, highlightLengthAtIndex function
// note that this results in the element being scrolled; the actual number returned is irrelevant
el.value = text.slice(0, rng[0]);
el.scrollTop = Number.MAX_SAFE_INTEGER;
el.value = text;
el.setSelectionRange(...selection);
return el.scrollTop;
}
InputRange.prototype._nativeWrap = function() {throw new Error("Cannot wrap in a text element")};
function W3CRange(){}
W3CRange.prototype = new Range();
W3CRange.prototype._textProp = 'textContent';
W3CRange.prototype._nativeRange = function (bounds){
var rng = this._doc.createRange();
rng.selectNodeContents(this._el);
if (bounds){
w3cmoveBoundary (rng, bounds[0], true, this._el);
rng.collapse (true);
w3cmoveBoundary (rng, bounds[1]-bounds[0], false, this._el);
}
return rng;
};
W3CRange.prototype._nativeSelect = function (rng){
this._win.getSelection().removeAllRanges();
this._win.getSelection().addRange (rng);
};
W3CRange.prototype._nativeSelection = function (){
// returns [start, end] for the selection constrained to be in element
var rng = this._nativeRange(); // range of the element to constrain to
if (this._win.getSelection().rangeCount == 0) return [this.length, this.length]; // append to the end
var sel = this._win.getSelection().getRangeAt(0);
return [
w3cstart(sel, rng),
w3cend (sel, rng)
];
};
W3CRange.prototype._nativeGetText = function (rng){
return rng.toString();
};
W3CRange.prototype._nativeSetText = function (text, rng){
rng.deleteContents();
rng.insertNode (this._doc.createTextNode(text));
// Lea Verou's "super dirty fix" to #31
if(text == '\n' && this[1]+1 == this._el.textContent.length) {
// inserting a newline at the end
this._el.innerHTML = this._el.innerHTML + '\n';
}
this._el.normalize(); // merge the text with the surrounding text
};
W3CRange.prototype._nativeEOL = function(){
var rng = this._nativeRange(this.bounds());
rng.deleteContents();
var br = this._doc.createElement('br');
br.setAttribute ('_moz_dirty', ''); // for Firefox
rng.insertNode (br);
rng.insertNode (this._doc.createTextNode('\n'));
rng.collapse (false);
};
W3CRange.prototype._nativeTop = function(rng){
if (this.length == 0) return 0; // no text, no scrolling
if (rng.toString() == ''){
var textnode = this._doc.createTextNode('X');
rng.insertNode (textnode);
}
var startrng = this._nativeRange([0,1]);