Generic
Generic

Reputation: 29

Monaco Editor | How to properly use Hover's IMarkdownString with HTML

monaco.languages.register({ id: 'mySpecialLanguage' });

monaco.languages.registerHoverProvider('mySpecialLanguage', {
    provideHover: function (model, position) {
        return {
            range: new monaco.Range(
                1,
                1,
                model.getLineCount(),
                model.getLineMaxColumn(model.getLineCount())
            ),
            contents: [
                {
                    supportHtml: true,
                    value: '<div style="color red; class="test">yes</div>'
                }
            ]
        };
    }
});

monaco.editor.create(document.getElementById('container'), {
    value: '\n\nHover over this text',
    language: 'mySpecialLanguage'
});

I'm trying to provide a HoverProvider for my editor but I can't seem to render the element with a different foreground or classList, Am I doing something wrong here? It works okay but the style didn't load / inserted to the hover content. I'm using IMarkdownString

Upvotes: 0

Views: 1953

Answers (2)

Ian A
Ian A

Reputation: 6163

I answered a similar question here.

Only a subset of HTML tags and attributes are supported in IMarkdownString. Only the HTML span elememt supports the style attribute and the CSS defined in the style attribute needs to align to these specific rules:

  • Is only allowed the CSS properties color or background-color

  • Must be defined in hex (colour names are not allowed)

  • No space between color: and the hex value

  • Must contain a semi colon at the end of the hex value

If you change the HTML string defined in the value property to

<span style="color:#ff0000;">yes<span>

then it should work and display the word "yes" in red.

If you copy and paste the following code into the Monaco playground, you should see it working:

monaco.languages.register({ id: 'mySpecialLanguage' });

monaco.languages.registerHoverProvider('mySpecialLanguage', {
    provideHover: function (model, position) {
        return {
            range: new monaco.Range(
                1,
                1,
                model.getLineCount(),
                model.getLineMaxColumn(model.getLineCount())
            ),
            contents: [
                {
                    supportHtml: true,
                    value: '<span style="color:#ff0000;">yes</span>'
                }
            ]
        };
    }
});

monaco.editor.create(document.getElementById('container'), {
    value: '\n\nHover over this text',
    language: 'mySpecialLanguage'
});

Upvotes: 3

Michal
Michal

Reputation: 1

The value does not contain a valid HTML. You're missing a colon after color and you're not closing the style attribute with a quote. It should be: '<div style="color: red" class="test">yes</div>'

Upvotes: 0

Related Questions