首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SlateJS将粗体应用于正则匹配

SlateJS将粗体应用于正则匹配
EN

Stack Overflow用户
提问于 2022-01-08 04:56:38
回答 1查看 364关注 0票数 3

我试图在slatejs编辑器中将粗体应用于**文本**,到目前为止,我的尝试都没有成功。

我偶然发现了this answer,这似乎是解决问题的一种可能的方法。

然而,在修改了这个答案之后,它仍然拒绝使用粗体。

我试着添加match: n => Text.isText(n),这使得整个段落变得粗体。

预期结果:**文本** => **文本**

实际结果:**文本** => **文本**

如何修改它以按预期工作?

代码语言:javascript
复制
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;
}

编辑:试了一下,得到了预期的结果,但同时也出现了一个错误。

代码语言:javascript
复制
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
    }
);

错误消息:

代码语言:javascript
复制
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.
EN

回答 1

Stack Overflow用户

发布于 2022-03-22 15:57:47

这就是在您的代码中发生的事情:

您检查是否匹配**

  • Then您在文本中添加了粗体格式。

因为这会修改当前节点,所以它将再次成为下一次规范化传递的一部分。这会遇到一个无限循环,因为您的文本总是匹配的。

我认为有三种选择:

editor.insertText.

  • 删除**,并仅在修改节点

  • 之前显示粗体文本

  • 检查文本是否已为粗体,将逻辑移动以使文本超出规范化逻辑,例如进入onKeyUp事件或重写onKeyUp事件。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70629704

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档