microsoft / monaco-editor

A browser based code editor
https://microsoft.github.io/monaco-editor/
MIT License
39k stars 3.51k forks source link

[Bug] error when selecting text with mouse in shadow dom #4548

Open hungtcs opened 3 weeks ago

hungtcs commented 3 weeks ago

Reproducible in vscode.dev or in VS Code Desktop?

Reproducible in the monaco editor playground?

Monaco Editor Playground Link

Link To Monaco Playground

Monaco Editor Playground Code

const defaultValue = `async function main() {
  // select this text with the mouse and an error will appear in the console
}
main().catch((err) => console.error(err))
`;

class MyElement extends HTMLElement {
    constructor() {
        super();
        const shadowRoot = this.attachShadow({ mode: "open" });
        const styleLink = document.createElement('link');
        styleLink.rel ='stylesheet';
        styleLink.href = 'node_modules/monaco-editor/min/vs/editor/editor.main.css'
        shadowRoot.appendChild(styleLink);
    }

    connectedCallback() {
        const conatiner = document.createElement("div");
        conatiner.style.width ='100%'
        conatiner.style.height ='320px'
        conatiner.style.resize ='both'
        conatiner.style.overflow ='hidden'
        this.shadowRoot?.appendChild(conatiner);

        monaco.editor.create(conatiner, {
            value: defaultValue,
            theme: 'vs-dark',
            language: "javascript",
            automaticLayout: true,
        });
    }
}

customElements.define('my-element', MyElement);

Reproduction Steps

  1. Select the text in editor with the mouse
  2. An error will appear in the console

Actual (Problematic) Behavior

An error occurred in the console

image

Expected Behavior

No response

Additional Context

No response

hungtcs commented 3 weeks ago

The method can be traced through the stack

function shadowCaretRangeFromPoint(shadowRoot, x, y) {
    const range = document.createRange();
    // Get the element under the point
    let el = shadowRoot.elementFromPoint(x, y);
    if (el !== null) {
        // parameter 1 is not of type 'Node'.                       // <---
        range.setStart(el.firstChild, offset);
        range.setEnd(el.firstChild, offset);
    }
    return range;
}
dominik1996 commented 2 weeks ago

We ran into the same issue: v0.47.0 is the last version to work correctly.