4

I am trying to apply bold to **text** in slatejs editor and so far my attempts have been unsuccessful.
I came across this answer which seems to be a possible solution to the problem.

However, after modifying that answer it still refused to apply bold.

I tried adding match: n => Text.isText(n) and that made the whole paragraph bold.

Expected result: **text** => **text**

Actual result: **text** => **text**

How may I modify this to work as expected?

const withMarkdown = editor => {
    const { normalizeNode } = editor;

    editor.normalizeNode = entry => {
        const [node, path] = entry;

        if (!Text.isText(node)) {
            return normalizeNode([node, path]);
        }

        const boldMatch = node.text.match(/([*]{2})(.+?)([*]{2})/);
        if (!boldMatch) {
            return normalizeNode([node, path]);
        }

        let [searchMatch, asteriskMatch] = boldMatch;
        const { index: startIndex } = boldMatch;
        const endIndex = startIndex + searchMatch.length;

        /* does not apply bold */
        Transforms.setNodes(editor, { bold: true }, {
            at: {
                anchor: { path, offset: startIndex },
                focus: { path, offset: endIndex },
            }
        })

        normalizeNode([node, path]);
    }

    return editor;
}

Edit: Tried this and got the expected result but along with that came an error.

Transforms.insertText(editor, searchMatch, {
    at: {
        anchor: { path, offset: startIndex },
        focus: { path, offset: endIndex },
    }
})

Transforms.setNodes(editor,
    { bold: true },
    { 
        at: { 
            anchor: { path, offset: startIndex },
            focus: { path, offset: endIndex }
        },
        match: n => Text.isText(n), split: true
    }
);

Error message:

Could not completely normalize the editor after 126 iterations! This is usually due to incorrect normalization logic that leaves a node in an invalid state.
Feelsbadman
  • 1,163
  • 4
  • 17
  • 37

1 Answers1

1

This is what's happening in your code:

  • You check for matching **
  • Then you add a bold formatting to your text.

Since this modifies the current node, it will be again part of the next normalization pass. This runs into an infinite loop, since your text will always match.

I see three options:

  • Remove the ** and only display the bold text
  • Check if the text is already bold before modifying the node
  • Move the logic to make the text bold out of the normalization logic, e.g. into the onKeyUp event or by overriding editor.insertText.
Philipp
  • 1,903
  • 2
  • 24
  • 33