-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathcodeit.js
1807 lines (1095 loc) · 43.7 KB
/
codeit.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
/*
codeit.js
3.1.6
https://codeit.codes
*/
// create a class for the codeit element
class CodeitElement extends HTMLElement {
// specify observed attributes so
// attributeChangedCallback will work
static get observedAttributes() {
return ['lang', 'edit'];
}
constructor() {
// call super to get codeit element
super();
let cd = this;
// if codeit CSS dosen't already exist
if (!document.head.querySelector('style[cd-style]')) {
// add codeit CSS to head
const css = `cd-el{outline:0;user-select:text;-webkit-user-select:text;overflow-wrap:break-word;white-space:pre-wrap;overflow:auto;font-size:14px;line-height:1.5;font-family:monospace;text-rendering:optimizeLegibility;font-feature-settings:"kern";display:block;background:#f1f3f4;color:#333;border-radius:10px;padding:10px;cursor:text;tab-size:2}code[class*=language-],pre[class*=language-]{color:#000;background:0 0;font-family:Consolas,Monaco,'Andale Mono','Ubuntu Mono',monospace;font-size:1em;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:2;-o-tab-size:2;tab-size:2;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}code[class*=language-] ::-moz-selection,code[class*=language-]::-moz-selection,pre[class*=language-] ::-moz-selection,pre[class*=language-]::-moz-selection{background:#b3d4fc}code[class*=language-] ::selection,code[class*=language-]::selection,pre[class*=language-] ::selection,pre[class*=language-]::selection{background:#b3d4fc}pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto}:not(pre)>code[class*=language-],pre[class*=language-]{background:#f5f2f0}:not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em;white-space:normal}.token.cdata,.token.comment,.token.doctype,.token.prolog{color:#708090}.token.punctuation{color:#999}.token.namespace{opacity:.7}.token.boolean,.token.constant,.token.deleted,.token.number,.token.property,.token.symbol,.token.tag{color:#905}.token.attr-name,.token.builtin,.token.char,.token.inserted,.token.selector,.token.string{color:#690}.language-css .token.string,.style .token.string,.token.entity,.token.operator,.token.url{color:#9a6e3a}.token.atrule,.token.attr-value,.token.keyword{color:#07a}.token.class-name,.token.function{color:#dd4a68}.token.important,.token.regex,.token.variable{color:#e90}.token.bold,.token.important{font-weight:700}.token.italic{font-style:italic}.token.entity{cursor:help}`,
head = document.head,
style = document.createElement('style');
style.setAttribute('cd-style', '');
head.appendChild(style);
style.appendChild(document.createTextNode(css));
}
// set default options
cd.options = {
tab: ' ',
catchTab: true,
preserveIdent: true,
addClosing: true,
openBrackets: ['(', '[', '{'],
closeBrackets: [')', ']', '}'],
quot: [`'`, `"`, '`'],
history: true,
// optional function which returns a boolean
// that determines whether codeit should auto-add a tab
// on current enter key press
shouldAutoTabFunc: false
};
// if edit property is true
cd.edit = (cd.getAttribute('edit') == 'false') ? false : true;
if (cd.edit) {
// make codeit editable
cd.setAttribute('contenteditable', 'plaintext-only');
cd.setAttribute('spellcheck', 'false');
cd.setAttribute('autocorrect', 'off');
cd.setAttribute('autocomplete', 'off');
cd.setAttribute('aria-autocomplete', 'list');
cd.setAttribute('autocapitalize', 'off');
cd.setAttribute('data-gramm', 'false');
cd.setAttribute('enterkeyhint', 'enter');
}
// create codeit custom events
const typeEvent = new CustomEvent('type');
const caretMoveEvent = new CustomEvent('caretmove');
// highlight codeit
cd.highlight = async (lang) => {
// change codeit class to given language
const prefix = 'language-';
const classes = cd.className.split(' ').filter(c => !c.startsWith(prefix));
cd.className = classes.join(' ').trim();
if (lang != null) cd.classList.add('language-' + lang);
else cd.classList.add('language-plain');
const textToHighlight = cd.textContent;
if (textToHighlight && textToHighlight !== '' && textToHighlight !== '\n'
&& lang !== 'none' && lang !== 'plain') {
// if language isn't loaded
if (!isLangLoaded(lang)) {
// load language
await new Promise(resolve => {
try {
Prism.plugins.autoloader.loadLanguages(lang, resolve, resolve);
} catch(e) {
resolve();
}
});
}
const highlightHTML = cd.highlightText(lang, textToHighlight);
// if could highlight text
if (highlightHTML !== false) {
cd.innerHTML = highlightHTML;
Prism.hooks.run('complete', { element: cd });
}
}
}
cd.highlightText = (lang, text) => {
if (!isLangLoaded(lang)) return false;
const grammar = Prism.languages[lang];
const highlightHTML = Prism.highlight(text,
grammar,
lang);
return highlightHTML;
}
// returns whether the given language is currently loaded.
function isLangLoaded(lang) {
if (lang in Prism.languages) {
// the given language is already loaded
return true;
}
}
let highlightTimeout;
function debounceHighlight() {
if (cd.textContent && cd.textContent !== '') {
// if text is big, highlight cursor node first,
// then highlight rest of codeit when finished typing
if (cd.textContent.length > 5000 &&
document.activeElement === cd) {
// get caret pos in text
const pos = cd.getSelection();
// highlight cursor node
highlightCursorNode();
// restore pos in text
cd.setSelection(pos.start, pos.end);
// clear highlight timeout
if (highlightTimeout) window.clearTimeout(highlightTimeout);
// set new timeout
highlightTimeout = window.setTimeout(() => {
// get caret pos in text
const pos = cd.getSelection();
// highlight codeit
cd.highlight(cd.lang);
// restore pos in text
cd.setSelection(pos.start, pos.end);
}, 420);
} else if (document.activeElement === cd) {
// get caret pos in text
const pos = cd.getSelection();
cd.highlight(cd.lang);
// restore pos in text
cd.setSelection(pos.start, pos.end);
} else {
cd.highlight(cd.lang);
}
} else {
cd.textContent = '\n';
}
}
// highlight cursor node
function highlightCursorNode() {
const cursor = cd.dropper.cursor();
let elToHighlight = cursor.startContainer;
let textToHighlight;
if (elToHighlight !== cd) {
if (!String(elToHighlight.parentElement.classList).includes('language-')) {
elToHighlight = elToHighlight.parentElement;
textToHighlight = elToHighlight.textContent;
} else {
textToHighlight = elToHighlight.nodeValue;
}
if (textToHighlight !== '') {
let highlightLang = Prism.util.getLanguage(elToHighlight);
if (highlightLang === 'none') highlightLang = 'plain';
let highlightHTML = Prism.highlight(textToHighlight,
Prism.languages[highlightLang],
highlightLang);
const frag = createHTMLFrag(highlightHTML);
elToHighlight.replaceWith(frag);
}
} else {
cd.highlight(cd.lang);
}
}
function createHTMLFrag(htmlStr) {
var frag = document.createDocumentFragment(),
temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
}
cd.history = {};
cd.history.records = [];
cd.history.pos = -1;
cd.history.recording = false;
function shouldRecord(event) {
return (
!isUndo(event) && !isRedo(event)
&& event.key !== 'Meta'
&& event.key !== 'Control'
&& event.key !== 'Alt'
&& event.key !== 'Shift'
&& event.key !== 'CapsLock'
&& event.key !== 'Escape'
&& !event.key.startsWith('Arrow')
&& !isCtrl(event)
);
}
cd.typed = (event) => {
return (
event &&
event.key &&
event.key !== 'Meta'
&& event.key !== 'Control'
&& event.key !== 'Alt'
&& event.key !== 'Shift'
&& event.key !== 'CapsLock'
&& event.key !== 'Escape'
&& !event.key.startsWith('Arrow')
&& (isCtrl(event) ?
(isUndo(event) || isRedo(event)
|| event.key === 'x' || event.key === 'v') : true)
);
}
cd.on = (events, callback, passive) => {
events.split(' ').forEach(evt => {
cd.addEventListener(evt, callback, passive);
});
}
function onNextFrame(func) {
window.requestAnimationFrame(func);
}
function debounce(func, time) {
window.setTimeout(func, time);
}
// create a new instance of 'MutationObserver',
// passing it a callback function
const textContentObserver = new MutationObserver(function(mutationsList, observer) {
cd.update();
});
const innerHTMLObserver = new MutationObserver(function(mutationsList, observer) {
cd.update();
});
// call 'observe' on that MutationObserver instance,
// passing it the element to observe, and the options object
const textContentConfig = { characterData: false, attributes: false, childList: true, subtree: false };
textContentObserver.observe(cd, textContentConfig);
const innerHTMLConfig = { characterData: true, attributes: false, childList: false, subtree: true };
innerHTMLObserver.observe(cd, innerHTMLConfig);
if (cd.edit) {
cd.on('keydown', (event) => {
// get current selection
const s = window.getSelection();
// if selection is empty
if (s.isCollapsed) {
if (cd.options.preserveIdent) handleNewLine(event);
if (cd.options.addClosing) handleDelClosingCharacters(event);
if (cd.options.preserveIdent) handleDelNewLine(event);
if (cd.options.preserveIdent) alignBracket(event);
}
if (cd.options.catchTab) handleTabCharacters(event);
if (cd.options.addClosing) handleSelfClosingCharacters(event);
if (cd.options.history) {
handleUndoRedo(event);
if (shouldRecord(event) && !cd.history.recording) {
recordHistory();
cd.history.recording = true;
}
}
overrideDeleteText(event);
});
cd.on('keyup', (event) => {
if (shouldRecord(event) && cd.history.recording) {
onNextFrame(recordHistory);
cd.history.recording = false;
}
});
cd.on('keydown mousedown mouseup touchstart touchend focus blur cut paste',
(e) => { onNextFrame(() => { checkCaretMoveEvent(e) }) }, false);
cd.on('cut', (e) => {
const selection = window.getSelection();
if (!selection.rangeCount) return false;
if (selection.getRangeAt(0).collapsed) return false;
const text = window.getSelection().toString();
e.clipboardData.setData('text/plain', text);
recordHistory();
cd.deleteCurrentSelection();
recordHistory();
e.preventDefault();
});
cd.on('copy', (e) => {
e.preventDefault();
const text = window.getSelection().toString();
if (text === '') return false;
e.clipboardData.setData('text/plain', text);
});
cd.on('paste', (e) => {
e.preventDefault();
let paste = e.clipboardData.getData('text');
if (paste === '') return false;
const selection = window.getSelection();
if (!selection.rangeCount) return false;
if (!selection.getRangeAt(0).collapsed &&
hashCode(paste) === hashCode(selection.toString())) {
selection.getRangeAt(0).collapse();
return false;
}
recordHistory();
// if selection isn't collapsed, delete it
if (!selection.getRangeAt(0).collapsed) {
cd.deleteCurrentSelection();
}
cd.insert(paste);
recordHistory();
});
}
// IDE-style behaviors
function handleNewLine(event) {
if (event.key === 'Enter') {
// check if should auto tab
if (cd.options.shouldAutoTabFunc) {
const shouldAutoTab = cd.options.shouldAutoTabFunc();
if (!shouldAutoTab) return;
}
const before = cd.beforeCursor();
const after = cd.afterCursor();
let [padding] = getPadding(before);
let newLinePadding = padding;
const charBefore = before.slice(-1);
const charAfter = after.charAt(0);
// if char before caret is opening bracket
// and char after is closing bracket indent new line
let bracketOne = (cd.options.openBrackets.includes(charBefore));
let bracketTwo = (charAfter ===
cd.options.closeBrackets[ cd.options.openBrackets.indexOf( charBefore ) ]);
let newLineBracket = (charBefore === '{' &&
[closingBracketNextToCursor(after)] );
if (bracketOne && (bracketTwo || newLineBracket)) {
// indent new line
newLinePadding += cd.options.tab;
if (bracketTwo) {
// get caret pos in text
const pos = cd.getSelection();
// move adjacent "}" down one line
cd.insert('\n' + padding, { moveToEnd: false });
}
}
if (cd.lang === 'python' && charBefore === ':') {
// indent new line
newLinePadding += cd.options.tab;
}
if (newLinePadding) {
event.preventDefault();
cd.insert('\n' + newLinePadding);
}
}
}
function handleDelNewLine(event) {
if (event.key === 'Backspace') {
const before = cd.beforeCursor();
let [padding, start] = getPadding(before);
if (padding.length > 0) {
// get caret pos in text
let pos = cd.getSelection();
// if selection is empty and caret is next to tabs
if (pos.start === pos.end && (start + padding.length) === pos.start) {
for (let i = 0; i < padding.length; i++) cd.deleteCurrentSelection();
}
}
}
}
function handleTabCharacters(event) {
if (event.key === 'Tab') {
event.preventDefault();
if (event.shiftKey) {
// get current selection
const s = window.getSelection();
let selContents = s.toString();
// if selection exists
if (!s.isCollapsed) {
let lines = selContents.split('\n');
// run on all lines
lines.forEach((line, index) => {
// if line contains a tab
if (line.startsWith(cd.options.tab)) {
// remove tab from line
lines[index] = line.slice(cd.options.tab.length);
}
});
// join lines
selContents = lines.join('\n');
// delete selection
cd.deleteCurrentSelection();
// insert un-tabbed selection
cd.insert(selContents, { moveToEnd: false });
// get caret pos in text
const pos = cd.getSelection();
// restore pos in text
cd.setSelection(pos.start, (pos.start + selContents.length));
} else {
let lastLine = cd.beforeCursor().split('\n');
lastLine = lastLine[lastLine.length-1];
// if current line contains a tab
if (lastLine.startsWith(cd.options.tab)) {
// remove tab from line
// get caret pos in text
const pos = cd.getSelection();
// select the tab
cd.setSelection((pos.start - lastLine.length), (pos.start - lastLine.length + cd.options.tab.length));
// delete selection
cd.deleteCurrentSelection();
// restore pos in text
cd.setSelection(pos.start - cd.options.tab.length);
}
}
} else {
// get current selection
const s = window.getSelection();
let selContents = s.toString();
// if selection exists
if (!s.isCollapsed) {
if (selContents.includes('\n')) {
// add tabs to selection string
selContents = cd.options.tab + selContents.split('\n').join('\n' + cd.options.tab);
// delete selection
cd.deleteCurrentSelection();
// insert tabbed selection
cd.insert(selContents, { moveToEnd: false });
// get caret pos in text
const pos = cd.getSelection();
// restore pos in text
cd.setSelection(pos.start, (pos.start + selContents.length));
} else {
// tab selection
// get caret pos in text
const pos = cd.getSelection();
const start = Math.min(pos.start, pos.end);
const end = Math.max(pos.start, pos.end);
cd.setSelection(start);
// insert tab at start of selection
cd.insert(cd.options.tab, { moveToEnd: false });
// restore pos in text
cd.setSelection(start, end + cd.options.tab.length);
}
} else {
// insert tab on current line
cd.insert(cd.options.tab);
}
}
}
}
function handleSelfClosingCharacters(event) {
const cursor = cd.dropper.cursor();
// join brackets and quotation marks
// to get chars to autocomplete
const open = cd.options.openBrackets.join('') + cd.options.quot.join('');
const close = cd.options.closeBrackets.join('') + cd.options.quot.join('');
// get code before and after cursor
const codeAfter = cd.afterCursor();
const codeBefore = cd.beforeCursor();
const charBefore = codeBefore.slice(-1);
const charAfter = codeAfter.charAt(0);
// check if typed an opening or closing char
const typedOpeningChar = open.includes(event.key);
const typedClosingChar = close.includes(event.key);
// closing char is next to cursor if
// the chars before and after the cursor are
// matching opening and closing chars
const closingCharNextToCursor = (charBefore === open[close.indexOf(event.key)]
&& charAfter === event.key);
// if typed opening char
if (typedOpeningChar) {
// if selection exists
if (!cursor.collapsed) {
// prevent default behavior
event.preventDefault();
// get the text to wrap
const textToWrap = window.getSelection().toString();
// wrap the text with matching opening and closing chars
const wrappedText = event.key + textToWrap + close[open.indexOf(event.key)];
// delete current selection
cd.deleteCurrentSelection();
// insert wrapped text
cd.insert(wrappedText, { moveToEnd: false });
// get caret pos in text
const pos = cd.getSelection();
// restore pos in text
cd.setSelection(pos.start, (pos.start + wrappedText.length));
} else {
// get caret pos in text
const pos = cd.getSelection();
// if cursor is on last line
if (pos.start === cd.textContent.length) {
// insert newline
cd.insert((close[open.indexOf(event.key)] + '\n'), { moveToEnd: false });
} else {
// insert matching closing char
cd.insert(close[open.indexOf(event.key)], { moveToEnd: false });
}
}
}
// if typed closing char but closing char
// is already next to cursor
if (typedClosingChar && closingCharNextToCursor) {
// prevent default behavior
event.preventDefault();
// get caret pos in text
const pos = cd.getSelection();
// move caret one char right
pos.start++;
cd.setSelection(pos.start);
}
}
function handleDelClosingCharacters(event) {
if (event.key === 'Backspace') {
const open = cd.options.openBrackets.join('') + cd.options.quot.join('');
const close = cd.options.closeBrackets.join('') + cd.options.quot.join('');
const codeAfter = cd.afterCursor();
const codeBefore = cd.beforeCursor();
const charBefore = codeBefore.slice(-1);
const charAfter = codeAfter.charAt(0);
let closeCharAdjacent = false;
let closeCharWhitespace = false;
let closeCharPadding = 0;
// if the char before is not an opening bracket
if (charBefore !== '{') {
// check if a closing char is nearby
closeCharAdjacent = (
close.includes(charAfter)
&& charBefore === open[close.indexOf(charAfter)]
);
} else { // if the char before is an opening bracket
// check if a closing bracket is nearby
[closeCharWhitespace, closeCharPadding] = closingBracketNextToCursor(codeAfter);
}
// get caret pos in text
const pos = cd.getSelection();
if ((closeCharAdjacent || closeCharWhitespace)
&& pos.start === pos.end) {
// delete chars after
if (closeCharWhitespace) {
cd.setSelection(pos.start, pos.start + closeCharPadding);
} else { // delete char after
cd.setSelection(pos.start + 1);
}
cd.deleteCurrentSelection();
}
}
}
// check if next line contains bracket
function closingBracketNextToCursor(text) {
// check if this line contains closing bracket
let i = 0;
while (i < text.length && text[i] !== '\n' && text[i] !== '}') {
// if there's text between the brackets, return false
if (text[i] !== ' ' && text[i] !== '\t') return [false, 0];
i++;
}
// if this line contains closing bracket, return its location
if (text[i] === '}') return [true, i+1];
// find beginning of next line
while (i < text.length && text[i] !== '\n') i++;
i++;
// check if next line contains bracket
while (i < text.length && text[i] !== '\n' && text[i] !== '}') i++;
return [(text[i] === '}'), i+1];
}
function alignBracket(event) {
// if typed a closing bracket
if (event.key === '}') {
const textBefore = cd.beforeCursor();
// if bracket pair is a one-liner, return
if (isOneLiner(textBefore)) return;
// run on all text to cursor, and find the matching padding
let bracketArr = [];
let i = 0;
while (textBefore.length > 0 && (i < textBefore.length)) {
if (textBefore[i] == '{') {
const bracketRange = cd.dropper.atTextPos(i);
if (bracketRange.in('punctuation')) {
const textBeforeBracket = textBefore.substr(0, i);
const [padding] = getPadding(textBeforeBracket);
bracketArr.push(padding);
}
bracketRange.detach();
} else if (textBefore[i] == '}') {
const bracketRange = cd.dropper.atTextPos(i);
if (bracketRange.in('punctuation')) {
bracketArr.pop();
}
bracketRange.detach();
}
i++;
}
if (bracketArr.length > 0) {
const newPadding = bracketArr[bracketArr.length-1];
const [oldPadding, startPos] = getPadding(textBefore);
// remove old padding
cd.setSelection(startPos, startPos + oldPadding.length);
cd.deleteCurrentSelection();
// insert new padding
cd.insert(newPadding);
}
}
}
// check if there's text
// on the same line as closing bracket
function isOneLiner(text) {
// go back text and stop when encountered
// a char that isn't a space or a tab
let i = text.length - 1;
while (i >= 0 && (text[i] === ' ' || text[i] === '\t')) i--;
return (text[i] !== '\n' || text[text.length - 1] === '\n');