├── .github └── workflows │ ├── minify.yml │ └── npm-publish.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── code-input.css ├── code-input.d.ts ├── code-input.js ├── code-input.min.css ├── code-input.min.js ├── package.json ├── plugins ├── README.md ├── auto-close-brackets.js ├── auto-close-brackets.min.js ├── autocomplete.css ├── autocomplete.js ├── autocomplete.min.css ├── autocomplete.min.js ├── autodetect.js ├── autodetect.min.js ├── find-and-replace.css ├── find-and-replace.js ├── find-and-replace.min.css ├── find-and-replace.min.js ├── go-to-line.css ├── go-to-line.js ├── go-to-line.min.css ├── go-to-line.min.js ├── indent.js ├── indent.min.js ├── prism-line-numbers.css ├── prism-line-numbers.min.css ├── select-token-callbacks.js ├── select-token-callbacks.min.js ├── special-chars.css ├── special-chars.js ├── special-chars.min.css ├── special-chars.min.js ├── test.js └── test.min.js └── tests ├── hljs.html ├── i18n.html ├── prism-match-braces-compatibility.js ├── prism-match-braces-compatibility.min.js ├── prism.html ├── tester.js └── tester.min.js /.github/workflows/minify.yml: -------------------------------------------------------------------------------- 1 | name: Auto-minify 2 | on: 3 | push: 4 | branches: 5 | - main 6 | jobs: 7 | Minify: 8 | runs-on: ubuntu-latest 9 | steps: 10 | # Checks-out your repository under $GITHUB_WORKSPACE, so auto-minify job can access it 11 | - uses: actions/checkout@v2 12 | 13 | - name: Auto Minify 14 | uses: nizarmah/auto-minify@v2.1 15 | 16 | # Auto commits minified files to the repository 17 | # Ignore it if you don't want to commit the files to the repository 18 | - name: Auto committing minified files 19 | uses: stefanzweifel/git-auto-commit-action@v4 20 | with: 21 | commit_message: "Auto Minified JS and CSS files" 22 | branch: ${{ github.ref }} -------------------------------------------------------------------------------- /.github/workflows/npm-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will publish a package to GitHub Packages when a release is created 2 | # For more information see: https://docs.github.com/en/actions/publishing-packages/publishing-nodejs-packages 3 | 4 | name: Node.js Package 5 | 6 | on: 7 | release: 8 | types: [created] 9 | 10 | jobs: 11 | publish-npm: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v3 15 | - uses: actions/setup-node@v3 16 | with: 17 | node-version: 16 18 | registry-url: https://registry.npmjs.org/ 19 | - run: npm publish 20 | env: 21 | NODE_AUTH_TOKEN: ${{secrets.npm_token}} 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | debug.html 3 | debug/ -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 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. 131 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 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 | We will generally *not* consider the following contributions: 10 | * Excess functionality and/or complexity in the main code-input files - these types of contributions should go in the plugin folder instead. 11 | * Issues that have been closed as not planned in the past (you can search the issue list to check), unless you bring a change that overcomes the reason they were not planned. 12 | 13 | This said, if you're not sure whether your change will be accepted, please ask in an issue. 14 | 15 | --- 16 | 17 | To keep this community productive and enjoyable, please [don't break our code of conduct](https://github.com/WebCoder49/code-input/blob/main/CODE_OF_CONDUCT.md). 18 | 19 | --- 20 | # Ways you could contribute: 21 | ## 1. I've found a bug but don't know how / don't have time to fix it. 22 | 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. 23 | 24 | ## 2. I have implemented a feature / have thought of a potential feature for the library and think it could be useful for others. 25 | 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. 26 | 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. 27 | 28 | ## 3. I want to contribute code that I need / have seen in the Issues. 29 | 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. 30 | 31 | 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). 32 | 33 | In the pull request, include the code updates for your feature / bug, and if you're adding a new feature make sure you comment your code so it's understandable to future contributors, and if you can, add unit tests for it in tests/tester.js. If you have any questions, just let me (@WebCoder49) know! 34 | 35 | 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. 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 WebCoder49 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # code-input 2 | 3 | ![Click to Switch](https://img.shields.io/static/v1?label=&message=Click%20to%20Switch:%20&color=grey&style=for-the-badge)[![GitHub](https://img.shields.io/static/v1?label=&message=GitHub&color=navy&style=for-the-badge&logo=github)](https://github.com/WebCoder49/code-input)[![NPM](https://img.shields.io/static/v1?label=&message=NPM&color=red&style=for-the-badge&logo=npm)](https://www.npmjs.com/package/@webcoder49/code-input) 4 | 5 | [![View License](https://img.shields.io/github/license/webcoder49/code-input?style=for-the-badge)](LICENSE) [![View Releases](https://img.sHields.io/github/v/release/webcoder49/code-input?style=for-the-badge)](https://github.com/WebCoder49/code-input/releases) [![View the demo on CodePen](https://img.shields.io/static/v1?label=Demo&message=on%20CodePen&color=orange&logo=codepen&style=for-the-badge)](https://codepen.io/WebCoder49/full/jOypJOx) 6 | 7 | > ___Fully customisable, editable syntax-highlighted textareas that can be placed in any HTML form.___ [[🚀 View the Demo](https://codepen.io/WebCoder49/full/jOypJOx)] 8 | 9 | ![Using code-input with many different themes](https://user-images.githubusercontent.com/69071853/133924472-05edde5c-23e7-4350-a41b-5a74d2dc1a9a.gif) 10 | *This demonstration uses themes from [Prism.js](https://prismjs.com/) and [highlight.js](https://highlightjs.org/), two syntax-highlighting programs which work well with and have compatibility built-in with code-input.* 11 | 12 | *A frontend JavaScript library, with:*
13 | [![TypeScript Bindings - Click to Use](https://img.shields.io/static/v1?label=TypeScript%20Bindings&message=Click%20to%20Use&style=for-the-badge&color=blue&logo=typescript&logoColor=white)](https://github.com/WebCoder49/code-input-for-typescript) 14 | 15 | --- 16 | 17 | ## What does it do? 18 | **`code-input`** lets you **turn any ordinary JavaScript syntax-highlighting theme and program into customisable syntax-highlighted textareas** using an HTML custom element. It uses vanilla CSS to superimpose a `textarea` on a `pre code` block, then handles indentations, scrolling and fixes any resulting bugs with JavaScript. To see how it works behind the scenes (not how to use this library), please see [this CSS-Tricks article](https://css-tricks.com/creating-an-editable-textarea-that-supports-syntax-highlighted-code/ "Creating an Editable Textarea That Supports Syntax-Highlighted Code") I wrote. 19 | 20 | ## What are the advantages of using code-input, and what can it be used for? 21 | Unlike other front-end code-editor projects, the simplicity of how `code-input` works means it is **highly customisable**. As it is not a full-featured editor, you can **choose what features you want it to include, and use your favourite syntax-highlighting algorithms and themes**. 22 | 23 | The `` element works like a ` 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 196 | 197 | 198 | -------------------------------------------------------------------------------- /tests/prism-match-braces-compatibility.js: -------------------------------------------------------------------------------- 1 | /* Modified from https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/match-braces/prism-match-braces.js 2 | to enable codeInput SelectTokenCallbacks compatibility. Use: 3 | new codeInput.plugins.SelectTokenCallbacks(new codeInput.plugins.SelectTokenCallbacks.TokenSelectorCallbacks(selectBrace, deselectAllBraces), true) */ 4 | // Additions on lines 6-10, and lines 84-98. 5 | 6 | // code-input modification: ADD 7 | // Callbacks 8 | let selectBrace; 9 | let deselectAllBraces; 10 | // END code-input modification 11 | (function () { 12 | 13 | if (typeof Prism === 'undefined' || typeof document === 'undefined') { 14 | return; 15 | } 16 | 17 | function mapClassName(name) { 18 | var customClass = Prism.plugins.customClass; 19 | if (customClass) { 20 | return customClass.apply(name, 'none'); 21 | } else { 22 | return name; 23 | } 24 | } 25 | 26 | var PARTNER = { 27 | '(': ')', 28 | '[': ']', 29 | '{': '}', 30 | }; 31 | 32 | // The names for brace types. 33 | // These names have two purposes: 1) they can be used for styling and 2) they are used to pair braces. Only braces 34 | // of the same type are paired. 35 | var NAMES = { 36 | '(': 'brace-round', 37 | '[': 'brace-square', 38 | '{': 'brace-curly', 39 | }; 40 | 41 | // A map for brace aliases. 42 | // This is useful for when some braces have a prefix/suffix as part of the punctuation token. 43 | var BRACE_ALIAS_MAP = { 44 | '${': '{', // JS template punctuation (e.g. `foo ${bar + 1}`) 45 | }; 46 | 47 | var LEVEL_WARP = 12; 48 | 49 | var pairIdCounter = 0; 50 | 51 | var BRACE_ID_PATTERN = /^(pair-\d+-)(close|open)$/; 52 | 53 | /** 54 | * Returns the brace partner given one brace of a brace pair. 55 | * 56 | * @param {HTMLElement} brace 57 | * @returns {HTMLElement} 58 | */ 59 | function getPartnerBrace(brace) { 60 | var match = BRACE_ID_PATTERN.exec(brace.id); 61 | return document.querySelector('#' + match[1] + (match[2] == 'open' ? 'close' : 'open')); 62 | } 63 | 64 | /** 65 | * @this {HTMLElement} 66 | */ 67 | function hoverBrace() { 68 | if (!Prism.util.isActive(this, 'brace-hover', true)) { 69 | return; 70 | } 71 | 72 | [this, getPartnerBrace(this)].forEach(function (e) { 73 | e.classList.add(mapClassName('brace-hover')); 74 | }); 75 | } 76 | /** 77 | * @this {HTMLElement} 78 | */ 79 | function leaveBrace() { 80 | [this, getPartnerBrace(this)].forEach(function (e) { 81 | e.classList.remove(mapClassName('brace-hover')); 82 | }); 83 | } 84 | // code-input modification: ADD 85 | selectBrace = (token) => { 86 | if(BRACE_ID_PATTERN.test(token.id)) { // Check it's a brace 87 | hoverBrace.apply(token); // Move the brace from a this to a parameter 88 | } 89 | }; 90 | deselectAllBraces = (tokenContainer) => { 91 | // Remove selected class 92 | let selectedClassTokens = tokenContainer.getElementsByClassName(mapClassName('brace-hover')); 93 | // Use it like a queue, because as elements have their class name removed they are live-removed from the collection. 94 | while(selectedClassTokens.length > 0) { 95 | selectedClassTokens[0].classList.remove(mapClassName('brace-hover')); 96 | } 97 | }; // Moves the brace from a this to a parameter 98 | // end code-input modification 99 | /** 100 | * @this {HTMLElement} 101 | */ 102 | function clickBrace() { 103 | if (!Prism.util.isActive(this, 'brace-select', true)) { 104 | return; 105 | } 106 | 107 | [this, getPartnerBrace(this)].forEach(function (e) { 108 | e.classList.add(mapClassName('brace-selected')); 109 | }); 110 | } 111 | 112 | Prism.hooks.add('complete', function (env) { 113 | 114 | /** @type {HTMLElement} */ 115 | var code = env.element; 116 | var pre = code.parentElement; 117 | 118 | if (!pre || pre.tagName != 'PRE') { 119 | return; 120 | } 121 | 122 | // find the braces to match 123 | /** @type {string[]} */ 124 | var toMatch = []; 125 | if (Prism.util.isActive(code, 'match-braces')) { 126 | toMatch.push('(', '[', '{'); 127 | } 128 | 129 | if (toMatch.length == 0) { 130 | // nothing to match 131 | return; 132 | } 133 | 134 | if (!pre.__listenerAdded) { 135 | // code blocks might be highlighted more than once 136 | pre.addEventListener('mousedown', function removeBraceSelected() { 137 | // the code element might have been replaced 138 | var code = pre.querySelector('code'); 139 | var className = mapClassName('brace-selected'); 140 | Array.prototype.slice.call(code.querySelectorAll('.' + className)).forEach(function (e) { 141 | e.classList.remove(className); 142 | }); 143 | }); 144 | Object.defineProperty(pre, '__listenerAdded', { value: true }); 145 | } 146 | 147 | /** @type {HTMLSpanElement[]} */ 148 | var punctuation = Array.prototype.slice.call( 149 | code.querySelectorAll('span.' + mapClassName('token') + '.' + mapClassName('punctuation')) 150 | ); 151 | 152 | /** @type {{ index: number, open: boolean, element: HTMLElement }[]} */ 153 | var allBraces = []; 154 | 155 | toMatch.forEach(function (open) { 156 | var close = PARTNER[open]; 157 | var name = mapClassName(NAMES[open]); 158 | 159 | /** @type {[number, number][]} */ 160 | var pairs = []; 161 | /** @type {number[]} */ 162 | var openStack = []; 163 | 164 | for (var i = 0; i < punctuation.length; i++) { 165 | var element = punctuation[i]; 166 | if (element.childElementCount == 0) { 167 | var text = element.textContent; 168 | text = BRACE_ALIAS_MAP[text] || text; 169 | if (text === open) { 170 | allBraces.push({ index: i, open: true, element: element }); 171 | element.classList.add(name); 172 | element.classList.add(mapClassName('brace-open')); 173 | openStack.push(i); 174 | } else if (text === close) { 175 | allBraces.push({ index: i, open: false, element: element }); 176 | element.classList.add(name); 177 | element.classList.add(mapClassName('brace-close')); 178 | if (openStack.length) { 179 | pairs.push([i, openStack.pop()]); 180 | } 181 | } 182 | } 183 | } 184 | 185 | pairs.forEach(function (pair) { 186 | var pairId = 'pair-' + (pairIdCounter++) + '-'; 187 | 188 | var opening = punctuation[pair[0]]; 189 | var closing = punctuation[pair[1]]; 190 | 191 | opening.id = pairId + 'open'; 192 | closing.id = pairId + 'close'; 193 | 194 | [opening, closing].forEach(function (e) { 195 | e.addEventListener('mouseenter', hoverBrace); 196 | e.addEventListener('mouseleave', leaveBrace); 197 | e.addEventListener('click', clickBrace); 198 | }); 199 | }); 200 | }); 201 | 202 | var level = 0; 203 | allBraces.sort(function (a, b) { return a.index - b.index; }); 204 | allBraces.forEach(function (brace) { 205 | if (brace.open) { 206 | brace.element.classList.add(mapClassName('brace-level-' + (level % LEVEL_WARP + 1))); 207 | level++; 208 | } else { 209 | level = Math.max(0, level - 1); 210 | brace.element.classList.add(mapClassName('brace-level-' + (level % LEVEL_WARP + 1))); 211 | } 212 | }); 213 | }); 214 | 215 | }()); -------------------------------------------------------------------------------- /tests/prism-match-braces-compatibility.min.js: -------------------------------------------------------------------------------- 1 | let selectBrace,deselectAllBraces;(function(){function a(a){var b=Prism.plugins.customClass;return b?b.apply(a,"none"):a}function b(a){var b=m.exec(a.id);return document.querySelector("#"+b[1]+("open"==b[2]?"close":"open"))}function c(){Prism.util.isActive(this,"brace-hover",!0)&&[this,b(this)].forEach(function(b){b.classList.add(a("brace-hover"))})}function d(){[this,b(this)].forEach(function(b){b.classList.remove(a("brace-hover"))})}function f(){Prism.util.isActive(this,"brace-select",!0)&&[this,b(this)].forEach(function(b){b.classList.add(a("brace-selected"))})}if("undefined"!=typeof Prism&&"undefined"!=typeof document){var g={"(":")","[":"]","{":"}"},h={"(":"brace-round","[":"brace-square","{":"brace-curly"},j={"${":"{"},k=12,l=0,m=/^(pair-\d+-)(close|open)$/;selectBrace=a=>{m.test(a.id)&&c.apply(a)},deselectAllBraces=b=>{for(let c=b.getElementsByClassName(a("brace-hover"));0 2 | 3 | 4 | 5 | 6 | code-input Tester 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 |

code-input Tester (Prism.js)

38 |

If the page doesn't load, please reload it, and answer the questions in alert boxes.

39 |

Test for highlight.js

40 |

This page carries out automated tests for the code-input library to check that both the core components and the plugins work in some ways. It doesn't fully cover every scenario so you should test any code you change by hand, but it's good for quickly checking a wide range of functionality works.

41 | 42 |
Test Results (Click to Open)
43 |
44 | console.log("Hello, World!"); 45 | // A second line 46 | // A third line with <html> tags 47 | 48 |
49 | 50 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /tests/tester.min.js: -------------------------------------------------------------------------------- 1 | var testsFailed=!1;function testData(a,b,c){let d=document.getElementById("test-results"),e=d.querySelector("#test-"+a);e==null&&(e=document.createElement("span"),e.innerHTML=`Group ${a}:\n`,e.id="test-"+a,d.append(e)),e.innerHTML+=`\t${b}: ${c}\n`}function testAssertion(a,b,c,d){let e=document.getElementById("test-results"),f=e.querySelector("#test-"+a);f==null&&(f=document.createElement("span"),f.innerHTML=`Group ${a}:\n`,f.id="test-"+a,e.append(f)),f.innerHTML+=`\t${b}: ${c?"passed":"failed ("+d+")"}\n`,c||(testsFailed=!0)}function assertEqual(a,b,c,d){let e=c==d;testAssertion(a,b,e,"see console output"),e||console.error(a,b,c,"should be",d)}function testAddingText(a,b,c,d,e,f){let g=b.selectionStart,h=b.value.substring(0,b.selectionStart),i=b.value.substring(b.selectionEnd);c(b);let j=h+d+i;assertEqual(a,"Text Output",b.value,j),assertEqual(a,"Code-Input Value JS Property Output",b.parentElement.value,j),assertEqual(a,"Selection Start",b.selectionStart,g+e),assertEqual(a,"Selection End",b.selectionEnd,g+f)}function addText(a,b,c=!1){for(let d=0;d{setTimeout(()=>{b()},a)})}function beginTest(a){let b=document.querySelector("code-input");a?codeInput.registerTemplate("code-editor",codeInput.templates.hljs(hljs,[new codeInput.plugins.AutoCloseBrackets,new codeInput.plugins.Autocomplete(function(a,b,c){"popup"==b.value.substring(c-5,c)?(a.style.display="block",a.innerHTML="Here's your popup!"):a.style.display="none"}),new codeInput.plugins.Autodetect,new codeInput.plugins.FindAndReplace,new codeInput.plugins.GoToLine,new codeInput.plugins.Indent(!0,2),new codeInput.plugins.SelectTokenCallbacks(codeInput.plugins.SelectTokenCallbacks.TokenSelectorCallbacks.createClassSynchronisation("in-selection"),!1,!0,!0,!0,!0,!1),new codeInput.plugins.SpecialChars(!0)])):codeInput.registerTemplate("code-editor",codeInput.templates.prism(Prism,[new codeInput.plugins.AutoCloseBrackets,new codeInput.plugins.Autocomplete(function(a,b,c){"popup"==b.value.substring(c-5,c)?(a.style.display="block",a.innerHTML="Here's your popup!"):a.style.display="none"}),new codeInput.plugins.FindAndReplace,new codeInput.plugins.GoToLine,new codeInput.plugins.Indent(!0,2),new codeInput.plugins.SelectTokenCallbacks(new codeInput.plugins.SelectTokenCallbacks.TokenSelectorCallbacks(selectBrace,deselectAllBraces),!0),new codeInput.plugins.SpecialChars(!0)])),startLoad(b,a)}function startLoad(a,b){let c,d=0,e=window.setInterval(()=>{c=a.querySelector("textarea"),null!=c&&window.clearInterval(e),d+=10,testData("TimeTaken","Textarea Appears",d+"ms (nearest 10)"),startTests(c,b)},10)}function allowInputEvents(a){a.addEventListener("input",function(a){a.isTrusted||(a.preventDefault(),document.execCommand("insertText",!1,a.data))},!1)}async function startTests(a,b){a.focus(),allowInputEvents(a),codeInputElement=a.parentElement,assertEqual("Core","Initial Textarea Value",a.value,`console.log("Hello, World!"); 2 | // A second line 3 | // A third line with tags`);let c=codeInputElement.codeElement.innerHTML.replace(/<[^>]+>/g,"");assertEqual("Core","Initial Rendered Value",c,`console.log("Hello, World!"); 4 | // A second line 5 | // A third line with <html> tags 6 | `),codeInputElement.value+=` 7 | console.log("I've got another line!", 2 < 3, "should be true.");`,await waitAsync(50),assertEqual("Core","JS-updated Textarea Value",a.value,`console.log("Hello, World!"); 8 | // A second line 9 | // A third line with tags 10 | console.log("I've got another line!", 2 < 3, "should be true.");`),c=codeInputElement.codeElement.innerHTML.replace(/<[^>]+>/g,""),assertEqual("Core","JS-updated Rendered Value",c,`console.log("Hello, World!"); 11 | // A second line 12 | // A third line with <html> tags 13 | console.log("I've got another line!", 2 < 3, "should be true."); 14 | `);let d=0,e=0,f=a=>{a.isTrusted||d++};codeInputElement.addEventListener("input",f);let g=()=>{e++};codeInputElement.addEventListener("change",g);let h=!1,i=()=>{h=!0};codeInputElement.addEventListener("input",i),codeInputElement.removeEventListener("input",i),a.focus(),addText(a," // Hi"),a.blur(),a.focus(),assertEqual("Core","Function Event Listeners: Input Called Right Number of Times",d,6),assertEqual("Core","Function Event Listeners: Change Called Right Number of Times",e,1),testAssertion("Core","Function Event Listeners: Input Removed Listener Not Called",!h,"(code-input element).removeEventListener did not work."),codeInputElement.removeEventListener("input",f),codeInputElement.removeEventListener("change",g),d=0,e=0,codeInputElement.addEventListener("input",{handleEvent:a=>{a.isTrusted||d++}}),codeInputElement.addEventListener("change",{handleEvent:()=>{e++}}),h=!1,i={handleEvent:()=>{h=!0}},codeInputElement.addEventListener("input",i),codeInputElement.removeEventListener("input",i),a.focus(),addText(a," // Hi"),a.blur(),a.focus(),assertEqual("Core","Object Event Listeners: Input Called Right Number of Times",d,6),assertEqual("Core","Object Event Listeners: Change Called Right Number of Times",e,1),testAssertion("Core","Object Event Listeners: Input Removed Listener Not Called",!h,"(code-input element).removeEventListener did not work."),b||(testAssertion("Core","Language attribute Initial value",!codeInputElement.codeElement.classList.contains("language-javascript")&&!codeInputElement.codeElement.classList.contains("language-html"),`Language unset but code element's class name is ${codeInputElement.codeElement.className}.`),codeInputElement.setAttribute("language","HTML"),await waitAsync(50),testAssertion("Core","Language attribute Changed value 1",codeInputElement.codeElement.classList.contains("language-html")&&!codeInputElement.codeElement.classList.contains("language-javascript"),`Language set to HTML but code element's class name is ${codeInputElement.codeElement.className}.`),codeInputElement.setAttribute("language","JavaScript"),await waitAsync(50),testAssertion("Core","Language attribute Changed value 2",codeInputElement.codeElement.classList.contains("language-javascript")&&!codeInputElement.codeElement.classList.contains("language-html"),`Language set to JavaScript but code element's class name is ${codeInputElement.codeElement.className}.`));let j=codeInputElement.parentElement;j.reset(),await waitAsync(50),assertEqual("Core","Form Reset resets Code-Input Value",codeInputElement.value,`console.log("Hello, World!"); 15 | // A second line 16 | // A third line with tags`),assertEqual("Core","Form Reset resets Textarea Value",a.value,`console.log("Hello, World!"); 17 | // A second line 18 | // A third line with tags`),c=codeInputElement.codeElement.innerHTML.replace(/<[^>]+>/g,""),assertEqual("Core","Form Reset resets Rendered Value",c,`console.log("Hello, World!"); 19 | // A second line 20 | // A third line with <html> tags 21 | `),testAddingText("AutoCloseBrackets",a,function(a){addText(a,`\nconsole.log("A test message`),move(a,2),addText(a,`;\nconsole.log("Another test message");\n{[{[]}(([[`),backspace(a),backspace(a),backspace(a),addText(a,`)`)},"\nconsole.log(\"A test message\");\nconsole.log(\"Another test message\");\n{[{[]}()]}",77,77),addText(a,"popup"),await waitAsync(50),testAssertion("Autocomplete","Popup Shows",confirm("Does the autocomplete popup display correctly? (OK=Yes)"),"user-judged"),backspace(a),await waitAsync(50),testAssertion("Autocomplete","Popup Disappears",confirm("Has the popup disappeared? (OK=Yes)"),"user-judged"),backspace(a),backspace(a),backspace(a),backspace(a),b&&(a.selectionStart=0,a.selectionEnd=a.value.length,backspace(a),addText(a,"console.log(\"Hello, World!\");\nfunction sayHello(name) {\n console.log(\"Hello, \" + name + \"!\");\n}\nsayHello(\"code-input\");"),await waitAsync(50),assertEqual("Autodetect","Detects JavaScript",codeInputElement.getAttribute("language"),"javascript"),a.selectionStart=0,a.selectionEnd=a.value.length,backspace(a),addText(a,"#!/usr/bin/python\nprint(\"Hello, World!\")\nfor i in range(5):\n print(i)"),await waitAsync(50),assertEqual("Autodetect","Detects Python",codeInputElement.getAttribute("language"),"python"),a.selectionStart=0,a.selectionEnd=a.value.length,backspace(a),addText(a,"body, html {\n height: 100%;\n background-color: blue;\n color: red;\n}"),await waitAsync(50),assertEqual("Autodetect","Detects CSS",codeInputElement.getAttribute("language"),"css")),a.selectionStart=0,a.selectionEnd=a.value.length,backspace(a),addText(a,"// hello /\\S/g\nhe('llo', /\\s/g);\nhello"),a.selectionStart=a.selectionEnd=0,await waitAsync(50),a.dispatchEvent(new KeyboardEvent("keydown",{cancelable:!0,key:"f",ctrlKey:!0}));let k=codeInputElement.querySelectorAll(".code-input_find-and-replace_dialog input"),l=k[0],m=k[1],n=k[2],o=k[3],p=codeInputElement.querySelectorAll(".code-input_find-and-replace_dialog button"),q=p[0],r=p[1],s=p[2],t=p[3],u=codeInputElement.querySelector(".code-input_find-and-replace_dialog details summary");l.value="/\\s/g",n.click(),await waitAsync(150),testAssertion("FindAndReplace","Finds Case-Sensitive Matches Correctly",confirm("Is there a match on only the lowercase '/\\s/g'?"),"user-judged"),l.value="he[^l]*llo",m.click(),n.click(),await waitAsync(150),testAssertion("FindAndReplace","Finds RegExp Matches Correctly",confirm("Are there matches on all 'he...llo's?"),"user-judged"),u.click(),r.click(),o.value="do('hello",s.click(),await waitAsync(50),assertEqual("FindAndReplace","Replaces Once Correctly",a.value,"// hello /\\S/g\ndo('hello', /\\s/g);\nhello"),q.click(),codeInputElement.querySelector(".code-input_find-and-replace_dialog").dispatchEvent(new KeyboardEvent("keydown",{key:"Escape"})),codeInputElement.querySelector(".code-input_find-and-replace_dialog").dispatchEvent(new KeyboardEvent("keyup",{key:"Escape"})),assertEqual("FindAndReplace","Selection Start on Focused Match when Dialog Exited",a.selectionStart,3),assertEqual("FindAndReplace","Selection End on Focused Match when Dialog Exited",a.selectionEnd,8),a.dispatchEvent(new KeyboardEvent("keydown",{cancelable:!0,key:"h",ctrlKey:!0})),l.value="",l.focus(),allowInputEvents(l),addText(l,"hello"),await waitAsync(150),o.value="hi",t.click(),assertEqual("FindAndReplace","Replaces All Correctly",a.value,"// hi /\\S/g\ndo('hi', /\\s/g);\nhi"),codeInputElement.querySelector(".code-input_find-and-replace_dialog").dispatchEvent(new KeyboardEvent("keydown",{key:"Escape"})),codeInputElement.querySelector(".code-input_find-and-replace_dialog").dispatchEvent(new KeyboardEvent("keyup",{key:"Escape"})),a.selectionStart=0,a.selectionEnd=a.value.length,backspace(a),addText(a,"// 7 times table\nlet i = 1;\nwhile(i <= 12) { console.log(`7 x ${i} = ${7*i}`) }\n// That's my code.\n// This is another comment\n// Another\n// Line"),a.dispatchEvent(new KeyboardEvent("keydown",{cancelable:!0,key:"g",ctrlKey:!0}));let v=codeInputElement.querySelector(".code-input_go-to-line_dialog input");v.value="1",v.dispatchEvent(new KeyboardEvent("keydown",{key:"Enter"})),v.dispatchEvent(new KeyboardEvent("keyup",{key:"Enter"})),assertEqual("GoToLine","Line Only",a.selectionStart,0),a.dispatchEvent(new KeyboardEvent("keydown",{cancelable:!0,key:"g",ctrlKey:!0})),v.value="3:18",v.dispatchEvent(new KeyboardEvent("keydown",{key:"Enter"})),v.dispatchEvent(new KeyboardEvent("keyup",{key:"Enter"})),assertEqual("GoToLine","Line and Column",a.selectionStart,45),a.dispatchEvent(new KeyboardEvent("keydown",{cancelable:!0,key:"g",ctrlKey:!0})),v.value="10",v.dispatchEvent(new KeyboardEvent("keydown",{key:"Enter"})),v.dispatchEvent(new KeyboardEvent("keyup",{key:"Enter"})),assertEqual("GoToLine","Rejects Out-of-range Line",v.classList.contains("code-input_go-to-line_error"),!0),a.dispatchEvent(new KeyboardEvent("keydown",{cancelable:!0,key:"g",ctrlKey:!0})),v.value="2:12",v.dispatchEvent(new KeyboardEvent("keydown",{key:"Enter"})),v.dispatchEvent(new KeyboardEvent("keyup",{key:"Enter"})),assertEqual("GoToLine","Rejects Out-of-range Column",v.classList.contains("code-input_go-to-line_error"),!0),a.dispatchEvent(new KeyboardEvent("keydown",{cancelable:!0,key:"g",ctrlKey:!0})),v.value="sausages",v.dispatchEvent(new KeyboardEvent("keydown",{key:"Enter"})),v.dispatchEvent(new KeyboardEvent("keyup",{key:"Enter"})),assertEqual("GoToLine","Rejects Invalid Input",v.classList.contains("code-input_go-to-line_error"),!0),assertEqual("GoToLine","Stays open when Rejects Input",v.parentElement.classList.contains("code-input_go-to-line_hidden-dialog"),!1),v.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape"})),v.dispatchEvent(new KeyboardEvent("keyup",{key:"Escape"})),assertEqual("GoToLine","Exits when Esc pressed",v.parentElement.classList.contains("code-input_go-to-line_hidden-dialog"),!0),a.selectionStart=a.selectionEnd=a.value.length,addText(a,"\nfor(let i = 0; i < 100; i++) {\n for(let j = i; j < 100; j++) {\n // Here's some code\n console.log(i,j);\n }\n}\n{\n // This is indented\n}"),a.selectionStart=0,a.selectionEnd=a.value.length,a.dispatchEvent(new KeyboardEvent("keydown",{key:"Tab",shiftKey:!1})),a.dispatchEvent(new KeyboardEvent("keyup",{key:"Tab",shiftKey:!1})),assertEqual("Indent","Indents Lines",a.value," // 7 times table\n let i = 1;\n while(i <= 12) { console.log(`7 x ${i} = ${7*i}`) }\n // That's my code.\n // This is another comment\n // Another\n // Line\n for(let i = 0; i < 100; i++) {\n for(let j = i; j < 100; j++) {\n // Here's some code\n console.log(i,j);\n }\n }\n {\n // This is indented\n }"),a.dispatchEvent(new KeyboardEvent("keydown",{key:"Tab",shiftKey:!0})),a.dispatchEvent(new KeyboardEvent("keyup",{key:"Tab",shiftKey:!0})),assertEqual("Indent","Unindents Lines",a.value,"// 7 times table\nlet i = 1;\nwhile(i <= 12) { console.log(`7 x ${i} = ${7*i}`) }\n// That's my code.\n// This is another comment\n// Another\n// Line\nfor(let i = 0; i < 100; i++) {\n for(let j = i; j < 100; j++) {\n // Here's some code\n console.log(i,j);\n }\n}\n{\n // This is indented\n}"),a.dispatchEvent(new KeyboardEvent("keydown",{key:"Tab",shiftKey:!0})),a.dispatchEvent(new KeyboardEvent("keyup",{key:"Tab",shiftKey:!0})),assertEqual("Indent","Unindents Lines where some are already fully unindented",a.value,"// 7 times table\nlet i = 1;\nwhile(i <= 12) { console.log(`7 x ${i} = ${7*i}`) }\n// That's my code.\n// This is another comment\n// Another\n// Line\nfor(let i = 0; i < 100; i++) {\nfor(let j = i; j < 100; j++) {\n // Here's some code\n console.log(i,j);\n}\n}\n{\n// This is indented\n}"),a.selectionStart=255,a.selectionEnd=274,a.dispatchEvent(new KeyboardEvent("keydown",{key:"Tab",shiftKey:!1})),a.dispatchEvent(new KeyboardEvent("keyup",{key:"Tab",shiftKey:!1})),assertEqual("Indent","Indents Lines by Selection",a.value,"// 7 times table\nlet i = 1;\nwhile(i <= 12) { console.log(`7 x ${i} = ${7*i}`) }\n// That's my code.\n// This is another comment\n// Another\n// Line\nfor(let i = 0; i < 100; i++) {\nfor(let j = i; j < 100; j++) {\n // Here's some code\n console.log(i,j);\n}\n}\n{\n // This is indented\n}"),a.selectionStart=265,a.selectionEnd=265,a.dispatchEvent(new KeyboardEvent("keydown",{key:"Tab",shiftKey:!0})),a.dispatchEvent(new KeyboardEvent("keyup",{key:"Tab",shiftKey:!0})),assertEqual("Indent","Unindents Lines by Selection",a.value,"// 7 times table\nlet i = 1;\nwhile(i <= 12) { console.log(`7 x ${i} = ${7*i}`) }\n// That's my code.\n// This is another comment\n// Another\n// Line\nfor(let i = 0; i < 100; i++) {\nfor(let j = i; j < 100; j++) {\n // Here's some code\n console.log(i,j);\n}\n}\n{\n// This is indented\n}"),a.selectionStart=0,a.selectionEnd=a.value.length,backspace(a),testAddingText("Indent-AutoCloseBrackets",a,function(a){addText(a,`function printTriples(max) {\nfor(let i = 0; i < max-2; i++) {\nfor(let j = 0; j < max-1; j++) {\nfor(let k = 0; k < max; k++) {\nconsole.log(i,j,k);\n}\n//Hmmm...`,!0)},"function printTriples(max) {\n for(let i = 0; i < max-2; i++) {\n for(let j = 0; j < max-1; j++) {\n for(let k = 0; k < max; k++) {\n console.log(i,j,k);\n }\n //Hmmm...\n }\n }\n }\n}",189,189),b?(addText(a,"\nlet x = 1;\nlet y = 2;\nconsole.log(`${x} + ${y} = ${x+y}`);"),move(a,-4),a.selectionStart-=35,await waitAsync(50),assertEqual("SelectTokenCallbacks","Number of Selected Tokens",codeInputElement.querySelectorAll(".in-selection").length,13),assertEqual("SelectTokenCallbacks","Number of Selected .hljs-string Tokens",codeInputElement.querySelectorAll(".hljs-string.in-selection").length,0),assertEqual("SelectTokenCallbacks","Number of Selected .hljs-subst Tokens",codeInputElement.querySelectorAll(".hljs-subst.in-selection").length,2)):(addText(a,"\n[(),((),'Hi')]"),await waitAsync(50),move(a,-2),await waitAsync(50),assertEqual("SelectTokenCallbacks","Number of Selected Braces 1",codeInputElement.getElementsByClassName("brace-hover").length,2),move(a,1),await waitAsync(50),assertEqual("SelectTokenCallbacks","Number of Selected Braces 2",codeInputElement.getElementsByClassName("brace-hover").length,4)),a.selectionStart=0,a.selectionEnd=a.value.length,backspace(a),addText(a,"\"Some special characters: \x96,\x01\x03,\x02...\""),a.selectionStart=a.value.length-4,a.selectionEnd=a.value.length,await waitAsync(50),testAssertion("SpecialChars","Displays Correctly",confirm("Do the special characters read (0096),(0001)(0003),(0002) and align with the ellipsis? (OK=Yes)"),"user-judged"),a.selectionStart=0,a.selectionEnd=a.value.length,backspace(a),fetch(new Request("https://cdn.jsdelivr.net/gh/webcoder49/code-input@2.1/code-input.js")).then(a=>a.text()).then(b=>{a.value="// code-input v2.1: A large code file (not the latest version!)\n// Editing this here should give little latency.\n\n"+b,a.selectionStart=112,a.selectionEnd=112,addText(a,"\n",!0),document.getElementById("collapse-results").setAttribute("open",!0)}),testsFailed?(document.querySelector("h2").style.backgroundColor="red",document.querySelector("h2").textContent="Some Tests have Failed."):(document.querySelector("h2").style.backgroundColor="lightgreen",document.querySelector("h2").textContent="All Tests have Passed.")} --------------------------------------------------------------------------------