HorusKol

Bytes:

Quick live code editor

November 21, 2022

A quick (and dirty) way to allow users to play with some HTML/CSS.

Over at Accessible Web Components, I'm working on including examples and demonstrations into the documentation, and I'm looking to put some interactivity in there, too, so users can play with the code and see how the component reacts.

Here's a quick first draft attempt that you can play with:

Editor


    
  1. Modify the code on top
  2. See the changes on the bottom
<div style="display: grid; grid-template-rows: auto auto; grid-gap: 1rem">
    <span id="label-for-editor" style="position: absolute; left: -1000px;">Editor</span>
    <pre id="editor" contenteditable spellcheck="false" aria-labelledby="label-for-editor"></pre>

    <div id="output" aria-live="polite">
        <ol>
            <li style="color: green">Modify the code on top</li>
            <li style="color: red">See the changes on the bottom</li>
        </ol>
    </div>
</div>
const editor = document.getElementById('editor');
const output = document.getElementById('output');

// create an array of lines of code for manipulation
let source = output.innerHTML;
source = source.split('\n');

// innerHTML might have an empty line at the start
if (source[0].length === 0) {
  source.slice(1);  
}

// removes excess indentation on the left each line
const indent = source[0].length - source[0].trimStart().length;
source = source.map((line) => {
    return line.substring(indent);
});

// display the source code in the editor window 
editor.textContent = source.join('\n');

// replace the innerHTML in the output as the user types in the editor
editor.addEventListener('input', () => {
    output.innerHTML = editor.textContent;
});

Won't this break the page?

The browser does a fair bit to protect the integrity of the page outside the output area. For example, you can't easily bust out of the editor or the output by typing a closing </pre> or </div>. Try this:

<style>
h1 { color: red !important }
</style>

However, some stuff will leak: such as if a user put a style block in the editor, the style rules will leak out and affect the whole page. The user can also put a <script> element in there.

Security

Ultimately, though, this will only affect the user as they change the code in the page - just as if they're editing via the browser's dev tools.

On the other hand, this is absolutely not secure enough to be used for a web site that takes code from users, stores it on a server, and then shares it to other users.

You're going to need some very careful validation and sanitation going on there.