-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathcode-input.js
More file actions
1469 lines (1329 loc) · 66.1 KB
/
code-input.js
File metadata and controls
1469 lines (1329 loc) · 66.1 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
/**
* **code-input** is a library which lets you create custom HTML `<code-input>`
* elements that act like `<textarea>` elements but support syntax-highlighted
* code, implemented using any typical syntax highlighting library.
*
* License of whole library for bundlers:
*
* Copyright 2021-2025 Oliver Geer and contributors
* @license MIT
*
* **<https://code-input-js.org>**
*/
"use strict";
var codeInput = {
/**
* A list of attributes that will trigger functionality in the
* `codeInput.CodeInput.attributeChangedCallback`
* when modified in a code-input element. This
* does not include events, which are handled in
* `codeInput.CodeInput.addEventListener` and
* `codeInput.CodeInput.removeEventListener`.
*
* This does not include those listed in `codeInput.textareaSyncAttributes` that only synchronise with the textarea element.
*/
observedAttributes: [
"value",
"placeholder",
"language",
"lang",
"template"
],
/**
* A list of attributes that will be moved to
* the textarea after they are applied on the
* code-input element.
*/
textareaSyncAttributes: [
"value",
// Form validation - https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation#using_built-in_form_validation
"min", "max",
"type",
"pattern",
// Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea
"autocomplete",
"autocorrect",
"autofocus",
"cols",
"dirname",
"disabled",
"form",
"maxlength",
"minlength",
"name",
"placeholder",
"readonly",
"required",
"rows",
"spellcheck",
"wrap"
],
/**
* A list of events whose listeners will be moved to
* the textarea after they are added to the
* code-input element.
*/
textareaSyncEvents: [
"change",
"selectionchange",
"invalid",
"input",
"focus",
"blur",
"focusin",
"focusout"
],
/* ------------------------------------
* ------------Templates---------------
* ------------------------------------ */
/**
* The templates currently available for any code-input elements
* to use. Registered using `codeInput.registerTemplate`.
* Key - Template Name
* Value - A Template Object
* @type {Object}
*/
usedTemplates: {
},
/**
* The name of the default template that a code-input element that
* does not specify the template attribute uses.
* @type {string}
*/
defaultTemplate: undefined,
/**
* A queue of elements waiting for a template to be registered,
* allowing elements to be created in HTML with a template before
* the template is registered in JS, for ease of use.
* Key - Template Name
* Value - An array of code-input elements
* @type {Object}
*/
templateNotYetRegisteredQueue: {},
/**
* Register a template so code-input elements with a template attribute that equals the templateName will use the template.
* See `codeInput.templates` for constructors to create templates.
* @param {string} templateName - the name to register the template under
* @param {Object} template - a Template object instance - see `codeInput.templates`
*/
registerTemplate: function (templateName, template) {
if(!(typeof templateName == "string" || templateName instanceof String)) throw TypeError(`code-input: Name of template "${templateName}" must be a string.`);
if(!(typeof template.highlight == "function" || template.highlight instanceof Function)) throw TypeError(`code-input: Template for "${templateName}" invalid, because the highlight function provided is not a function; it is "${template.highlight}". Please make sure you use one of the constructors in codeInput.templates, and that you provide the correct arguments.`);
if(!(typeof template.includeCodeInputInHighlightFunc == "boolean" || template.includeCodeInputInHighlightFunc instanceof Boolean)) throw TypeError(`code-input: Template for "${templateName}" invalid, because the includeCodeInputInHighlightFunc value provided is not a true or false; it is "${template.includeCodeInputInHighlightFunc}". Please make sure you use one of the constructors in codeInput.templates, and that you provide the correct arguments.`);
if(!(typeof template.preElementStyled == "boolean" || template.preElementStyled instanceof Boolean)) throw TypeError(`code-input: Template for "${templateName}" invalid, because the preElementStyled value provided is not a true or false; it is "${template.preElementStyled}". Please make sure you use one of the constructors in codeInput.templates, and that you provide the correct arguments.`);
if(!(typeof template.isCode == "boolean" || template.isCode instanceof Boolean)) throw TypeError(`code-input: Template for "${templateName}" invalid, because the isCode value provided is not a true or false; it is "${template.isCode}". Please make sure you use one of the constructors in codeInput.templates, and that you provide the correct arguments.`);
if(!Array.isArray(template.plugins)) throw TypeError(`code-input: Template for "${templateName}" invalid, because the plugin array provided is not an array; it is "${template.plugins}". Please make sure you use one of the constructors in codeInput.templates, and that you provide the correct arguments.`);
template.plugins.forEach((plugin, i) => {
if(!(plugin instanceof codeInput.Plugin)) {
throw TypeError(`code-input: Template for "${templateName}" invalid, because the plugin provided at index ${i} is not valid; it is "${template.plugins[i]}". Please make sure you use one of the constructors in codeInput.templates, and that you provide the correct arguments.`);
}
});
codeInput.usedTemplates[templateName] = template;
// Add waiting code-input elements wanting this template from queue
if (templateName in codeInput.templateNotYetRegisteredQueue) {
for (let i in codeInput.templateNotYetRegisteredQueue[templateName]) {
const elem = codeInput.templateNotYetRegisteredQueue[templateName][i];
elem.templateObject = template;
elem.setup();
}
}
if (codeInput.defaultTemplate == undefined) {
codeInput.defaultTemplate = templateName;
// Add elements with default template from queue
if (undefined in codeInput.templateNotYetRegisteredQueue) {
for (let i in codeInput.templateNotYetRegisteredQueue[undefined]) {
const elem = codeInput.templateNotYetRegisteredQueue[undefined][i];
elem.templateObject = template;
elem.setup();
}
}
}
},
stylesheetI: 0, // Increments to give different classes to each code-input element so they can have custom styles synchronised internally without affecting the inline style
/**
* Please see `codeInput.templates.prism` or `codeInput.templates.hljs`.
* Templates are used in `<code-input>` elements and once registered with
* `codeInput.registerTemplate` will be in charge of the highlighting
* algorithm and settings for all code-inputs with a `template` attribute
* matching the registered name.
*/
Template: class {
/**
* Constructor to create a custom template instance. Pass this into `codeInput.registerTemplate` to use it.
* I would strongly recommend using the built-in simpler template `codeInput.templates.prism` or `codeInput.templates.hljs`.
* @param {(codeElement: HTMLCodeElement, codeInput?: codeInput.CodeInput) => void} highlight - a callback to highlight the code, that takes an HTML `<code>` element inside a `<pre>` element as a parameter
* @param {boolean} preElementStyled - is the `<pre>` element CSS-styled (if so set to true), or the `<code>` element (false)?
* @param {boolean} isCode - is this for writing code? If true, the code-input's lang HTML attribute can be used, and the `<code>` element will be given the class name 'language-[lang attribute's value]'.
* @param {boolean} includeCodeInputInHighlightFunc - Setting this to true passes the `<code-input>` element as a second argument to the highlight function.
* @param {codeInput.Plugin[]} plugins - An array of plugin objects to add extra features - see `codeInput.Plugin`
* @returns {codeInput.Template} template object
*/
constructor(highlight = function (codeElement) { }, preElementStyled = true, isCode = true, includeCodeInputInHighlightFunc = false, plugins = []) {
this.highlight = highlight;
this.preElementStyled = preElementStyled;
this.isCode = isCode;
this.includeCodeInputInHighlightFunc = includeCodeInputInHighlightFunc;
this.plugins = plugins;
}
/**
* A callback to highlight the code, that takes an HTML `<code>` element
* inside a `<pre>` element as a parameter, and an optional second
* `<code-input>` element parameter if `this.includeCodeInputInHighlightFunc` is
* `true`.
*/
highlight = function(codeElement) {};
/**
* Is the <pre> element CSS-styled as well as the `<code>` element?
* If `true`, `<pre>` element's scrolling is synchronised; if false,
* <code> element's scrolling is synchronised.
*/
preElementStyled = true;
/**
* Is this for writing code?
* If true, the code-input's lang HTML attribute can be used,
* and the `<code>` element will be given the class name
* 'language-[lang attribute's value]'.
*/
isCode = true;
/**
* Setting this to true passes the `<code-input>` element as a
* second argument to the highlight function.
*/
includeCodeInputInHighlightFunc = false;
/**
* An array of plugin objects to add extra features -
* see `codeInput.Plugin`.
*/
plugins = [];
},
// ESM-SUPPORT-START-TEMPLATES-BLOCK-1 Do not (re)move this - it's needed for ESM generation!
/**
* For creating a custom template from scratch, please
* use `new codeInput.Template(...)`
*
* Shortcut functions for creating templates.
* Each code-input element has a template attribute that
* tells it which template to use.
* Each template contains functions and preferences that
* run the syntax-highlighting and let code-input control
* the highlighting.
* For adding small pieces of functionality, please see `codeInput.plugins`.
*/
templates: {
// (Source code for class templates after var codeInput = ... so they can extend the codeInput.Template class)
/**
* @deprecated Please use `new codeInput.templates.Prism(...)`
*/
prism(prism, plugins = []) { // Dependency: Prism.js (https://prismjs.com/)
return new codeInput.templates.Prism(prism, plugins);
},
/**
* @deprecated Please use `new codeInput.templates.Hljs(...)`
*/
hljs(hljs, plugins = []) { // Dependency: Highlight.js (https://highlightjs.org/)
return new codeInput.templates.Hljs(hljs, plugins);
},
/**
* @deprecated Make your own version of this template if you need it - we think it isn't widely used so will remove it from the next version of code-input.
*/
characterLimit(plugins) {
return {
highlight: function (resultElement, codeInput, plugins = []) {
let characterLimit = Number(codeInput.getAttribute("data-character-limit"));
let normalCharacters = codeInput.escapeHtml(codeInput.value.slice(0, characterLimit));
let overflowCharacters = codeInput.escapeHtml(codeInput.value.slice(characterLimit));
resultElement.innerHTML = `${normalCharacters}<mark class="overflow">${overflowCharacters}</mark>`;
if (overflowCharacters.length > 0) {
resultElement.innerHTML += ` <mark class="overflow-msg">${codeInput.getAttribute("data-overflow-msg") || "(Character limit reached)"}</mark>`;
}
},
includeCodeInputInHighlightFunc: true,
preElementStyled: true,
isCode: false,
plugins: plugins,
}
},
/**
* @deprecated Make your own version of this template if you need it - we think it isn't widely used so will remove it from the next version of code-input.
*/
rainbowText(rainbowColors = ["red", "orangered", "orange", "goldenrod", "gold", "green", "darkgreen", "navy", "blue", "magenta"], delimiter = "", plugins = []) {
return {
highlight: function (resultElement, codeInput) {
let htmlResult = [];
let sections = codeInput.value.split(codeInput.template.delimiter);
for (let i = 0; i < sections.length; i++) {
htmlResult.push(`<span style="color: ${codeInput.template.rainbowColors[i % codeInput.template.rainbowColors.length]}">${codeInput.escapeHtml(sections[i])}</span>`);
}
resultElement.innerHTML = htmlResult.join(codeInput.template.delimiter);
},
includeCodeInputInHighlightFunc: true,
preElementStyled: true,
isCode: false,
rainbowColors: rainbowColors,
delimiter: delimiter,
plugins: plugins,
}
},
/**
* @deprecated Make your own version of this template if you need it - we think it isn't widely used so will remove it from the next version of code-input.
*/
character_limit() {
return this.characterLimit([]);
},
/**
* @deprecated Make your own version of this template if you need it - we think it isn't widely used so will remove it from the next version of code-input.
*/
rainbow_text(rainbowColors = ["red", "orangered", "orange", "goldenrod", "gold", "green", "darkgreen", "navy", "blue", "magenta"], delimiter = "", plugins = []) {
return this.rainbowText(rainbowColors, delimiter, plugins);
},
/**
* @deprecated Please use `new codeInput.Template(...)`
*/
custom(highlight = function () { }, preElementStyled = true, isCode = true, includeCodeInputInHighlightFunc = false, plugins = []) {
return {
highlight: highlight,
includeCodeInputInHighlightFunc: includeCodeInputInHighlightFunc,
preElementStyled: preElementStyled,
isCode: isCode,
plugins: plugins,
};
},
},
// ESM-SUPPORT-END-TEMPLATES-BLOCK-1 Do not (re)move this - it's needed for ESM generation!
/* ------------------------------------
* ------------Plugins-----------------
* ------------------------------------ */
/**
* Before using any plugin in this namespace, please ensure you import its JavaScript
* files (in the plugins folder), or continue to get a more detailed error in the developer
* console.
*
* Where plugins are stored, after they are imported. The plugin
* file assigns them a space in this object.
* For adding completely new syntax-highlighting algorithms, please see `codeInput.templates`.
*
* Key - plugin name
*
* Value - plugin object
* @type {Object}
*/
plugins: new Proxy({}, {
get(plugins, name) {
if(plugins[name] == undefined) {
throw ReferenceError(`code-input: Plugin '${name}' is not defined. Please ensure you import the necessary files from the plugins folder in the WebCoder49/code-input repository, in the <head> of your HTML, before the plugin is instatiated.`);
}
return plugins[name];
}
}),
/**
* Plugins are imported from the plugins folder. They will then
* provide custom extra functionality to code-input elements.
*/
Plugin: class {
/**
* Create a Plugin
*
* @param {Array<string>} observedAttributes - The HTML attributes to watch for this plugin, and report any
* modifications to the `codeInput.Plugin.attributeChanged` method.
*/
constructor(observedAttributes) {
observedAttributes.forEach((attribute) => {
codeInput.observedAttributes.push(attribute);
});
}
/**
* Replace the values in destination with those from source where the keys match, in-place.
* @param {Object} destination Where to place the translated strings, already filled with the keys pointing to English strings.
* @param {Object} source The same keys, or some of them, mapped to translated strings. Keys not present here will retain the values they are maapped to in destination.
*/
addTranslations(destination, source) {
for(const key in source) {
destination[key] = source[key];
}
}
/**
* Runs before code is highlighted.
* @param {codeInput.CodeInput} codeInput - The codeInput element
*/
beforeHighlight(codeInput) { }
/**
* Runs after code is highlighted.
* @param {codeInput.CodeInput} codeInput - The codeInput element
*/
afterHighlight(codeInput) { }
/**
* Runs before elements are added into a code-input element.
* @param {codeInput.CodeInput} codeInput - The codeInput element
*/
beforeElementsAdded(codeInput) { }
/**
* Runs after elements are added into a code-input element (useful for adding events to the textarea).
* @param {codeInput.CodeInput} codeInput - The codeInput element
*/
afterElementsAdded(codeInput) { }
/**
* Runs when an attribute of a code-input element is changed (you must add the attribute name to `codeInput.Plugin.observedAttributes` first).
* @param {codeInput.CodeInput} codeInput - The codeInput element
* @param {string} name - The name of the attribute
* @param {string} oldValue - The value of the attribute before it was changed
* @param {string} newValue - The value of the attribute after it is changed
*/
attributeChanged(codeInput, name, oldValue, newValue) { }
},
/* ------------------------------------
* -------------Main-------------------
* ------------------------------------ */
/**
* A `<code-input>` element, an instance of an `HTMLElement`, and the result
* of `document.createElement("code-input")`. Attributes are only set when
* the element's template has been registered, and before this are null.
*/
CodeInput: class extends HTMLElement {
constructor() {
super(); // Element
}
/**
* When the code-input's template is registered, this contains its codeInput.Template object.
* Should be treated as read-only by external code.
*/
templateObject = null;
/**
* Exposed child textarea element for user to input code in
*/
textareaElement = null;
/**
* Exposed child pre element where syntax-highlighted code is outputted.
* Contains this.codeElement as its only child.
*/
preElement = null
/**
* Exposed child pre element's child code element where syntax-highlighted code is outputted.
* Has this.preElement as its parent.
*/
codeElement = null;
/**
* Exposed non-scrolling element designed to contain dialog boxes etc. from plugins,
* that shouldn't scroll with the code-input element.
*/
dialogContainerElement = null;
/**
* Like style attribute, but with a specificity of 1
* element, 1 class. Present so styles can be set on only
* this element while giving other code freedom of use of
* the style attribute.
*
* For internal use only.
*/
internalStyle = null;
/**
* Form-Associated Custom Element Callbacks
* https://html.spec.whatwg.org/multipage/custom-elements.html#custom-elements-face-example
*/
static formAssociated = true;
/**
* When events are transferred to the textarea element, callbacks
* are bound to set the this variable to the code-input element
* rather than the textarea. This allows the callback to be converted
* to a bound one:
* Key - Callback not bound
* Value - Callback that is bound, with this equalling the code-input element in the callback
*/
boundEventCallbacks = {};
/** Trigger this event in all plugins with a optional list of arguments
* @param {string} eventName - the name of the event to trigger
* @param {Array} args - the arguments to pass into the event callback in the template after the code-input element. Normally left empty
*/
pluginEvt(eventName, args) {
for (let i in this.templateObject.plugins) {
let plugin = this.templateObject.plugins[i];
if (eventName in plugin) {
if (args === undefined) {
plugin[eventName](this);
} else {
plugin[eventName](this, ...args);
}
}
}
}
/* ------------------------------------
* ----------Main Functionality--------
* ------------------------------------
* The main function of a code-input element is to take
* code written in its textarea element, copy this code into
* the result (pre code) element, then use the template object
* to syntax-highlight it. */
needsHighlight = false; // Just inputted
originalAriaDescription;
/**
* Highlight the code as soon as possible
*/
scheduleHighlight() {
this.needsHighlight = true;
}
/**
* Call an animation frame
*/
animateFrame() {
// Synchronise the contents of the pre/code and textarea elements
if(this.needsHighlight) {
this.update();
this.needsHighlight = false;
}
window.requestAnimationFrame(this.animateFrame.bind(this));
}
/**
* Update the text value to the result element, after the textarea contents have changed.
*/
update() {
let resultElement = this.codeElement;
let value = this.value;
value += "\n"; // Placeholder for next line
// Update code
resultElement.innerHTML = this.escapeHtml(value);
this.pluginEvt("beforeHighlight");
// Syntax Highlight
if (this.templateObject.includeCodeInputInHighlightFunc) this.templateObject.highlight(resultElement, this);
else this.templateObject.highlight(resultElement);
this.syncSize();
this.pluginEvt("afterHighlight");
}
getStyledHighlightingElement() {
if(this.templateObject.preElementStyled) {
return this.preElement;
} else {
return this.codeElement;
}
}
/**
* Set the size of the textarea element to the size of the pre/code element.
*/
syncSize() {
// Synchronise the size of the pre/code and textarea elements
// Set directly as well as via the variable so precedence
// not lowered, breaking CSS backwards compatibility.
const height = getComputedStyle(this.getStyledHighlightingElement()).height;
this.textareaElement.style.height = height;
this.internalStyle.setProperty("--code-input_synced-height", height);
const width = getComputedStyle(this.getStyledHighlightingElement()).width;
this.textareaElement.style.width = width;
this.internalStyle.setProperty("--code-input_synced-width", width);
}
/**
* If the color attribute has been defined on the
* code-input element by external code, run the callback
* provided.
* Otherwise, make the aspects the color affects
* (placeholder and caret colour) be the base colour
* of the highlighted text, for best contrast.
*/
syncIfColorNotOverridden(callbackIfOverridden=function() {}) {
if(this.checkingColorOverridden) return;
this.checkingColorOverridden = true;
const oldTransition = this.style.transition;
this.style.transition = "unset";
window.requestAnimationFrame(() => {
this.internalStyle.setProperty("--code-input_no-override-color", "rgb(0, 0, 0)");
if(getComputedStyle(this).color == "rgb(0, 0, 0)") {
// May not be overriden
this.internalStyle.setProperty("--code-input_no-override-color", "rgb(255, 255, 255)");
if(getComputedStyle(this).color == "rgb(255, 255, 255)") {
// Definitely not overriden
this.internalStyle.removeProperty("--code-input_no-override-color");
console.log(this, "Autoadapt; " + oldTransition);
this.style.transition = oldTransition;
const highlightedTextColor = getComputedStyle(this.getStyledHighlightingElement()).color;
this.internalStyle.setProperty("--code-input_highlight-text-color", highlightedTextColor);
this.internalStyle.setProperty("--code-input_default-caret-color", highlightedTextColor);
this.checkingColorOverridden = false;
} else {
this.style.transition = oldTransition;
this.checkingColorOverridden = false;
callbackIfOverridden();
}
} else {
this.style.transition = oldTransition;
this.checkingColorOverridden = false;
callbackIfOverridden();
}
this.internalStyle.removeProperty("--code-input_no-override-color");
console.log(this, "No autoadapt; " + oldTransition);
this.style.transition = oldTransition;
});
}
/**
* Update the aspects the color affects
* (placeholder and caret colour) to the correct
* colour: either that defined on the code-input
* element, or if none is defined externally the
* base colour of the highlighted text.
*/
syncColorCompletely() {
// color of code-input element
this.syncIfColorNotOverridden(() => {
// color overriden
this.internalStyle.removeProperty("--code-input_highlight-text-color");
this.internalStyle.setProperty("--code-input_default-caret-color", getComputedStyle(this).color);
});
}
/**
* Show some instructions to the user only if they are using keyboard navigation - for example, a prompt on how to navigate with the keyboard if Tab is repurposed.
* @param {string} instructions The instructions to display only if keyboard navigation is being used. If it's blank, no instructions will be shown.
* @param {boolean} includeAriaDescriptionFirst Whether to include the aria-description of the code-input element before the keyboard navigation instructions for a screenreader. Keep this as true when the textarea is first focused.
*/
setKeyboardNavInstructions(instructions, includeAriaDescriptionFirst) {
this.dialogContainerElement.querySelector(".code-input_keyboard-navigation-instructions").innerText = instructions;
if(includeAriaDescriptionFirst) {
this.textareaElement.setAttribute("aria-description", this.originalAriaDescription + ". " + instructions);
} else {
this.textareaElement.setAttribute("aria-description", instructions);
}
}
/**
* HTML-escape an arbitrary string.
* @param {string} text - The original, unescaped text
* @returns {string} - The new, HTML-escaped text
*/
escapeHtml(text) {
return text.replace(new RegExp("&", "g"), "&").replace(new RegExp("<", "g"), "<"); /* Global RegExp */
}
/**
* HTML-unescape an arbitrary string.
* @param {string} text - The original, HTML-escaped text
* @returns {string} - The new, unescaped text
*/
unescapeHtml(text) {
return text.replace(new RegExp("&", "g"), "&").replace(new RegExp("<", "g"), "<").replace(new RegExp(">", "g"), ">"); /* Global RegExp */
}
/**
* Get the template object this code-input element is using.
* @returns {Object} - Template object
*/
getTemplate() {
let templateName;
if (this.getAttribute("template") == undefined) {
// Default
templateName = codeInput.defaultTemplate;
} else {
templateName = this.getAttribute("template");
}
if (templateName in codeInput.usedTemplates) {
return codeInput.usedTemplates[templateName];
} else {
// Doesn't exist - add to queue
if (!(templateName in codeInput.templateNotYetRegisteredQueue)) {
codeInput.templateNotYetRegisteredQueue[templateName] = [];
}
codeInput.templateNotYetRegisteredQueue[templateName].push(this);
return undefined;
}
}
/**
* Set up and initialise the textarea.
* This will be called once the template has been added.
*/
setup() {
if(this.textareaElement != null) return; // Already set up
this.classList.add("code-input_registered");
this.mutationObserver = new MutationObserver(this.mutationObserverCallback.bind(this));
this.mutationObserver.observe(this, {
attributes: true,
attributeOldValue: true
});
this.classList.add("code-input_registered"); // Remove register message
if (this.templateObject.preElementStyled) this.classList.add("code-input_pre-element-styled");
const fallbackTextarea = this.querySelector("textarea[data-code-input-fallback]");
let fallbackFocused = false;
let fallbackSelectionStart = undefined;
let fallbackSelectionEnd = undefined;
let fallbackSelectionDirection = undefined;
let fallbackScrollLeft = undefined;
let fallbackScrollTop = undefined;
if(fallbackTextarea) {
// Move some attributes to new textarea so typing during
// slow load not interrupted
if(fallbackTextarea === document.activeElement) { // Thanks to https://stackoverflow.com/a/36430896
fallbackFocused = true;
}
fallbackSelectionStart = fallbackTextarea.selectionStart;
fallbackSelectionEnd = fallbackTextarea.selectionEnd;
fallbackSelectionDirection = fallbackTextarea.selectionDirection;
fallbackScrollLeft = fallbackTextarea.scrollLeft;
fallbackScrollTop = fallbackTextarea.scrollTop;
}
let value;
if(fallbackTextarea) {
// Fallback textarea exists
// Sync attributes; existing code-input attributes take priority
let textareaAttributeNames = fallbackTextarea.getAttributeNames();
for(let i = 0; i < textareaAttributeNames.length; i++) {
const attr = textareaAttributeNames[i];
if(attr == "data-code-input-fallback") continue;
if(!this.hasAttribute(attr)) {
this.setAttribute(attr, fallbackTextarea.getAttribute(attr));
}
}
// Sync value
value = fallbackTextarea.value;
// Backwards compatibility with plugins
this.innerHTML = this.escapeHtml(value);
} else {
value = this.unescapeHtml(this.innerHTML);
}
value = value || this.getAttribute("value") || "";
this.pluginEvt("beforeElementsAdded");
// First-time attribute sync
const lang = this.getAttribute("language") || this.getAttribute("lang");
const placeholder = this.getAttribute("placeholder") || lang || "";
this.initialValue = value; // For form reset
// Create textarea
const textarea = document.createElement("textarea");
textarea.placeholder = placeholder;
if(value != "") {
textarea.value = value;
}
textarea.innerHTML = this.innerHTML;
if(!this.hasAttribute("spellcheck")) {
// For backwards compatibility:
textarea.setAttribute("spellcheck", "false");
}
// Disable focusing on the code-input element - only allow the textarea to be focusable
textarea.setAttribute("tabindex", this.getAttribute("tabindex") || 0);
this.setAttribute("tabindex", -1);
// Save aria-description so keyboard navigation guidance can be added.
this.originalAriaDescription = this.getAttribute("aria-description") || "Code input field";
// Accessibility - detect when mouse focus to remove focus outline + keyboard navigation guidance that could irritate users.
this.addEventListener("mousedown", () => {
this.classList.add("code-input_mouse-focused");
// Wait for CSS to update padding
window.setTimeout(() => {
this.syncSize();
}, 0);
});
textarea.addEventListener("blur", () => {
this.classList.remove("code-input_mouse-focused");
// Wait for CSS to update padding
window.setTimeout(() => {
this.syncSize();
}, 0);
});
textarea.addEventListener("focus", () => {
// Wait for CSS to update padding
window.setTimeout(() => {
this.syncSize();
}, 0);
});
this.innerHTML = ""; // Clear Content
// Add internal style as non-externally-overridable alternative to style attribute for e.g. syncing color
this.classList.add("code-input_styles_" + codeInput.stylesheetI);
const stylesheet = document.createElement("style");
stylesheet.innerHTML = "code-input.code-input_styles_" + codeInput.stylesheetI + " {}";
this.appendChild(stylesheet);
this.internalStyle = stylesheet.sheet.cssRules[0].style;
codeInput.stylesheetI++;
// Synchronise attributes to textarea
for(let i = 0; i < this.attributes.length; i++) {
let attribute = this.attributes[i].name;
if (codeInput.textareaSyncAttributes.includes(attribute)
|| attribute.substring(0, 5) == "aria-") {
textarea.setAttribute(attribute, this.getAttribute(attribute));
}
}
textarea.addEventListener('input', (evt) => { this.value = this.textareaElement.value; });
// Save element internally
this.textareaElement = textarea;
this.append(textarea);
this.setupTextareaSyncEvents(this.textareaElement);
// Create result element
let code = document.createElement("code");
let pre = document.createElement("pre");
pre.setAttribute("aria-hidden", "true"); // Hide for screen readers
pre.setAttribute("tabindex", "-1"); // Hide for keyboard navigation
pre.setAttribute("inert", true); // Hide for keyboard navigation
// Save elements internally
this.preElement = pre;
this.codeElement = code;
pre.append(code);
this.append(pre);
if (this.templateObject.isCode) {
if (lang != undefined && lang != "") {
code.classList.add("language-" + lang.toLowerCase());
}
}
// dialogContainerElement used to store non-scrolling dialog boxes, etc.
let dialogContainerElement = document.createElement("div");
dialogContainerElement.classList.add("code-input_dialog-container");
this.append(dialogContainerElement);
this.dialogContainerElement = dialogContainerElement;
let keyboardNavigationInstructions = document.createElement("div");
keyboardNavigationInstructions.classList.add("code-input_keyboard-navigation-instructions");
dialogContainerElement.append(keyboardNavigationInstructions);
this.pluginEvt("afterElementsAdded");
this.dispatchEvent(new CustomEvent("code-input_load"));
this.value = value;
// Update with fallback textarea's state so can keep editing
// if loaded slowly
if(fallbackSelectionStart !== undefined) {
textarea.setSelectionRange(fallbackSelectionStart, fallbackSelectionEnd, fallbackSelectionDirection);
textarea.scrollTo(fallbackScrollTop, fallbackScrollLeft);
}
if(fallbackFocused) {
textarea.focus();
}
this.animateFrame();
const resizeObserver = new ResizeObserver((elements) => {
// The only element that could be resized is this code-input element.
this.syncSize();
});
resizeObserver.observe(this);
// Must resize when this content resizes, for autogrow plugin
// support.
resizeObserver.observe(this.preElement);
resizeObserver.observe(this.codeElement);
// Synchronise colors
const preColorChangeCallback = (evt) => {
if(evt.propertyName == "color") {
this.syncIfColorNotOverridden();
}
};
this.preElement.addEventListener("transitionend", preColorChangeCallback);
this.preElement.addEventListener("-webkit-transitionend", preColorChangeCallback);
const thisColorChangeCallback = (evt) => {
if(evt.propertyName == "color") {
this.syncColorCompletely();
}
if(evt.target == this.dialogContainerElement) {
evt.stopPropagation();
// Prevent bubbling because code-input
// transitionend is separate
}
};
// Not on this element so CSS transition property does not override publicly-visible one
this.dialogContainerElement.addEventListener("transitionend", thisColorChangeCallback);
this.dialogContainerElement.addEventListener("-webkit-transitionend", thisColorChangeCallback);
// For when this code-input element has an externally-defined, different-duration transition
this.addEventListener("transitionend", thisColorChangeCallback);
this.addEventListener("-webkit-transitionend", thisColorChangeCallback);
this.syncColorCompletely();
this.classList.add("code-input_loaded");
}
/**
* @deprecated This shouldn't have been accessed as part of the library's public interface (to enable more flexibility in backwards-compatible versions), but is still here just in case it was.
*/
escape_html(text) {
return this.escapeHtml(text);
}
/**
* @deprecated This shouldn't have been accessed as part of the library's public interface (to enable more flexibility in backwards-compatible versions), but is still here just in case it was.
*/
get_template() {
return this.getTemplate();
}
/**
* @deprecated Present for backwards compatibility; use CodeInput.templateObject.
*/
get template() {
return this.templateObject;
}
/**
* @deprecated The Vue framework may try to set the template
* property to the value of the template attribute, a string.
* This should not happen. Intentional use of this should
* also not happen since templates are changed by changing
* the template attribute to the name of one registered.
*/
set template(value) { }
/* ------------------------------------
* -----------Callbacks----------------
* ------------------------------------
* Implement the `HTMLElement` callbacks
* to trigger the main functionality properly. */
/**
* When the code-input element has been added to the document,
* find its template and set up the element.
*/
connectedCallback() {
// Stored in templateObject because some frameworks will override
// template property with the string value of the attribute
this.templateObject = this.getTemplate();
if (this.templateObject != undefined) {
// Template registered before loading
this.classList.add("code-input_registered");
if (document.readyState === 'loading') {
// Children not yet present - wait until they are
window.addEventListener("DOMContentLoaded", this.setup.bind(this))
} else {
this.setup();
}
}
// Graceful degradation: make events still work without template being
// registered
if (document.readyState === 'loading') {
// Children not yet present - wait until they are
window.addEventListener("DOMContentLoaded", () => {
const fallbackTextarea = this.querySelector("textarea[data-code-input-fallback]");
if(fallbackTextarea) {
this.setupTextareaSyncEvents(fallbackTextarea);
}
})
} else {
const fallbackTextarea = this.querySelector("textarea[data-code-input-fallback]");
if(fallbackTextarea) {
this.setupTextareaSyncEvents(fallbackTextarea);
}
}
}
mutationObserverCallback(mutationList, observer) {
for (const mutation of mutationList) {
if (mutation.type !== 'attributes')
continue;
/* Check regular attributes */
for(let i = 0; i < codeInput.observedAttributes.length; i++) {
if (mutation.attributeName == codeInput.observedAttributes[i]) {
return this.attributeChangedCallback(mutation.attributeName, mutation.oldValue, super.getAttribute(mutation.attributeName));
}
}
for(let i = 0; i < codeInput.textareaSyncAttributes.length; i++) {
if (mutation.attributeName == codeInput.textareaSyncAttributes[i]) {
return this.attributeChangedCallback(mutation.attributeName, mutation.oldValue, super.getAttribute(mutation.attributeName));
}
}
if (mutation.attributeName.substring(0, 5) == "aria-") {
return this.attributeChangedCallback(mutation.attributeName, mutation.oldValue, super.getAttribute(mutation.attributeName));