3

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?

Supersharp
  • 29,002
  • 9
  • 92
  • 134
moof2k
  • 1,678
  • 1
  • 17
  • 19

1 Answers1

5

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>`         
}
Supersharp
  • 29,002
  • 9
  • 92
  • 134