Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 236
moof2k Avatar asked Nov 07 '25 08:11

moof2k


1 Answers

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>`         
}
like image 56
Supersharp Avatar answered Nov 08 '25 21:11

Supersharp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!