Search code examples
javascriptweb-componentcodemirrorshadow-domcustom-element

Adding CodeMirror to Shadow Dom of Custom Element?


I'd like to dynamically create a CodeMirror instance inside a Custom Element and have it live inside the element's Shadow DOM. For example:

<code-mirror>foo</code-mirror>
<script>
window.customElements.define('code-mirror', class extends HTMLElement {
    constructor() {
        super();
        let shadowRoot = this.attachShadow({mode: 'open'});
    }

    connectedCallback() {
        this.cm = CodeMirror(this.shadowRoot, {lineNumbers: true});
    }
});
</script>

This "works" but the layout is all wrong.. margin-left gets set to the width of the window, line numbers aren't displayed correctly and the selection logic is off by a few lines vertically.

Here's a jsfiddle demonstrating the layout issue: link

Suggestions?


Solution

  • Import CodeMirror's stylesheet inside the shadow DOM with @import url:

    constructor() {
        super();
        let shadowRoot = this.attachShadow({ mode: 'open' });
        shadowRoot.innerHTML = `
            <style>
               @import url(https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.24.2/codemirror.min.css)
            </style>`         
    }