@webcoder49/code-input 2.0.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,130 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ 🎉 This project is fuelled by open-source contributions, but to sustain this community we need to all follow the rules below.
4
+
5
+ ## Our Pledge
6
+
7
+ We as members, contributors, and leaders pledge to make participation in our
8
+ community a harassment-free experience for everyone, regardless of age, body
9
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
10
+ identity and expression, level of experience, education, socio-economic status,
11
+ nationality, personal appearance, race, religion, or sexual identity
12
+ and orientation.
13
+
14
+ We pledge to act and interact in ways that contribute to an open, welcoming,
15
+ diverse, inclusive, and healthy community.
16
+
17
+ ## Our Standards
18
+
19
+ Examples of behavior that contributes to a positive environment for our
20
+ community include:
21
+
22
+ * Demonstrating empathy and kindness toward other people
23
+ * Being respectful of differing opinions, viewpoints, and experiences
24
+ * Giving and gracefully accepting constructive feedback
25
+ * Accepting responsibility and apologizing to those affected by our mistakes,
26
+ and learning from the experience
27
+ * Focusing on what is best not just for us as individuals, but for the
28
+ overall community
29
+
30
+ Examples of unacceptable behavior include:
31
+
32
+ * The use of sexualized language or imagery, and sexual attention or
33
+ advances of any kind
34
+ * Trolling, insulting or derogatory comments, and personal or political attacks
35
+ * Public or private harassment
36
+ * Publishing others' private information, such as a physical or email
37
+ address, without their explicit permission
38
+ * Other conduct which could reasonably be considered inappropriate in a
39
+ professional setting
40
+
41
+ ## Enforcement Responsibilities
42
+
43
+ Community leaders are responsible for clarifying and enforcing our standards of
44
+ acceptable behavior and will take appropriate and fair corrective action in
45
+ response to any behavior that they deem inappropriate, threatening, offensive,
46
+ or harmful.
47
+
48
+ Community leaders have the right and responsibility to remove, edit, or reject
49
+ comments, commits, code, wiki edits, issues, and other contributions that are
50
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
51
+ decisions when appropriate.
52
+
53
+ ## Scope
54
+
55
+ This Code of Conduct applies within all community spaces, and also applies when
56
+ an individual is officially representing the community in public spaces.
57
+ Examples of representing our community include using an official e-mail address,
58
+ posting via an official social media account, or acting as an appointed
59
+ representative at an online or offline event.
60
+
61
+ ## Enforcement
62
+
63
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
64
+ reported to the community leaders responsible for enforcement at
65
+ legal@webcoder49.dev.
66
+ All complaints will be reviewed and investigated promptly and fairly.
67
+
68
+ All community leaders are obligated to respect the privacy and security of the
69
+ reporter of any incident.
70
+
71
+ ## Enforcement Guidelines
72
+
73
+ Community leaders will follow these Community Impact Guidelines in determining
74
+ the consequences for any action they deem in violation of this Code of Conduct:
75
+
76
+ ### 1. Correction
77
+
78
+ **Community Impact**: Use of inappropriate language or other behavior deemed
79
+ unprofessional or unwelcome in the community.
80
+
81
+ **Consequence**: A private, written warning from community leaders, providing
82
+ clarity around the nature of the violation and an explanation of why the
83
+ behavior was inappropriate. A public apology may be requested.
84
+
85
+ ### 2. Warning
86
+
87
+ **Community Impact**: A violation through a single incident or series
88
+ of actions.
89
+
90
+ **Consequence**: A warning with consequences for continued behavior. No
91
+ interaction with the people involved, including unsolicited interaction with
92
+ those enforcing the Code of Conduct, for a specified period of time. This
93
+ includes avoiding interactions in community spaces as well as external channels
94
+ like social media. Violating these terms may lead to a temporary or
95
+ permanent ban.
96
+
97
+ ### 3. Temporary Ban
98
+
99
+ **Community Impact**: A serious violation of community standards, including
100
+ sustained inappropriate behavior.
101
+
102
+ **Consequence**: A temporary ban from any sort of interaction or public
103
+ communication with the community for a specified period of time. No public or
104
+ private interaction with the people involved, including unsolicited interaction
105
+ with those enforcing the Code of Conduct, is allowed during this period.
106
+ Violating these terms may lead to a permanent ban.
107
+
108
+ ### 4. Permanent Ban
109
+
110
+ **Community Impact**: Demonstrating a pattern of violation of community
111
+ standards, including sustained inappropriate behavior, harassment of an
112
+ individual, or aggression toward or disparagement of classes of individuals.
113
+
114
+ **Consequence**: A permanent ban from any sort of public interaction within
115
+ the community.
116
+
117
+ ## Attribution
118
+
119
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
120
+ version 2.0, available at
121
+ https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
122
+
123
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct
124
+ enforcement ladder](https://github.com/mozilla/diversity).
125
+
126
+ [homepage]: https://www.contributor-covenant.org
127
+
128
+ For answers to common questions about this code of conduct, see the FAQ at
129
+ https://www.contributor-covenant.org/faq. Translations are available at
130
+ https://www.contributor-covenant.org/translations.
@@ -0,0 +1,25 @@
1
+ # Contributing to `code-input`
2
+
3
+ 🎉**Here at `code-input`, contributions of all sizes are more than welcome. Below are some scenarios where you could contribute and how to do so.** Contributions are generally accepted when they help achieve at least one of the aims below, but others will be considered:
4
+
5
+ * The `code-input` element should act like a normal HTML `textarea` in all browsers, working with all of the normal attributes, events and other types of behaviour.
6
+ * The `code-input` element should be easy to use with all popular syntax-highlighting libraries.
7
+ * Any modifications of `code-input` that would be useful for the open-source community but are not core to this functionality should be available as optional plugins in the `plugins` folder. Here's where most feature contributions will go.
8
+
9
+ To keep this community productive and enjoyable, please [don't break the code of conduct here](https://github.com/WebCoder49/code-input/blob/main/CODE_OF_CONDUCT.md).
10
+
11
+ ---
12
+ # Ways you could contribute:
13
+ ## 1. I've found a bug but don't know how / don't have time to fix it.
14
+ If you think you've found a bug, please [submit an issue](https://github.com/WebCoder49/code-input/issues) with screenshots, how you found the bug, and copies of the console's logs if an error is in them. Please also mention the template and plugins you used (your `codeInput.registerTemplate(...)` snippet). We'd be more than happy to help you fix it. A demo using [CodePen](https://codepen.io/) would be incredibly useful.
15
+
16
+ ## 2. I have implemented a feature / have thought of a potential feature for the library and think it could be useful for others.
17
+ The best way to implement a feature is as a plugin like those in the `plugins` folder of `code-input`. If you do this, you could contribute it as in point 3 below.
18
+ Otherwise, if you do not have the time needed / do not want to implement it, any potential plugins would be [welcome as an Issue](https://github.com/WebCoder49/code-input/issues) which specifies the uses and desired characteristics.
19
+
20
+ ## 3. I want to contribute code that I need / have seen in the Issues.
21
+ Firstly, thank you for doing this! This is probably the most time consuming way of contributing but is also the most rewarding for both you and me as a maintainer.
22
+
23
+ Please first open an issue if one doesn't already exist, and assign yourself to it. Then, [make a fork of the repo and submit a pull request](https://docs.github.com/en/get-started/quickstart/contributing-to-projects).
24
+
25
+ If an issue is open but already assigned to someone, it is probably already being worked on - you could still suggest a method of fixing it in the comments but shouldn't open a pull request as it would waste your time.
package/README.md CHANGED
@@ -99,7 +99,7 @@ The next step is to set up a `template` to link `code-input` to your syntax-high
99
99
  hljs,
100
100
  [
101
101
  new codeInput.plugins.Autodetect(),
102
- new codeInput.plugins.Indent()
102
+ new codeInput.plugins.Indent(true, 2) // 2 spaces indentation
103
103
  ]
104
104
  )
105
105
  );
@@ -119,7 +119,7 @@ Now that you have registered a template, you can use the custom `<code-input>` e
119
119
  ```
120
120
 
121
121
  ## Contributing
122
- If you have any features you would like to add to `code-input`, or have found any bugs, please [open an issue](https://github.com/WebCoder49/code-input/issues) or [fork and submit a pull request](https://github.com/WebCoder49/code-input/fork)! All contributions to this open-source project would be greatly appreciated.
122
+ If you have any features you would like to add to `code-input` as plugins or core functionality, or have found any bugs, please [open an issue](https://github.com/WebCoder49/code-input/issues) or [fork and submit a pull request](https://github.com/WebCoder49/code-input/fork)! All contributions to this open-source project will be greatly appreciated. You can see [more info in our `CONTRIBUTING.md` file](CONTRIBUTING.md).
123
123
 
124
124
 
125
125
  |[![Contributors](https://contrib.rocks/image?repo=WebCoder49%2Fcode-input)](https://github.com/WebCoder49/code-input/graphs/contributors)|
package/code-input.css CHANGED
@@ -83,13 +83,16 @@ code-input:not(.code-input_loaded)::after {
83
83
  color: #ccc;
84
84
  }
85
85
 
86
- /* Make textarea almost completely transparent */
86
+ /* Make textarea almost completely transparent, except for caret and placeholder */
87
87
 
88
88
  code-input textarea {
89
89
  color: transparent;
90
90
  background: transparent;
91
91
  caret-color: inherit!important; /* Or choose your favourite color */
92
92
  }
93
+ code-input textarea::placeholder {
94
+ color: lightgrey;
95
+ }
93
96
 
94
97
  /* Can be scrolled */
95
98
  code-input textarea, code-input pre {
package/code-input.d.ts CHANGED
@@ -116,7 +116,12 @@ export namespace plugins {
116
116
  * Files: indent.js
117
117
  */
118
118
  class Indent extends Plugin {
119
- constructor();
119
+ /**
120
+ * Create an indentation plugin to pass into a template
121
+ * @param {Boolean} defaultSpaces Should the Tab key enter spaces rather than tabs? Defaults to false.
122
+ * @param {Number} numSpaces How many spaces is each tab character worth? Defaults to 4.
123
+ */
124
+ constructor(defaultSpaces?: boolean, numSpaces?: Number);
120
125
  }
121
126
 
122
127
  /**
package/code-input.js CHANGED
@@ -31,13 +31,28 @@ var codeInput = {
31
31
  textareaSyncAttributes: [
32
32
  "aria-*",
33
33
  "value",
34
- "name",
35
34
  // Form validation - https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation#using_built-in_form_validation
36
- "required",
37
- "minlength", "maxlength",
38
35
  "min", "max",
39
36
  "type",
40
- "pattern"
37
+ "pattern",
38
+
39
+ // Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea
40
+ "autocomplete",
41
+ "autocorrect",
42
+ "autofocus",
43
+ "cols",
44
+ "dirname",
45
+ "disabled",
46
+ "form",
47
+ "maxlength",
48
+ "minlength",
49
+ "name",
50
+ "placeholder",
51
+ "readonly",
52
+ "required",
53
+ "rows",
54
+ "spellcheck",
55
+ "wrap"
41
56
  ],
42
57
 
43
58
  /**
@@ -759,7 +774,6 @@ var codeInput = {
759
774
  oldValue = oldValue.toLowerCase();
760
775
 
761
776
  // Remove old language class and add new
762
- console.log("code-input: Language: REMOVE", "language-" + oldValue);
763
777
  code.classList.remove("language-" + oldValue); // From codeElement
764
778
  code.parentElement.classList.remove("language-" + oldValue); // From preElement
765
779
  code.classList.remove("language-none"); // Prism
@@ -767,7 +781,6 @@ var codeInput = {
767
781
 
768
782
  if (newValue != undefined && newValue != "") {
769
783
  code.classList.add("language-" + newValue);
770
- console.log("code-input: Language: ADD", "language-" + newValue);
771
784
  }
772
785
 
773
786
  if (mainTextarea.placeholder == oldValue) mainTextarea.placeholder = newValue;
@@ -777,7 +790,7 @@ var codeInput = {
777
790
  break;
778
791
  default:
779
792
  if (codeInput.textareaSyncAttributes.includes(name)) {
780
- if(newValue == null) {
793
+ if(newValue == null || newValue == undefined) {
781
794
  this.textareaElement.removeAttribute(name);
782
795
  } else {
783
796
  this.textareaElement.setAttribute(name, newValue);
@@ -939,27 +952,6 @@ var codeInput = {
939
952
  return this.textareaElement.reportValidity();
940
953
  }
941
954
 
942
-
943
- /**
944
- * @override
945
- */
946
- setAttribute(qualifiedName, value) {
947
- super.setAttribute(qualifiedName, value); // code-input
948
- if(this.textareaElement != null) {
949
- this.textareaElement.setAttribute(qualifiedName, value); // textarea
950
- }
951
- }
952
-
953
- /**
954
- * @override
955
- */
956
- getAttribute(qualifiedName) {
957
- if (this.textareaElement == null) {
958
- return super.getAttribute(qualifiedName);
959
- }
960
- return this.textareaElement.getAttribute(qualifiedName); // textarea
961
- }
962
-
963
955
  /**
964
956
  * Allows plugins to store data in the scope of a single element.
965
957
  * Key - name of the plugin
@@ -1 +1 @@
1
- code-input{position:relative;top:0;left:0;display:block;overflow:hidden;margin:8px;--padding:16px;height:250px;font-size:normal;font-family:monospace;line-height:1.5;tab-size:2;caret-color:#a9a9a9;white-space:pre;padding:0!important}code-input textarea,code-input.code-input_pre-element-styled pre,code-input:not(.code-input_pre-element-styled) pre code{margin:0!important;padding:var(--padding,16px)!important;border:0;width:calc(100% - var(--padding,16px) * 2);height:calc(100% - var(--padding,16px) * 2)}code-input:not(.code-input_loaded){margin:0!important;margin-bottom:calc(-1 * var(--padding,16px))!important;padding:var(--padding,16px)!important;border:0}code-input.code-input_pre-element-styled pre code,code-input:not(.code-input_pre-element-styled) pre{margin:0!important;padding:0!important;width:100%;height:100%}code-input pre,code-input pre *,code-input textarea{font-size:inherit!important;font-family:inherit!important;line-height:inherit!important;tab-size:inherit!important}code-input pre,code-input textarea{position:absolute;top:0;left:0}code-input textarea{z-index:1}code-input pre{z-index:0}code-input:not(.code-input_loaded) pre,code-input:not(.code-input_loaded) textarea{opacity:0}code-input:not(.code-input_loaded)::after{color:#ccc}code-input textarea{color:transparent;background:0 0;caret-color:inherit!important}code-input pre,code-input textarea{overflow:auto!important;white-space:inherit;word-spacing:normal;word-break:normal;word-wrap:normal}code-input textarea{resize:none;outline:0!important}code-input:not(.code-input_registered)::after{content:"Use codeInput.registerTemplate to set up.";display:block;color:grey}
1
+ code-input{position:relative;top:0;left:0;display:block;overflow:hidden;margin:8px;--padding:16px;height:250px;font-size:normal;font-family:monospace;line-height:1.5;tab-size:2;caret-color:#a9a9a9;white-space:pre;padding:0!important}code-input textarea,code-input.code-input_pre-element-styled pre,code-input:not(.code-input_pre-element-styled) pre code{margin:0!important;padding:var(--padding,16px)!important;border:0;width:calc(100% - var(--padding,16px) * 2);height:calc(100% - var(--padding,16px) * 2)}code-input:not(.code-input_loaded){margin:0!important;margin-bottom:calc(-1 * var(--padding,16px))!important;padding:var(--padding,16px)!important;border:0}code-input.code-input_pre-element-styled pre code,code-input:not(.code-input_pre-element-styled) pre{margin:0!important;padding:0!important;width:100%;height:100%}code-input pre,code-input pre *,code-input textarea{font-size:inherit!important;font-family:inherit!important;line-height:inherit!important;tab-size:inherit!important}code-input pre,code-input textarea{position:absolute;top:0;left:0}code-input textarea{z-index:1}code-input pre{z-index:0}code-input:not(.code-input_loaded) pre,code-input:not(.code-input_loaded) textarea{opacity:0}code-input:not(.code-input_loaded)::after{color:#ccc}code-input textarea{color:transparent;background:0 0;caret-color:inherit!important}code-input textarea::placeholder{color:#d3d3d3}code-input pre,code-input textarea{overflow:auto!important;white-space:inherit;word-spacing:normal;word-break:normal;word-wrap:normal}code-input textarea{resize:none;outline:0!important}code-input:not(.code-input_registered)::after{content:"Use codeInput.registerTemplate to set up.";display:block;color:grey}
package/code-input.min.js CHANGED
@@ -1 +1 @@
1
- var codeInput={observedAttributes:["value","placeholder","lang","template"],textareaSyncAttributes:["aria-*","value","name","required","minlength","maxlength","min","max","type","pattern"],textareaSyncEvents:["change","selectionchange","invalid","input"],usedTemplates:{},defaultTemplate:void 0,templateNotYetRegisteredQueue:{},registerTemplate:function(a,b){if(!("string"==typeof a||a instanceof String))throw TypeError(`code-input: Template for "${a}" must be a string.`);if(!("function"==typeof b.highlight||b.highlight instanceof Function))throw TypeError(`code-input: Template for "${a}" invalid, because the highlight function provided is not a function; it is "${b.highlight}". Please make sure you use one of the constructors in codeInput.templates, and that you provide the correct arguments.`);if(!("boolean"==typeof b.includeCodeInputInHighlightFunc||b.includeCodeInputInHighlightFunc instanceof Boolean))throw TypeError(`code-input: Template for "${a}" invalid, because the includeCodeInputInHighlightFunc value provided is not a true or false; it is "${b.includeCodeInputInHighlightFunc}". Please make sure you use one of the constructors in codeInput.templates, and that you provide the correct arguments.`);if(!("boolean"==typeof b.preElementStyled||b.preElementStyled instanceof Boolean))throw TypeError(`code-input: Template for "${a}" invalid, because the preElementStyled value provided is not a true or false; it is "${b.preElementStyled}". Please make sure you use one of the constructors in codeInput.templates, and that you provide the correct arguments.`);if(!("boolean"==typeof b.isCode||b.isCode instanceof Boolean))throw TypeError(`code-input: Template for "${a}" invalid, because the isCode value provided is not a true or false; it is "${b.isCode}". Please make sure you use one of the constructors in codeInput.templates, and that you provide the correct arguments.`);if(!Array.isArray(b.plugins))throw TypeError(`code-input: Template for "${a}" invalid, because the plugin array provided is not an array; it is "${b.plugins}". Please make sure you use one of the constructors in codeInput.templates, and that you provide the correct arguments.`);if(b.plugins.forEach((c,d)=>{if(!(c instanceof codeInput.Plugin))throw TypeError(`code-input: Template for "${a}" invalid, because the plugin provided at index ${d} is not valid; it is "${b.plugins[d]}". Please make sure you use one of the constructors in codeInput.templates, and that you provide the correct arguments.`)}),codeInput.usedTemplates[a]=b,a in codeInput.templateNotYetRegisteredQueue){for(let c in codeInput.templateNotYetRegisteredQueue[a])elem=codeInput.templateNotYetRegisteredQueue[a][c],elem.template=b,codeInput.runOnceWindowLoaded(function(a){a.connectedCallback()}.bind(null,elem),elem);console.log(`code-input: template: Added existing elements with template ${a}`)}if(null==codeInput.defaultTemplate){if(codeInput.defaultTemplate=a,void 0 in codeInput.templateNotYetRegisteredQueue)for(let a in codeInput.templateNotYetRegisteredQueue[void 0])elem=codeInput.templateNotYetRegisteredQueue[void 0][a],elem.template=b,codeInput.runOnceWindowLoaded(function(a){a.connectedCallback()}.bind(null,elem),elem);console.log(`code-input: template: Set template ${a} as default`)}console.log(`code-input: template: Created template ${a}`)},Template:class{constructor(a=function(){},b=!0,c=!0,d=!1,e=[]){this.highlight=a,this.preElementStyled=b,this.isCode=c,this.includeCodeInputInHighlightFunc=d,this.plugins=e}highlight=function(){};preElementStyled=!0;isCode=!0;includeCodeInputInHighlightFunc=!1;plugins=[]},templates:{prism(a,b=[]){return{includeCodeInputInHighlightFunc:!1,highlight:a.highlightElement,preElementStyled:!0,isCode:!0,plugins:b}},hljs(a,b=[]){return{includeCodeInputInHighlightFunc:!1,highlight:a.highlightElement,preElementStyled:!1,isCode:!0,plugins:b}},characterLimit(a){return{highlight:function(a,b,c=[]){let d=+b.getAttribute("data-character-limit"),e=b.escapeHtml(b.value.slice(0,d)),f=b.escapeHtml(b.value.slice(d));a.innerHTML=`${e}<mark class="overflow">${f}</mark>`,0<f.length&&(a.innerHTML+=` <mark class="overflow-msg">${b.getAttribute("data-overflow-msg")||"(Character limit reached)"}</mark>`)},includeCodeInputInHighlightFunc:!0,preElementStyled:!0,isCode:!1,plugins:a}},rainbowText(a=["red","orangered","orange","goldenrod","gold","green","darkgreen","navy","blue","magenta"],b="",c=[]){return{highlight:function(a,b){let c=[],d=b.value.split(b.template.delimiter);for(let e=0;e<d.length;e++)c.push(`<span style="color: ${b.template.rainbowColors[e%b.template.rainbowColors.length]}">${b.escapeHtml(d[e])}</span>`);a.innerHTML=c.join(b.template.delimiter)},includeCodeInputInHighlightFunc:!0,preElementStyled:!0,isCode:!1,rainbowColors:a,delimiter:b,plugins:c}},character_limit(){return this.characterLimit([])},rainbow_text(a=["red","orangered","orange","goldenrod","gold","green","darkgreen","navy","blue","magenta"],b="",c=[]){return this.rainbowText(a,b,c)},custom(a=function(){},b=!0,c=!0,d=!1,e=[]){return{highlight:a,includeCodeInputInHighlightFunc:d,preElementStyled:b,isCode:c,plugins:e}}},plugins:new Proxy({},{get(a,b){if(a[b]==null)throw ReferenceError(`code-input: Plugin '${b}' 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 a[b]}}),Plugin:class{constructor(a){console.log("code-input: plugin: Created plugin"),a.forEach(a=>{let b=codeInput.wildcard2regex(a);null==b?codeInput.observedAttributes.push(a):codeInput.observedAttributes.regexp.push(b)})}beforeHighlight(){}afterHighlight(){}beforeElementsAdded(){}afterElementsAdded(){}attributeChanged(){}},CodeInput:class extends HTMLElement{constructor(){super()}_value="";textareaElement=null;preElement=null;codeElement=null;static formAssociated=!0;boundEventCallbacks={};pluginEvt(a,b){for(let c in this.template.plugins){let d=this.template.plugins[c];a in d&&(b===void 0?d[a](this):d[a](this,...b))}}update(a){if(!this.ignoreValueUpdate){if(null==this.textareaElement)return void this.addEventListener("code-input_load",()=>{this.update(a)});this.ignoreValueUpdate=!0,this.value=a,this.ignoreValueUpdate=!1,this.textareaElement.value!=a&&(this.textareaElement.value=a);let b=this.codeElement;"\n"==a[a.length-1]&&(a+=" "),b.innerHTML=this.escapeHtml(a),this.pluginEvt("beforeHighlight"),this.template.includeCodeInputInHighlightFunc?this.template.highlight(b,this):this.template.highlight(b),this.pluginEvt("afterHighlight")}}syncScroll(){let a=this.textareaElement,b=this.template.preElementStyled?this.preElement:this.codeElement;b.scrollTop=a.scrollTop,b.scrollLeft=a.scrollLeft}escapeHtml(a){return a.replace(/&/g,"&amp;").replace(/</g,"&lt;")}unescapeHtml(a){return a.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">")}getTemplate(){let a;return a=null==this.getAttribute("template")?codeInput.defaultTemplate:this.getAttribute("template"),a in codeInput.usedTemplates?codeInput.usedTemplates[a]:(a in codeInput.templateNotYetRegisteredQueue||(codeInput.templateNotYetRegisteredQueue[a]=[]),void codeInput.templateNotYetRegisteredQueue[a].push(this))}setup(){if(null!=this.textareaElement)return;this.classList.add("code-input_registered"),this.template.preElementStyled&&this.classList.add("code-input_pre-element-styled"),this.pluginEvt("beforeElementsAdded");let a=this.getAttribute("lang"),b=this.getAttribute("placeholder")||this.getAttribute("lang")||"",c=this.unescapeHtml(this.innerHTML)||this.getAttribute("value")||"";this.initialValue=c;let d=document.createElement("textarea");d.placeholder=b,""!=c&&(d.value=c),d.innerHTML=this.innerHTML,d.setAttribute("spellcheck","false"),this.innerHTML="",codeInput.textareaSyncAttributes.forEach(a=>{this.hasAttribute(a)&&d.setAttribute(a,this.getAttribute(a))}),codeInput.textareaSyncAttributes.regexp.forEach(a=>{for(const b of this.attributes)b.nodeName.match(a)&&d.setAttribute(b.nodeName,b.nodeValue)}),d.addEventListener("input",()=>{d.parentElement.update(d.value),d.parentElement.sync_scroll()}),d.addEventListener("scroll",()=>d.parentElement.sync_scroll()),this.textareaElement=d,this.append(d);let e=document.createElement("code"),f=document.createElement("pre");f.setAttribute("aria-hidden","true"),this.preElement=f,this.codeElement=e,f.append(e),this.append(f),this.template.isCode&&a!=null&&""!=a&&e.classList.add("language-"+a),this.pluginEvt("afterElementsAdded"),this.update(c),this.dispatchEvent(new CustomEvent("code-input_load"))}sync_scroll(){this.syncScroll()}escape_html(a){return this.escapeHtml(a)}get_template(){return this.getTemplate()}connectedCallback(){this.template=this.getTemplate(),this.template!=null&&(this.classList.add("code-input_registered"),codeInput.runOnceWindowLoaded(()=>{this.setup(),this.classList.add("code-input_loaded")},this)),this.mutationObserver=new MutationObserver(this.mutationObserverCallback.bind(this)),this.mutationObserver.observe(this,{attributes:!0,attributeOldValue:!0})}mutationObserverCallback(a){for(const b of a)if("attributes"===b.type){for(let a=0;a<codeInput.observedAttributes.length;a++)if(b.attributeName==codeInput.observedAttributes[a])return this.attributeChangedCallback(b.attributeName,b.oldValue,super.getAttribute(b.attributeName));for(let a=0;a<codeInput.observedAttributes.regexp.length;a++){const c=codeInput.observedAttributes.regexp[a];if(b.attributeName.match(c))return this.attributeChangedCallback(b.attributeName,b.oldValue,super.getAttribute(b.attributeName))}}}disconnectedCallback(){this.mutationObserver.disconnect()}attributeChangedCallback(a,b,c){if(this.isConnected)switch(this.pluginEvt("attributeChanged",[a,b,c]),a){case"value":this.value=c;break;case"placeholder":this.textareaElement.placeholder=c;break;case"template":this.template=codeInput.usedTemplates[c||codeInput.defaultTemplate],this.template.preElementStyled?this.classList.add("code-input_pre-element-styled"):this.classList.remove("code-input_pre-element-styled"),this.update(this.value);break;case"lang":let d=this.codeElement,e=this.textareaElement;if(null!=c&&(c=c.toLowerCase(),d.classList.contains(`language-${c}`)))break;b=b.toLowerCase(),console.log("code-input: Language: REMOVE","language-"+b),d.classList.remove("language-"+b),d.parentElement.classList.remove("language-"+b),d.classList.remove("language-none"),d.parentElement.classList.remove("language-none"),null!=c&&""!=c&&(d.classList.add("language-"+c),console.log("code-input: Language: ADD","language-"+c)),e.placeholder==b&&(e.placeholder=c),this.update(this.value);break;default:codeInput.textareaSyncAttributes.includes(a)?null==c?this.textareaElement.removeAttribute(a):this.textareaElement.setAttribute(a,c):codeInput.textareaSyncAttributes.regexp.forEach(b=>{a.match(b)&&(null==c?this.textareaElement.removeAttribute(a):this.textareaElement.setAttribute(a,c))})}}addEventListener(a,b,c=void 0){let d=b.bind(this);this.boundEventCallbacks[b]=d,codeInput.textareaSyncEvents.includes(a)?c===void 0?null==this.textareaElement?this.addEventListener("code-input_load",()=>{this.textareaElement.addEventListener(a,d)}):this.textareaElement.addEventListener(a,d):null==this.textareaElement?this.addEventListener("code-input_load",()=>{this.textareaElement.addEventListener(a,d,c)}):this.textareaElement.addEventListener(a,d,c):c===void 0?super.addEventListener(a,d):super.addEventListener(a,d,c)}removeEventListener(a,b,c=null){let d=this.boundEventCallbacks[b];"change"==a?null===c?this.textareaElement.removeEventListener("change",d):this.textareaElement.removeEventListener("change",d,c):"selectionchange"==a?null===c?this.textareaElement.removeEventListener("selectionchange",d):this.textareaElement.removeEventListener("selectionchange",d,c):super.removeEventListener(a,b,c)}get value(){return this._value}set value(a){return(null===a||void 0===a)&&(a=""),this._value=a,this.update(a),a}get placeholder(){return this.getAttribute("placeholder")}set placeholder(a){return this.setAttribute("placeholder",a)}get validity(){return this.textareaElement.validity}get validationMessage(){return this.textareaElement.validationMessage}setCustomValidity(a){return this.textareaElement.setCustomValidity(a)}checkValidity(){return this.textareaElement.checkValidity()}reportValidity(){return this.textareaElement.reportValidity()}setAttribute(a,b){super.setAttribute(a,b),null!=this.textareaElement&&this.textareaElement.setAttribute(a,b)}getAttribute(a){return null==this.textareaElement?super.getAttribute(a):this.textareaElement.getAttribute(a)}pluginData={};formResetCallback(){this.update(this.initialValue)}},arrayWildcards2regex(a){for(let b=0;b<a.length;b++){const c=a[b];0>c.indexOf("*")||(a.regexp.push(new RegExp("^"+c.replace(/[/\-\\^$+?.()|[\]{}]/g,"\\$&").replace("*",".*")+"$","i")),a.splice(b--,1))}},wildcard2regex(a){return 0>a.indexOf("*")?null:new RegExp("^"+a.replace(/[/\-\\^$+?.()|[\]{}]/g,"\\$&").replace("*",".*")+"$","i")},runOnceWindowLoaded(a){codeInput.windowLoaded?a():window.addEventListener("load",a)},windowLoaded:!1};window.addEventListener("load",function(){codeInput.windowLoaded=!0}),Object.defineProperty(codeInput.textareaSyncAttributes,"regexp",{value:[],writable:!1,enumerable:!1,configurable:!1}),codeInput.observedAttributes=codeInput.observedAttributes.concat(codeInput.textareaSyncAttributes),Object.defineProperty(codeInput.observedAttributes,"regexp",{value:[],writable:!1,enumerable:!1,configurable:!1}),codeInput.arrayWildcards2regex(codeInput.textareaSyncAttributes),codeInput.arrayWildcards2regex(codeInput.observedAttributes),customElements.define("code-input",codeInput.CodeInput);
1
+ var codeInput={observedAttributes:["value","placeholder","lang","template"],textareaSyncAttributes:["aria-*","value","min","max","type","pattern","autocomplete","autocorrect","autofocus","cols","dirname","disabled","form","maxlength","minlength","name","placeholder","readonly","required","rows","spellcheck","wrap"],textareaSyncEvents:["change","selectionchange","invalid","input"],usedTemplates:{},defaultTemplate:void 0,templateNotYetRegisteredQueue:{},registerTemplate:function(a,b){if(!("string"==typeof a||a instanceof String))throw TypeError(`code-input: Template for "${a}" must be a string.`);if(!("function"==typeof b.highlight||b.highlight instanceof Function))throw TypeError(`code-input: Template for "${a}" invalid, because the highlight function provided is not a function; it is "${b.highlight}". Please make sure you use one of the constructors in codeInput.templates, and that you provide the correct arguments.`);if(!("boolean"==typeof b.includeCodeInputInHighlightFunc||b.includeCodeInputInHighlightFunc instanceof Boolean))throw TypeError(`code-input: Template for "${a}" invalid, because the includeCodeInputInHighlightFunc value provided is not a true or false; it is "${b.includeCodeInputInHighlightFunc}". Please make sure you use one of the constructors in codeInput.templates, and that you provide the correct arguments.`);if(!("boolean"==typeof b.preElementStyled||b.preElementStyled instanceof Boolean))throw TypeError(`code-input: Template for "${a}" invalid, because the preElementStyled value provided is not a true or false; it is "${b.preElementStyled}". Please make sure you use one of the constructors in codeInput.templates, and that you provide the correct arguments.`);if(!("boolean"==typeof b.isCode||b.isCode instanceof Boolean))throw TypeError(`code-input: Template for "${a}" invalid, because the isCode value provided is not a true or false; it is "${b.isCode}". Please make sure you use one of the constructors in codeInput.templates, and that you provide the correct arguments.`);if(!Array.isArray(b.plugins))throw TypeError(`code-input: Template for "${a}" invalid, because the plugin array provided is not an array; it is "${b.plugins}". Please make sure you use one of the constructors in codeInput.templates, and that you provide the correct arguments.`);if(b.plugins.forEach((c,d)=>{if(!(c instanceof codeInput.Plugin))throw TypeError(`code-input: Template for "${a}" invalid, because the plugin provided at index ${d} is not valid; it is "${b.plugins[d]}". Please make sure you use one of the constructors in codeInput.templates, and that you provide the correct arguments.`)}),codeInput.usedTemplates[a]=b,a in codeInput.templateNotYetRegisteredQueue){for(let c in codeInput.templateNotYetRegisteredQueue[a])elem=codeInput.templateNotYetRegisteredQueue[a][c],elem.template=b,codeInput.runOnceWindowLoaded(function(a){a.connectedCallback()}.bind(null,elem),elem);console.log(`code-input: template: Added existing elements with template ${a}`)}if(null==codeInput.defaultTemplate){if(codeInput.defaultTemplate=a,void 0 in codeInput.templateNotYetRegisteredQueue)for(let a in codeInput.templateNotYetRegisteredQueue[void 0])elem=codeInput.templateNotYetRegisteredQueue[void 0][a],elem.template=b,codeInput.runOnceWindowLoaded(function(a){a.connectedCallback()}.bind(null,elem),elem);console.log(`code-input: template: Set template ${a} as default`)}console.log(`code-input: template: Created template ${a}`)},Template:class{constructor(a=function(){},b=!0,c=!0,d=!1,e=[]){this.highlight=a,this.preElementStyled=b,this.isCode=c,this.includeCodeInputInHighlightFunc=d,this.plugins=e}highlight=function(){};preElementStyled=!0;isCode=!0;includeCodeInputInHighlightFunc=!1;plugins=[]},templates:{prism(a,b=[]){return{includeCodeInputInHighlightFunc:!1,highlight:a.highlightElement,preElementStyled:!0,isCode:!0,plugins:b}},hljs(a,b=[]){return{includeCodeInputInHighlightFunc:!1,highlight:a.highlightElement,preElementStyled:!1,isCode:!0,plugins:b}},characterLimit(a){return{highlight:function(a,b,c=[]){let d=+b.getAttribute("data-character-limit"),e=b.escapeHtml(b.value.slice(0,d)),f=b.escapeHtml(b.value.slice(d));a.innerHTML=`${e}<mark class="overflow">${f}</mark>`,0<f.length&&(a.innerHTML+=` <mark class="overflow-msg">${b.getAttribute("data-overflow-msg")||"(Character limit reached)"}</mark>`)},includeCodeInputInHighlightFunc:!0,preElementStyled:!0,isCode:!1,plugins:a}},rainbowText(a=["red","orangered","orange","goldenrod","gold","green","darkgreen","navy","blue","magenta"],b="",c=[]){return{highlight:function(a,b){let c=[],d=b.value.split(b.template.delimiter);for(let e=0;e<d.length;e++)c.push(`<span style="color: ${b.template.rainbowColors[e%b.template.rainbowColors.length]}">${b.escapeHtml(d[e])}</span>`);a.innerHTML=c.join(b.template.delimiter)},includeCodeInputInHighlightFunc:!0,preElementStyled:!0,isCode:!1,rainbowColors:a,delimiter:b,plugins:c}},character_limit(){return this.characterLimit([])},rainbow_text(a=["red","orangered","orange","goldenrod","gold","green","darkgreen","navy","blue","magenta"],b="",c=[]){return this.rainbowText(a,b,c)},custom(a=function(){},b=!0,c=!0,d=!1,e=[]){return{highlight:a,includeCodeInputInHighlightFunc:d,preElementStyled:b,isCode:c,plugins:e}}},plugins:new Proxy({},{get(a,b){if(a[b]==null)throw ReferenceError(`code-input: Plugin '${b}' 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 a[b]}}),Plugin:class{constructor(a){console.log("code-input: plugin: Created plugin"),a.forEach(a=>{let b=codeInput.wildcard2regex(a);null==b?codeInput.observedAttributes.push(a):codeInput.observedAttributes.regexp.push(b)})}beforeHighlight(){}afterHighlight(){}beforeElementsAdded(){}afterElementsAdded(){}attributeChanged(){}},CodeInput:class extends HTMLElement{constructor(){super()}_value="";textareaElement=null;preElement=null;codeElement=null;static formAssociated=!0;boundEventCallbacks={};pluginEvt(a,b){for(let c in this.template.plugins){let d=this.template.plugins[c];a in d&&(b===void 0?d[a](this):d[a](this,...b))}}update(a){if(!this.ignoreValueUpdate){if(null==this.textareaElement)return void this.addEventListener("code-input_load",()=>{this.update(a)});this.ignoreValueUpdate=!0,this.value=a,this.ignoreValueUpdate=!1,this.textareaElement.value!=a&&(this.textareaElement.value=a);let b=this.codeElement;"\n"==a[a.length-1]&&(a+=" "),b.innerHTML=this.escapeHtml(a),this.pluginEvt("beforeHighlight"),this.template.includeCodeInputInHighlightFunc?this.template.highlight(b,this):this.template.highlight(b),this.pluginEvt("afterHighlight")}}syncScroll(){let a=this.textareaElement,b=this.template.preElementStyled?this.preElement:this.codeElement;b.scrollTop=a.scrollTop,b.scrollLeft=a.scrollLeft}escapeHtml(a){return a.replace(/&/g,"&amp;").replace(/</g,"&lt;")}unescapeHtml(a){return a.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">")}getTemplate(){let a;return a=null==this.getAttribute("template")?codeInput.defaultTemplate:this.getAttribute("template"),a in codeInput.usedTemplates?codeInput.usedTemplates[a]:(a in codeInput.templateNotYetRegisteredQueue||(codeInput.templateNotYetRegisteredQueue[a]=[]),void codeInput.templateNotYetRegisteredQueue[a].push(this))}setup(){if(null!=this.textareaElement)return;this.classList.add("code-input_registered"),this.template.preElementStyled&&this.classList.add("code-input_pre-element-styled"),this.pluginEvt("beforeElementsAdded");let a=this.getAttribute("lang"),b=this.getAttribute("placeholder")||this.getAttribute("lang")||"",c=this.unescapeHtml(this.innerHTML)||this.getAttribute("value")||"";this.initialValue=c;let d=document.createElement("textarea");d.placeholder=b,""!=c&&(d.value=c),d.innerHTML=this.innerHTML,d.setAttribute("spellcheck","false"),this.innerHTML="",codeInput.textareaSyncAttributes.forEach(a=>{this.hasAttribute(a)&&d.setAttribute(a,this.getAttribute(a))}),codeInput.textareaSyncAttributes.regexp.forEach(a=>{for(const b of this.attributes)b.nodeName.match(a)&&d.setAttribute(b.nodeName,b.nodeValue)}),d.addEventListener("input",()=>{d.parentElement.update(d.value),d.parentElement.sync_scroll()}),d.addEventListener("scroll",()=>d.parentElement.sync_scroll()),this.textareaElement=d,this.append(d);let e=document.createElement("code"),f=document.createElement("pre");f.setAttribute("aria-hidden","true"),this.preElement=f,this.codeElement=e,f.append(e),this.append(f),this.template.isCode&&a!=null&&""!=a&&e.classList.add("language-"+a),this.pluginEvt("afterElementsAdded"),this.update(c),this.dispatchEvent(new CustomEvent("code-input_load"))}sync_scroll(){this.syncScroll()}escape_html(a){return this.escapeHtml(a)}get_template(){return this.getTemplate()}connectedCallback(){this.template=this.getTemplate(),this.template!=null&&(this.classList.add("code-input_registered"),codeInput.runOnceWindowLoaded(()=>{this.setup(),this.classList.add("code-input_loaded")},this)),this.mutationObserver=new MutationObserver(this.mutationObserverCallback.bind(this)),this.mutationObserver.observe(this,{attributes:!0,attributeOldValue:!0})}mutationObserverCallback(a){for(const b of a)if("attributes"===b.type){for(let a=0;a<codeInput.observedAttributes.length;a++)if(b.attributeName==codeInput.observedAttributes[a])return this.attributeChangedCallback(b.attributeName,b.oldValue,super.getAttribute(b.attributeName));for(let a=0;a<codeInput.observedAttributes.regexp.length;a++){const c=codeInput.observedAttributes.regexp[a];if(b.attributeName.match(c))return this.attributeChangedCallback(b.attributeName,b.oldValue,super.getAttribute(b.attributeName))}}}disconnectedCallback(){this.mutationObserver.disconnect()}attributeChangedCallback(a,b,c){if(this.isConnected)switch(this.pluginEvt("attributeChanged",[a,b,c]),a){case"value":this.value=c;break;case"placeholder":this.textareaElement.placeholder=c;break;case"template":this.template=codeInput.usedTemplates[c||codeInput.defaultTemplate],this.template.preElementStyled?this.classList.add("code-input_pre-element-styled"):this.classList.remove("code-input_pre-element-styled"),this.update(this.value);break;case"lang":let d=this.codeElement,e=this.textareaElement;if(null!=c&&(c=c.toLowerCase(),d.classList.contains(`language-${c}`)))break;b=b.toLowerCase(),d.classList.remove("language-"+b),d.parentElement.classList.remove("language-"+b),d.classList.remove("language-none"),d.parentElement.classList.remove("language-none"),null!=c&&""!=c&&d.classList.add("language-"+c),e.placeholder==b&&(e.placeholder=c),this.update(this.value);break;default:codeInput.textareaSyncAttributes.includes(a)?null==c||null==c?this.textareaElement.removeAttribute(a):this.textareaElement.setAttribute(a,c):codeInput.textareaSyncAttributes.regexp.forEach(b=>{a.match(b)&&(null==c?this.textareaElement.removeAttribute(a):this.textareaElement.setAttribute(a,c))})}}addEventListener(a,b,c=void 0){let d=b.bind(this);this.boundEventCallbacks[b]=d,codeInput.textareaSyncEvents.includes(a)?c===void 0?null==this.textareaElement?this.addEventListener("code-input_load",()=>{this.textareaElement.addEventListener(a,d)}):this.textareaElement.addEventListener(a,d):null==this.textareaElement?this.addEventListener("code-input_load",()=>{this.textareaElement.addEventListener(a,d,c)}):this.textareaElement.addEventListener(a,d,c):c===void 0?super.addEventListener(a,d):super.addEventListener(a,d,c)}removeEventListener(a,b,c=null){let d=this.boundEventCallbacks[b];"change"==a?null===c?this.textareaElement.removeEventListener("change",d):this.textareaElement.removeEventListener("change",d,c):"selectionchange"==a?null===c?this.textareaElement.removeEventListener("selectionchange",d):this.textareaElement.removeEventListener("selectionchange",d,c):super.removeEventListener(a,b,c)}get value(){return this._value}set value(a){return(null===a||void 0===a)&&(a=""),this._value=a,this.update(a),a}get placeholder(){return this.getAttribute("placeholder")}set placeholder(a){return this.setAttribute("placeholder",a)}get validity(){return this.textareaElement.validity}get validationMessage(){return this.textareaElement.validationMessage}setCustomValidity(a){return this.textareaElement.setCustomValidity(a)}checkValidity(){return this.textareaElement.checkValidity()}reportValidity(){return this.textareaElement.reportValidity()}pluginData={};formResetCallback(){this.update(this.initialValue)}},arrayWildcards2regex(a){for(let b=0;b<a.length;b++){const c=a[b];0>c.indexOf("*")||(a.regexp.push(new RegExp("^"+c.replace(/[/\-\\^$+?.()|[\]{}]/g,"\\$&").replace("*",".*")+"$","i")),a.splice(b--,1))}},wildcard2regex(a){return 0>a.indexOf("*")?null:new RegExp("^"+a.replace(/[/\-\\^$+?.()|[\]{}]/g,"\\$&").replace("*",".*")+"$","i")},runOnceWindowLoaded(a){codeInput.windowLoaded?a():window.addEventListener("load",a)},windowLoaded:!1};window.addEventListener("load",function(){codeInput.windowLoaded=!0}),Object.defineProperty(codeInput.textareaSyncAttributes,"regexp",{value:[],writable:!1,enumerable:!1,configurable:!1}),codeInput.observedAttributes=codeInput.observedAttributes.concat(codeInput.textareaSyncAttributes),Object.defineProperty(codeInput.observedAttributes,"regexp",{value:[],writable:!1,enumerable:!1,configurable:!1}),codeInput.arrayWildcards2regex(codeInput.textareaSyncAttributes),codeInput.arrayWildcards2regex(codeInput.observedAttributes),customElements.define("code-input",codeInput.CodeInput);
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@webcoder49/code-input",
3
- "version": "2.0.1",
3
+ "version": "2.1.0",
4
4
  "description": "Fully customisable, editable syntax-highlighted textareas.",
5
5
  "browser": "code-input.js",
6
6
  "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
7
+ "test": "echo \"This is a front-end library, not a Node library. Please see the README for how to use.\" && exit 1"
8
8
  },
9
9
  "repository": {
10
10
  "type": "git",
@@ -20,8 +20,8 @@
20
20
  ],
21
21
  "author": {
22
22
  "name": "WebCoder49",
23
- "email": "webcoder49.tutorials@gmail.com",
24
- "url": "https://webcoder49.github.io/"
23
+ "email": "hi@webcoder49.dev",
24
+ "url": "https://webcoder49.dev/"
25
25
  },
26
26
  "license": "MIT",
27
27
  "bugs": {
package/plugins/README.md CHANGED
@@ -1,6 +1,12 @@
1
1
  # Code-input: Plugins
2
2
  ## List Of Plugins
3
3
 
4
+ 💡 Do you just want to get a quick editor working? We suggest the [Indent](#indent) and [Prism Line Numbers](#prism-line-numbers) plugins.
5
+
6
+ **Lots of plugins are very customisable - please see the JavaScript files for parameters and if you want more features let us know via GitHub Issues.**
7
+
8
+ ---
9
+
4
10
  ### Autocomplete
5
11
  Display a popup under the caret using the text in the code-input element. This works well with autocomplete suggestions.
6
12
 
@@ -23,7 +29,7 @@ Files: [debounce-update.js](./debounce-update.js)
23
29
  [🚀 *CodePen Demo*](https://codepen.io/WebCoder49/pen/GRXyxzV)
24
30
 
25
31
  ### Indent
26
- Adds indentation using the `Tab` key, and auto-indents after a newline, as well as making it possible to indent/unindent multiple lines using Tab/Shift+Tab
32
+ Adds indentation using the `Tab` key, and auto-indents after a newline, as well as making it possible to indent/unindent multiple lines using Tab/Shift+Tab. **Supports tab characters and custom numbers of spaces as indentation.**
27
33
 
28
34
  Files: [indent.js](./indent.js)
29
35
 
@@ -60,7 +66,7 @@ Plugins allow you to add extra features to a template, like [automatic indentati
60
66
  hljs,
61
67
  [
62
68
  new codeInput.plugins.Autodetect(),
63
- new codeInput.plugins.Indent()
69
+ new codeInput.plugins.Indent(true, 2) // 2 spaces indentation
64
70
  ]
65
71
  )
66
72
  );
@@ -13,7 +13,7 @@ codeInput.plugins.Autocomplete = class extends codeInput.Plugin {
13
13
  }
14
14
  /* When a key is pressed, or scrolling occurs, update the autocomplete */
15
15
  updatePopup(codeInput, onlyScrolled) {
16
- let textarea = codeInput.querySelector("textarea");
16
+ let textarea = codeInput.textareaElement;
17
17
  let caretCoords = this.getCaretCoordinates(codeInput, textarea, textarea.selectionEnd, onlyScrolled);
18
18
  let popupElem = codeInput.querySelector(".code-input_autocomplete_popup");
19
19
  popupElem.style.top = caretCoords.top + "px";
@@ -33,7 +33,7 @@ codeInput.plugins.Autocomplete = class extends codeInput.Plugin {
33
33
  testPosElem.classList.add("code-input_autocomplete_testpos");
34
34
  codeInput.appendChild(testPosElem); // Styled like first pre, but first pre found to update
35
35
 
36
- let textarea = codeInput.querySelector("textarea");
36
+ let textarea = codeInput.textareaElement;
37
37
  textarea.addEventListener("keyup", this.updatePopup.bind(this, codeInput, false)); // Override this+args in bind - not just scrolling
38
38
  textarea.addEventListener("click", this.updatePopup.bind(this, codeInput, false)); // Override this+args in bind - not just scrolling
39
39
  textarea.addEventListener("scroll", this.updatePopup.bind(this, codeInput, true)); // Override this+args in bind - just scrolling
@@ -1 +1 @@
1
- codeInput.plugins.Autocomplete=class extends codeInput.Plugin{constructor(a){super([]),this.updatePopupCallback=a}updatePopup(a,b){let c=a.querySelector("textarea"),d=this.getCaretCoordinates(a,c,c.selectionEnd,b),e=a.querySelector(".code-input_autocomplete_popup");e.style.top=d.top+"px",e.style.left=d.left+"px",b||this.updatePopupCallback(e,c,c.selectionEnd)}afterElementsAdded(a){let b=document.createElement("div");b.classList.add("code-input_autocomplete_popup"),a.appendChild(b);let c=document.createElement("pre");c.classList.add("code-input_autocomplete_testpos"),a.appendChild(c);let d=a.querySelector("textarea");d.addEventListener("keyup",this.updatePopup.bind(this,a,!1)),d.addEventListener("click",this.updatePopup.bind(this,a,!1)),d.addEventListener("scroll",this.updatePopup.bind(this,a,!0))}getCaretCoordinates(a,b,c,d){let e;if(d){let d=a.querySelector(".code-input_autocomplete_testpos").querySelectorAll("span");if(2>d.length)return this.getCaretCoordinates(a,b,c,!1);e=d[1]}else{let d=a.querySelector(".code-input_autocomplete_testpos"),f=document.createElement("span");for(f.textContent=b.value.substring(0,c),e=document.createElement("span"),e.textContent=".";d.firstChild;)d.removeChild(d.firstChild);d.appendChild(f),d.appendChild(e)}return{top:e.offsetTop-b.scrollTop,left:e.offsetLeft-b.scrollLeft}}updatePopupCallback=function(){}};
1
+ codeInput.plugins.Autocomplete=class extends codeInput.Plugin{constructor(a){super([]),this.updatePopupCallback=a}updatePopup(a,b){let c=a.textareaElement,d=this.getCaretCoordinates(a,c,c.selectionEnd,b),e=a.querySelector(".code-input_autocomplete_popup");e.style.top=d.top+"px",e.style.left=d.left+"px",b||this.updatePopupCallback(e,c,c.selectionEnd)}afterElementsAdded(a){let b=document.createElement("div");b.classList.add("code-input_autocomplete_popup"),a.appendChild(b);let c=document.createElement("pre");c.classList.add("code-input_autocomplete_testpos"),a.appendChild(c);let d=a.textareaElement;d.addEventListener("keyup",this.updatePopup.bind(this,a,!1)),d.addEventListener("click",this.updatePopup.bind(this,a,!1)),d.addEventListener("scroll",this.updatePopup.bind(this,a,!0))}getCaretCoordinates(a,b,c,d){let e;if(d){let d=a.querySelector(".code-input_autocomplete_testpos").querySelectorAll("span");if(2>d.length)return this.getCaretCoordinates(a,b,c,!1);e=d[1]}else{let d=a.querySelector(".code-input_autocomplete_testpos"),f=document.createElement("span");for(f.textContent=b.value.substring(0,c),e=document.createElement("span"),e.textContent=".";d.firstChild;)d.removeChild(d.firstChild);d.appendChild(f),d.appendChild(e)}return{top:e.offsetTop-b.scrollTop,left:e.offsetLeft-b.scrollLeft}}updatePopupCallback=function(){}};
@@ -9,15 +9,15 @@ codeInput.plugins.Autodetect = class extends codeInput.Plugin {
9
9
  }
10
10
  /* Remove previous language class */
11
11
  beforeHighlight(codeInput) {
12
- let result_element = codeInput.querySelector("pre code");
13
- result_element.className = ""; // CODE
14
- result_element.parentElement.className = ""; // PRE
12
+ let resultElement = codeInput.codeElement;
13
+ resultElement.className = ""; // CODE
14
+ resultElement.parentElement.className = ""; // PRE
15
15
  }
16
16
  /* Get new language class and set `lang` attribute */
17
17
  afterHighlight(codeInput) {
18
- let result_element = codeInput.querySelector("pre code");
19
- let lang_class = result_element.className || result_element.parentElement.className;
20
- let lang = lang_class.match(/lang(\w|-)*/i)[0]; // Get word starting with lang...; Get outer bracket
18
+ let resultElement = codeInput.codeElement;
19
+ let langClass = resultElement.className || resultElement.parentElement.className;
20
+ let lang = langClass.match(/lang(\w|-)*/i)[0]; // Get word starting with lang...; Get outer bracket
21
21
  lang = lang.split("-")[1];
22
22
  if(lang == "undefined") {
23
23
  codeInput.removeAttribute("lang");
@@ -1 +1 @@
1
- codeInput.plugins.Autodetect=class extends codeInput.Plugin{constructor(){super([])}beforeHighlight(a){let b=a.querySelector("pre code");b.className="",b.parentElement.className=""}afterHighlight(a){let b=a.querySelector("pre code"),c=b.className||b.parentElement.className,d=c.match(/lang(\w|-)*/i)[0];d=d.split("-")[1],"undefined"==d?a.removeAttribute("lang"):a.setAttribute("lang",d)}};
1
+ codeInput.plugins.Autodetect=class extends codeInput.Plugin{constructor(){super([])}beforeHighlight(a){let b=a.codeElement;b.className="",b.parentElement.className=""}afterHighlight(a){let b=a.codeElement,c=b.className||b.parentElement.className,d=c.match(/lang(\w|-)*/i)[0];d=d.split("-")[1],"undefined"==d?a.removeAttribute("lang"):a.setAttribute("lang",d)}};
@@ -14,7 +14,6 @@ codeInput.plugins.DebounceUpdate = class extends codeInput.Plugin {
14
14
  }
15
15
  /* Runs before elements are added into a `code-input`; Params: codeInput element) */
16
16
  beforeElementsAdded(codeInput) {
17
- console.log(codeInput, "before elements added");
18
17
  this.update = codeInput.update.bind(codeInput); // Save previous update func
19
18
  codeInput.update = this.updateDebounced.bind(this, codeInput);
20
19
  }
@@ -1 +1 @@
1
- codeInput.plugins.DebounceUpdate=class extends codeInput.Plugin{constructor(a){super([]),this.delayMs=a}beforeElementsAdded(a){console.log(a,"before elements added"),this.update=a.update.bind(a),a.update=this.updateDebounced.bind(this,a)}updateDebounced(a,b){null!=this.debounceTimeout&&window.clearTimeout(this.debounceTimeout),this.debounceTimeout=window.setTimeout(()=>{this.update(b)},this.delayMs)}debounceTimeout=null;delayMs=0};
1
+ codeInput.plugins.DebounceUpdate=class extends codeInput.Plugin{constructor(a){super([]),this.delayMs=a}beforeElementsAdded(a){this.update=a.update.bind(a),a.update=this.updateDebounced.bind(this,a)}updateDebounced(a,b){null!=this.debounceTimeout&&window.clearTimeout(this.debounceTimeout),this.debounceTimeout=window.setTimeout(()=>{this.update(b)},this.delayMs)}debounceTimeout=null;delayMs=0};
package/plugins/indent.js CHANGED
@@ -4,151 +4,175 @@
4
4
  * Files: indent.js
5
5
  */
6
6
  codeInput.plugins.Indent = class extends codeInput.Plugin {
7
- constructor() {
7
+
8
+ numSpaces;
9
+ indentation = "\t";
10
+ indentationNumChars = 1;
11
+
12
+ /**
13
+ * Create an indentation plugin to pass into a template
14
+ * @param {Boolean} defaultSpaces Should the Tab key enter spaces rather than tabs? Defaults to false.
15
+ * @param {Number} numSpaces How many spaces is each tab character worth? Defaults to 4.
16
+ */
17
+ constructor(defaultSpaces=false, numSpaces=4) {
8
18
  super([]); // No observed attributes
19
+
20
+ this.numSpaces = numSpaces;
21
+ if(defaultSpaces) {
22
+ this.indentation = "";
23
+ for(let i = 0; i < numSpaces; i++) {
24
+ this.indentation += " ";
25
+ }
26
+ this.indentationNumChars = numSpaces;
27
+ }
9
28
  }
10
29
 
11
30
  /* Add keystroke events */
12
31
  afterElementsAdded(codeInput) {
13
- let textarea = codeInput.querySelector("textarea");
14
- textarea.addEventListener('keydown', (event) => { this.check_tab(codeInput, event); this.check_enter(codeInput, event); });
32
+ let textarea = codeInput.textareaElement;
33
+ textarea.addEventListener('keydown', (event) => { this.checkTab(codeInput, event); this.checkEnter(codeInput, event); this.checkBackspace(codeInput, event); });
15
34
  }
16
35
 
17
36
  /* Event handlers */
18
- check_tab(codeInput, event) {
37
+ checkTab(codeInput, event) {
19
38
  if(event.key != "Tab") {
20
39
  return;
21
40
  }
22
- let input_element = codeInput.querySelector("textarea");
23
- let code = input_element.value;
41
+ let inputElement = codeInput.textareaElement;
24
42
  event.preventDefault(); // stop normal
25
43
 
26
- if(!event.shiftKey && input_element.selectionStart == input_element.selectionEnd) {
27
- // Just place a tab here.
28
- document.execCommand("insertText", false, "\t");
44
+ if(!event.shiftKey && inputElement.selectionStart == inputElement.selectionEnd) {
45
+ // Just place a tab/spaces here.
46
+ document.execCommand("insertText", false, this.indentation);
29
47
 
30
48
  } else {
31
- let lines = input_element.value.split("\n");
32
- let letter_i = 0;
33
-
34
- let selection_start = input_element.selectionStart; // where cursor moves after tab - moving forward by 1 indent
35
- let selection_end = input_element.selectionEnd; // where cursor moves after tab - moving forward by 1 indent
49
+ let lines = inputElement.value.split("\n");
50
+ let letterI = 0;
36
51
 
37
- let number_indents = 0;
38
- let first_line_indents = 0;
52
+ let selectionStartI = inputElement.selectionStart; // where cursor moves after tab - moving forward by 1 indent
53
+ let selectionEndI = inputElement.selectionEnd; // where cursor moves after tab - moving forward by 1 indent
39
54
 
40
- for (let i = 0; i < lines.length; i++) {
41
- // console.log(lines[i], ": start", selection_start, letter_i + lines[i].length + 1, "&& end", selection_end , letter_i + 1)
42
- if((selection_start <= letter_i+lines[i].length && selection_end >= letter_i + 1)
43
- || (selection_start == selection_end && selection_start <= letter_i+lines[i].length+1 && selection_end >= letter_i)) { // + 1 so newlines counted
55
+ for (let i = 0; i < lines.length; i++) {
56
+ if((selectionStartI <= letterI+lines[i].length && selectionEndI >= letterI + 1)
57
+ || (selectionStartI == selectionEndI && selectionStartI <= letterI+lines[i].length+1 && selectionEndI >= letterI)) { // + 1 so newlines counted
44
58
  // Starts before or at last char and ends after or at first char
45
59
  if(event.shiftKey) {
46
- if(lines[i][0] == "\t") {
47
- // Remove first tab
48
- input_element.selectionStart = letter_i;
49
- input_element.selectionEnd = letter_i+1;
60
+ if(lines[i].substring(0, this.indentationNumChars) == this.indentation) {
61
+ // Remove first indent
62
+ inputElement.selectionStart = letterI;
63
+ inputElement.selectionEnd = letterI+this.indentationNumChars;
50
64
  document.execCommand("delete", false, "");
51
65
 
52
66
  // Change selection
53
- if(selection_start > letter_i) { // Indented outside selection
54
- selection_start--;
67
+ if(selectionStartI > letterI) { // Indented outside selection
68
+ selectionStartI = Math.max(selectionStartI - this.indentationNumChars, letterI); // Don't move to before indent
55
69
  }
56
- selection_end--;
57
- letter_i--;
70
+ selectionEndI -= this.indentationNumChars;
71
+ letterI -= this.indentationNumChars;
58
72
  }
59
73
  } else {
60
74
  // Add tab at start
61
- input_element.selectionStart = letter_i;
62
- input_element.selectionEnd = letter_i;
63
- document.execCommand("insertText", false, "\t");
75
+ inputElement.selectionStart = letterI;
76
+ inputElement.selectionEnd = letterI;
77
+ document.execCommand("insertText", false, this.indentation);
64
78
 
65
79
  // Change selection
66
- if(selection_start > letter_i) { // Indented outside selection
67
- selection_start++;
80
+ if(selectionStartI > letterI) { // Indented outside selection
81
+ selectionStartI += this.indentationNumChars;
68
82
  }
69
- selection_end++;
70
- letter_i++;
83
+ selectionEndI += this.indentationNumChars;
84
+ letterI += this.indentationNumChars;
71
85
  }
72
86
  }
73
87
 
74
- letter_i += lines[i].length+1; // newline counted
88
+ letterI += lines[i].length+1; // newline counted
75
89
  }
76
- // input_element.value = lines.join("\n");
77
90
 
78
91
  // move cursor
79
- input_element.selectionStart = selection_start;
80
- input_element.selectionEnd = selection_end;
92
+ inputElement.selectionStart = selectionStartI;
93
+ inputElement.selectionEnd = selectionEndI;
81
94
  }
82
95
 
83
- codeInput.update(input_element.value);
96
+ codeInput.update(inputElement.value);
84
97
  }
85
98
 
86
- check_enter(codeInput, event) {
99
+ checkEnter(codeInput, event) {
87
100
  if(event.key != "Enter") {
88
101
  return;
89
102
  }
90
- event.preventDefault(); // stop normal
103
+ event.preventDefault(); // Stop normal \n only
91
104
 
92
- let input_element = codeInput.querySelector("textarea");
93
- let lines = input_element.value.split("\n");
94
- let letter_i = 0;
95
- let current_line = lines.length - 1;
96
- let new_line = "";
97
- let number_indents = 0;
105
+ let inputElement = codeInput.querySelector("textarea");
106
+ let lines = inputElement.value.split("\n");
107
+ let letterI = 0;
108
+ let currentLineI = lines.length - 1;
109
+ let newLine = "";
110
+ let numberIndents = 0;
98
111
 
99
112
  // find the index of the line our cursor is currently on
100
113
  for (let i = 0; i < lines.length; i++) {
101
- letter_i += lines[i].length + 1;
102
- if(input_element.selectionEnd <= letter_i) {
103
- current_line = i;
114
+ letterI += lines[i].length + 1;
115
+ if(inputElement.selectionEnd <= letterI) {
116
+ currentLineI = i;
104
117
  break;
105
118
  }
106
119
  }
107
120
 
108
121
  // count the number of indents the current line starts with (up to our cursor position in the line)
109
- let cursor_pos_in_line = lines[current_line].length - (letter_i - input_element.selectionEnd) + 1;
110
- for (let i = 0; i < cursor_pos_in_line; i++) {
111
- if (lines[current_line][i] == "\t") {
112
- number_indents++;
122
+ let cursorPosInLine = lines[currentLineI].length - (letterI - inputElement.selectionEnd) + 1;
123
+ for (let i = 0; i < cursorPosInLine; i += this.indentationNumChars) {
124
+ if (lines[currentLineI].substring(i, i+this.indentationNumChars) == this.indentation) {
125
+ numberIndents++;
113
126
  } else {
114
127
  break;
115
128
  }
116
129
  }
117
130
 
118
131
  // determine the text before and after the cursor and chop the current line at the new line break
119
- let text_after_cursor = "";
120
- if (cursor_pos_in_line != lines[current_line].length) {
121
- text_after_cursor = lines[current_line].substring(cursor_pos_in_line);
122
- lines[current_line] = lines[current_line].substring(0, cursor_pos_in_line);
132
+ let textAfterCursor = "";
133
+ if (cursorPosInLine != lines[currentLineI].length) {
134
+ textAfterCursor = lines[currentLineI].substring(cursorPosInLine);
135
+ lines[currentLineI] = lines[currentLineI].substring(0, cursorPosInLine);
123
136
  }
124
137
 
125
138
  // insert our indents and any text from the previous line that might have been after the line break
126
- for (let i = 0; i < number_indents; i++) {
127
- new_line += "\t";
139
+ for (let i = 0; i < numberIndents; i++) {
140
+ newLine += this.indentation;
128
141
  }
129
142
 
130
143
  // save the current cursor position
131
- let selection_start = input_element.selectionStart;
132
- let selection_end = input_element.selectionEnd;
144
+ let selectionStartI = inputElement.selectionStart;
133
145
 
134
- document.execCommand("insertText", false, "\n" + new_line); // Write new line, including auto-indentation
146
+ document.execCommand("insertText", false, "\n" + newLine); // Write new line, including auto-indentation
135
147
 
136
148
  // move cursor to new position
137
- input_element.selectionStart = selection_start + number_indents + 1; // count the indent level and the newline character
138
- input_element.selectionEnd = selection_start + number_indents + 1;
149
+ inputElement.selectionStart = selectionStartI + numberIndents*this.indentationNumChars + 1; // count the indent level and the newline character
150
+ inputElement.selectionEnd = inputElement.selectionStart;
139
151
 
140
- codeInput.update(input_element.value);
152
+
153
+ // Scroll down to cursor if necessary
154
+ let paddingTop = Number(getComputedStyle(inputElement).paddingTop.replace("px", ""));
155
+ let lineHeight = Number(getComputedStyle(inputElement).lineHeight.replace("px", ""));
156
+ let inputHeight = Number(getComputedStyle(inputElement).height.replace("px", ""));
157
+ if(currentLineI*lineHeight + lineHeight*2 + paddingTop >= inputElement.scrollTop + inputHeight) { // Cursor too far down
158
+ inputElement.scrollBy(0, Number(getComputedStyle(inputElement).lineHeight.replace("px", "")))
159
+ }
141
160
 
161
+ codeInput.update(inputElement.value);
162
+ }
142
163
 
143
- // Update scrolls
144
- input_element.scrollLeft = 0;
145
- // Move down 1 line
146
- let lineHeight = Number(getComputedStyle(input_element).lineHeight.split(0, -2));
147
- // console.log(getComputedStyle(input_element).lineHeight);
148
- if(lineHeight == NaN && getComputedStyle(input_element).lineHeight.split(-2) == "px") {
149
- input_element.scrollTop += lineHeight;
150
- } else {
151
- input_element.scrollTop += 20; // px
164
+ checkBackspace(codeInput, event) {
165
+ if(event.key != "Backspace" || this.indentationNumChars == 1) {
166
+ return; // Normal backspace
167
+ }
168
+
169
+ let inputElement = codeInput.textareaElement;
170
+
171
+ if(inputElement.selectionStart == inputElement.selectionEnd && codeInput.value.substring(inputElement.selectionStart - this.indentationNumChars, inputElement.selectionStart) == this.indentation) {
172
+ // Indentation before cursor = delete it
173
+ inputElement.selectionStart -= this.indentationNumChars;
174
+ event.preventDefault();
175
+ document.execCommand("delete", false, "");
152
176
  }
153
177
  }
154
178
  }
@@ -1 +1 @@
1
- codeInput.plugins.Indent=class extends codeInput.Plugin{constructor(){super([])}afterElementsAdded(a){let b=a.querySelector("textarea");b.addEventListener("keydown",b=>{this.check_tab(a,b),this.check_enter(a,b)})}check_tab(a,b){if("Tab"!=b.key)return;let c=a.querySelector("textarea"),d=c.value;if(b.preventDefault(),!b.shiftKey&&c.selectionStart==c.selectionEnd)document.execCommand("insertText",!1,"\t");else{let a=c.value.split("\n"),d=0,e=c.selectionStart,f=c.selectionEnd;for(let g=0;g<a.length;g++)(e<=d+a[g].length&&f>=d+1||e==f&&e<=d+a[g].length+1&&f>=d)&&(b.shiftKey?"\t"==a[g][0]&&(c.selectionStart=d,c.selectionEnd=d+1,document.execCommand("delete",!1,""),e>d&&e--,f--,d--):(c.selectionStart=d,c.selectionEnd=d,document.execCommand("insertText",!1,"\t"),e>d&&e++,f++,d++)),d+=a[g].length+1;c.selectionStart=e,c.selectionEnd=f}a.update(c.value)}check_enter(a,b){if("Enter"!=b.key)return;b.preventDefault();let c=a.querySelector("textarea"),d=c.value.split("\n"),e=0,f=d.length-1,g="",h=0;for(let g=0;g<d.length;g++)if(e+=d[g].length+1,c.selectionEnd<=e){f=g;break}let j=d[f].length-(e-c.selectionEnd)+1;for(let c=0;c<j&&"\t"==d[f][c];c++)h++;let k="";j!=d[f].length&&(k=d[f].substring(j),d[f]=d[f].substring(0,j));for(let c=0;c<h;c++)g+="\t";let l=c.selectionStart,m=c.selectionEnd;document.execCommand("insertText",!1,"\n"+g),c.selectionStart=l+h+1,c.selectionEnd=l+h+1,a.update(c.value),c.scrollLeft=0;let n=+getComputedStyle(c).lineHeight.split(0,-2);c.scrollTop+=n==NaN&&"px"==getComputedStyle(c).lineHeight.split(-2)?n:20}};
1
+ codeInput.plugins.Indent=class extends codeInput.Plugin{numSpaces;indentation="\t";indentationNumChars=1;constructor(a=!1,b=4){if(super([]),this.numSpaces=b,a){this.indentation="";for(let a=0;a<b;a++)this.indentation+=" ";this.indentationNumChars=b}}afterElementsAdded(a){let b=a.textareaElement;b.addEventListener("keydown",b=>{this.checkTab(a,b),this.checkEnter(a,b),this.checkBackspace(a,b)})}checkTab(a,b){var c=Math.max;if("Tab"==b.key){let d=a.textareaElement;if(b.preventDefault(),!b.shiftKey&&d.selectionStart==d.selectionEnd)document.execCommand("insertText",!1,this.indentation);else{let a=d.value.split("\n"),e=0,f=d.selectionStart,g=d.selectionEnd;for(let h=0;h<a.length;h++)(f<=e+a[h].length&&g>=e+1||f==g&&f<=e+a[h].length+1&&g>=e)&&(b.shiftKey?a[h].substring(0,this.indentationNumChars)==this.indentation&&(d.selectionStart=e,d.selectionEnd=e+this.indentationNumChars,document.execCommand("delete",!1,""),f>e&&(f=c(f-this.indentationNumChars,e)),g-=this.indentationNumChars,e-=this.indentationNumChars):(d.selectionStart=e,d.selectionEnd=e,document.execCommand("insertText",!1,this.indentation),f>e&&(f+=this.indentationNumChars),g+=this.indentationNumChars,e+=this.indentationNumChars)),e+=a[h].length+1;d.selectionStart=f,d.selectionEnd=g}a.update(d.value)}}checkEnter(a,b){if("Enter"!=b.key)return;b.preventDefault();let c=a.querySelector("textarea"),d=c.value.split("\n"),e=0,f=d.length-1,g="",h=0;for(let g=0;g<d.length;g++)if(e+=d[g].length+1,c.selectionEnd<=e){f=g;break}let j=d[f].length-(e-c.selectionEnd)+1;for(let c=0;c<j&&d[f].substring(c,c+this.indentationNumChars)==this.indentation;c+=this.indentationNumChars)h++;let k="";j!=d[f].length&&(k=d[f].substring(j),d[f]=d[f].substring(0,j));for(let c=0;c<h;c++)g+=this.indentation;let l=c.selectionStart;document.execCommand("insertText",!1,"\n"+g),c.selectionStart=l+h*this.indentationNumChars+1,c.selectionEnd=c.selectionStart;let m=+getComputedStyle(c).paddingTop.replace("px",""),n=+getComputedStyle(c).lineHeight.replace("px",""),o=+getComputedStyle(c).height.replace("px","");f*n+2*n+m>=c.scrollTop+o&&c.scrollBy(0,+getComputedStyle(c).lineHeight.replace("px","")),a.update(c.value)}checkBackspace(a,b){if("Backspace"==b.key&&1!=this.indentationNumChars){let c=a.textareaElement;c.selectionStart==c.selectionEnd&&a.value.substring(c.selectionStart-this.indentationNumChars,c.selectionStart)==this.indentation&&(c.selectionStart-=this.indentationNumChars,b.preventDefault(),document.execCommand("delete",!1,""))}}};
@@ -143,8 +143,6 @@ codeInput.plugins.SpecialChars = class extends codeInput.Plugin {
143
143
  // Calculate darkness
144
144
  text_color = color_brightness < 128 ? "white" : "black";
145
145
 
146
- // console.log(background_color, color_brightness, text_color);
147
-
148
146
  this.cachedColors[ascii_code] = [background_color, text_color];
149
147
  return [background_color, text_color];
150
148
  } else {
@@ -172,7 +170,6 @@ codeInput.plugins.SpecialChars = class extends codeInput.Plugin {
172
170
  }
173
171
 
174
172
  // Ensure font the same
175
- // console.log(font);
176
173
  this.canvasContext.font = font;
177
174
 
178
175
  // Try to get width from canvas
@@ -186,33 +183,6 @@ codeInput.plugins.SpecialChars = class extends codeInput.Plugin {
186
183
 
187
184
  this.cachedWidths[font][char] = width;
188
185
 
189
- // console.log(this.cachedWidths);
190
186
  return width;
191
187
  }
192
-
193
- // getCharacterWidth(char) { // Doesn't work for now - from StackOverflow suggestion https://stackoverflow.com/a/76146120/21785620
194
- // let textarea = codeInput.pluginData.specialChars.textarea;
195
-
196
- // // Create a temporary element to measure the width of the character
197
- // const span = document.createElement('span');
198
- // span.textContent = char;
199
-
200
- // // Copy the textarea's font to the temporary element
201
- // span.style.fontSize = window.getComputedStyle(textarea).fontSize;
202
- // span.style.fontFamily = window.getComputedStyle(textarea).fontFamily;
203
- // span.style.fontWeight = window.getComputedStyle(textarea).fontWeight;
204
- // span.style.visibility = 'hidden';
205
- // span.style.position = 'absolute';
206
-
207
- // // Add the temporary element to the document so we can measure its width
208
- // document.body.appendChild(span);
209
-
210
- // // Get the width of the character in pixels
211
- // const width = span.offsetWidth;
212
-
213
- // // Remove the temporary element from the document
214
- // document.body.removeChild(span);
215
-
216
- // return width;
217
- // }
218
188
  }