【问题标题】:SlateJS apply bold to regex matchSlateJS 将粗体应用于正则表达式匹配
【发布时间】:2022-03-22 23:57:47
【问题描述】:

我正在尝试将 bold 应用于 slatejs 编辑器中的 **text**,但到目前为止我的尝试均未成功。
我遇到了this answer,这似乎是解决问题的可能方法。

但是,在修改该答案后,它仍然拒绝应用粗体。

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

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

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

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

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;
}

编辑:尝试了这个并得到了预期的结果,但随之而来的是一个错误。

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
    }
);

错误信息:

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.

【问题讨论】:

    标签: javascript markdown slatejs


    【解决方案1】:

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

    • 您检查匹配的**
    • 然后为文本添加粗体格式。

    由于这会修改当前节点,它将再次成为下一个规范化过程的一部分。这会陷入无限循环,因为您的文本将始终匹配。

    我看到三个选项:

    • 删除**,只显示粗体字
    • 在修改节点之前检查文本是否已经是粗体
    • 移动逻辑以使文本粗体脱离规范化逻辑,例如进入onKeyUp 事件或覆盖editor.insertText

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-12
      • 2010-10-10
      • 2022-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-30
      • 2011-05-01
      相关资源
      最近更新 更多