forked from WebCoder49/code-input
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode-input.js
More file actions
378 lines (326 loc) · 15.8 KB
/
Copy pathcode-input.js
File metadata and controls
378 lines (326 loc) · 15.8 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
// CodeInput
// by WebCoder49
// Based on a CSS-Tricks Post
var codeInput = {
observedAttributes: [
"value",
"placeholder",
"lang",
"template",
"onchange",
"onselectionchange"
],
// Attributes to monitor - needs to be global and static
/* Templates */
usedTemplates: {
},
defaultTemplate: undefined,
templateQueue: {}, // lists of elements for each unrecognised template
/* Plugins */
plugins: { // Import a plugin from the plugins folder and it will be saved here.
},
Plugin: class {
constructor() {
console.log("code-input: plugin: Created plugin!");
// Add attributes
codeInput.observedAttributes = codeInput.observedAttributes.concat(self.observedAttributes);
}
/* Runs before code is highlighted; Params: codeInput element) */
beforeHighlight(codeInput) {}
/* Runs after code is highlighted; Params: codeInput element) */
afterHighlight(codeInput) {}
/* Runs before elements are added into a `code-input`; Params: codeInput element) */
beforeElementsAdded(codeInput) {}
/* Runs after elements are added into a `code-input` (useful for adding events to the textarea); Params: codeInput element) */
afterElementsAdded(codeInput) {}
/* Runs when an attribute of a `code-input` is changed (you must add the attribute name to observedAttributes); Params: codeInput element, name attribute name, oldValue previous value of attribute, newValue changed value of attribute) */
attributeChanged(codeInput, name, oldValue, newValue) {}
observedAttributes = []
},
/* Main */
CodeInput: class extends HTMLElement { // Create code input element
constructor() {
super(); // Element
}
last_events = {}; // Last events applied; removed when changed so can be added to textarea, etc.
/* Run this event in all plugins with a optional list of arguments */
plugin_evt(id, args) {
// Run the event `id` in each plugin
for (let i in this.template.plugins) {
let plugin = this.template.plugins[i];
if (id in plugin) {
if(args === undefined) {
plugin[id](this);
} else {
plugin[id](this, ...args);
}
}
}
}
/* Syntax-highlighting functions */
update(text) {
if(this.value != text) this.value = text; // Change value attribute if necessary.
if(this.querySelector("textarea").value != text) this.querySelector("textarea").value = text;
let result_element = this.querySelector("pre code");
// Handle final newlines (see article)
if (text[text.length - 1] == "\n") {
text += " ";
}
// Update code
result_element.innerHTML = this.escape_html(text);
this.plugin_evt("beforeHighlight");
// Syntax Highlight
if(this.template.includeCodeInputInHighlightFunc) this.template.highlight(result_element, this);
else this.template.highlight(result_element);
this.plugin_evt("afterHighlight");
}
sync_scroll() {
/* Scroll result to scroll coords of event - sync with textarea */
let input_element = this.querySelector("textarea");
let result_element = this.template.preElementStyled ? this.querySelector("pre") : this.querySelector("pre code");
// Get and set x and y
result_element.scrollTop = input_element.scrollTop;
result_element.scrollLeft = input_element.scrollLeft;
}
escape_html(text) {
return text.replace(new RegExp("&", "g"), "&").replace(new RegExp("<", "g"), "<"); /* Global RegExp */
}
/* Get the template for this element or add to the unrecognised template queue. */
get_template() {
// Get name of template
let template_name;
if(this.getAttribute("template") == undefined) {
// Default
template_name = codeInput.defaultTemplate;
} else {
template_name = this.getAttribute("template");
}
// Get template
if(template_name in codeInput.usedTemplates) {
return codeInput.usedTemplates[template_name];
} else {
// Doesn't exist - add to queue
if( !(template_name in codeInput.templateQueue)) {
codeInput.templateQueue[template_name] = [];
}
codeInput.templateQueue[template_name].push(this);
return undefined;
}
codeInput.usedTemplates[codeInput.defaultTemplate]
}
/* Set up element when a template is added */
setup() {
this.classList.add("code-input_registered"); // Remove register message
if(this.template.preElementStyled) this.classList.add("code-input_pre-element-styled");
this.plugin_evt("beforeElementsAdded");
/* Defaults */
let lang = this.getAttribute("lang");
let placeholder = this.getAttribute("placeholder") || this.getAttribute("lang") || "";
let value = this.value || this.innerHTML || "";
this.innerHTML = ""; // Clear Content
/* Create Textarea */
let textarea = document.createElement("textarea");
textarea.placeholder = placeholder;
textarea.value = value;
textarea.setAttribute("spellcheck", "false");
if (this.getAttribute("name")) {
textarea.setAttribute("name", this.getAttribute("name")); // for use in forms
this.removeAttribute("name");
}
textarea.setAttribute("oninput", "this.parentElement.update(this.value); this.parentElement.sync_scroll();");
textarea.setAttribute("onscroll", "this.parentElement.sync_scroll();");
this.append(textarea);
/* Create pre code */
let code = document.createElement("code");
let pre = document.createElement("pre");
pre.setAttribute("aria-hidden", "true"); // Hide for screen readers
pre.append(code);
this.append(pre);
if(this.template.isCode) {
if(lang != undefined && lang != "") {
code.classList.add("language-" + lang);
}
}
this.plugin_evt("afterElementsAdded");
// Events
textarea = this.querySelector("textarea");
// Add event listeners, bound so `this` can be referenced
this.transfer_event("change", this.querySelector("textarea"), null, this.onchange);
this.transfer_event("selectionchange", this.querySelector("textarea"), null, this.onselectionchange);
/* Add code from value attribute - useful for loading from backend */
this.update(value, this);
}
/* Callbacks */
connectedCallback() {
// Added to document
this.template = this.get_template();
if(this.template != undefined) this.setup();
}
static get observedAttributes() {
return codeInput.observedAttributes;
}
attributeChangedCallback(name, oldValue, newValue) {
if(this.isConnected) {
// This will sometimes be called before the element has been created, so trying to update an attribute causes an error.
// Thanks to Kevin Loughead for pointing this out.
this.plugin_evt("attributeChanged", [name, oldValue, newValue]); // Plugin event
switch (name) {
case "value":
// Update code
this.update(newValue);
break;
case "placeholder":
this.querySelector("textarea").placeholder = newValue;
break;
case "template":
this.template = codeInput.usedTemplates[newValue || codeInput.defaultTemplate];
if(this.template.preElementStyled) this.classList.add("code-input_pre-element-styled");
else this.classList.remove("code-input_pre-element-styled");
// Syntax Highlight
this.update(this.value);
break;
case "lang":
let code = this.querySelector("pre code");
let main_textarea = this.querySelector("textarea");
// Case insensitive
oldValue = oldValue.toLowerCase();
newValue = newValue.toLowerCase();
// Remove old language class and add new
console.log("code-input: Language: REMOVE", "language-" + oldValue);
code.classList.remove("language-" + oldValue); // From CODE
code.parentElement.classList.remove("language-" + oldValue); // From PRE
code.classList.remove("language-none"); // Prism
code.parentElement.classList.remove("language-none"); // Prism
if(newValue != undefined && newValue != "") {
code.classList.add("language-" + newValue);
console.log("code-input: Language:ADD", "language-" + newValue);
}
if(main_textarea.placeholder == oldValue) main_textarea.placeholder = newValue;
this.update(this.value);
break;
// Events
case "onchange":
this.transfer_event("change", this.querySelector("textarea"), oldValue, newValue);
break;
case "onselectionchange":
this.transfer_event("selectionchange", this.querySelector("textarea"), oldValue, newValue);
break;
}
}
}
/* Transfer an event by name from this to an inner element. */
transfer_event(evt_name, transfer_to, oldValue, newValue) {
// Doesn't exist
if(oldValue) {
transfer_to.removeEventListener(evt_name, this.last_events[evt_name]);
}
if(newValue) {
this.last_events[evt_name] = this.onchange.bind(this);
transfer_to.addEventListener(evt_name, this.last_events[evt_name]);
this[`on${evt_name}`] = undefined; // Prevent duplicate
}
}
/* Value attribute */
get value() {
return this.getAttribute("value");
}
set value(val) {
return this.setAttribute("value", val);
}
/* Placeholder attribute */
get placeholder() {
return this.getAttribute("placeholder");
}
set placeholder(val) {
return this.setAttribute("placeholder", val);
}
},
registerTemplate: function(template_name, template) {
// Set default class
codeInput.usedTemplates[template_name] = template;
// Add elements w/ template from queue
if(template_name in codeInput.templateQueue) {
for(let i in codeInput.templateQueue[template_name]) {
elem = codeInput.templateQueue[template_name][i];
elem.template = template;
elem.setup();
}
console.log(`code-input: template: Added existing elements with template ${template_name}`);
}
if(codeInput.defaultTemplate == undefined) {
codeInput.defaultTemplate = template_name;
// Add elements w/ default template from queue
if(undefined in codeInput.templateQueue) {
for(let i in codeInput.templateQueue[undefined]) {
elem = codeInput.templateQueue[undefined][i];
elem.template = template;
elem.setup();
}
}
console.log(`code-input: template: Set template ${template_name} as default`);
}
console.log(`code-input: template: Created template ${template_name}`);
},
templates: {
custom(highlight=function() {}, preElementStyled=true, isCode=true, includeCodeInputInHighlightFunc=false, plugins=[]) {
return {
highlight: highlight,
includeCodeInputInHighlightFunc: includeCodeInputInHighlightFunc,
preElementStyled: preElementStyled,
isCode: isCode,
};
},
prism(prism, plugins=[]) { // Dependency: Prism.js (https://prismjs.com/)
return {
includeCodeInputInHighlightFunc: false,
highlight: prism.highlightElement,
preElementStyled: true,
isCode: true,
plugins: plugins,
};
},
hljs(hljs, plugins=[]) { // Dependency: Highlight.js (https://highlightjs.org/)
return {
includeCodeInputInHighlightFunc: false,
highlight: hljs.highlightElement,
preElementStyled: false,
isCode: true,
plugins: plugins,
};
},
characterLimit() {
return {
highlight: function(result_element, code_input) {
let character_limit = Number(code_input.getAttribute("data-character-limit"));
let normal_characters = code_input.escape_html(code_input.value.slice(0, character_limit));
let overflow_characters = code_input.escape_html(code_input.value.slice(character_limit));
result_element.innerHTML = `${normal_characters}<mark class="overflow">${overflow_characters}</mark>`;
if(overflow_characters.length > 0) {
result_element.innerHTML += ` <mark class="overflow-msg">${code_input.getAttribute("data-overflow-msg") || "(Character limit reached)"}</mark>`;
}
},
includeCodeInputInHighlightFunc: true,
preElementStyled: true,
isCode: false
}
},
rainbowText(rainbow_colors=["red", "orangered", "orange", "goldenrod", "gold", "green", "darkgreen", "navy", "blue", "magenta"], delimiter="") {
return {
highlight: function(result_element, code_input) {
let html_result = [];
let sections = code_input.value.split(code_input.template.delimiter);
for (let i = 0; i < sections.length; i++) {
html_result.push(`<span style="color: ${code_input.template.rainbow_colors[i % code_input.template.rainbow_colors.length]}">${code_input.escape_html(sections[i])}</span>`);
}
result_element.innerHTML = html_result.join(code_input.template.delimiter);
},
includeCodeInputInHighlightFunc: true,
preElementStyled: true,
isCode: false,
rainbow_colors: rainbow_colors,
delimiter: delimiter
}
}
}
}
customElements.define("code-input", codeInput.CodeInput); // Set tag