gpt4 book ai didi

javascript - 使用官方示例无法在Slate.js 编辑器中清楚地删除链接

转载 作者:行者123 更新时间:2023-12-05 04:47:22 32 4
gpt4 key购买 nike

enter image description here

代码沙盒示例:

https://codesandbox.io/s/slate-2-images-and-links-forked-s09wi

这基本上是 withLink() example来自官方文档。

当您按退格键或剪切以删除链接时,JSON 输出仍然包含带有空文本的链接数据。我不明白为什么它仍然保留在输出中。谁能为此提供解决方案?

withLink 示例:

const withLinks = editor => {
const { insertData, insertText, isInline } = editor

editor.isInline = element => {
return element.type === 'link' ? true : isInline(element)
}

editor.insertText = text => {
if (text && isUrl(text)) {
wrapLink(editor, text)
} else {
insertText(text)
}
}

editor.insertData = data => {
const text = data.getData('text/plain')

if (text && isUrl(text)) {
wrapLink(editor, text)
} else {
insertData(data)
}
}

return editor
}

const unwrapLink = editor => {
Transforms.unwrapNodes(editor, {
match: n =>
!Editor.isEditor(n) && SlateElement.isElement(n) && n.type === 'link',
})
}

const wrapLink = (editor, url) => {
if (isLinkActive(editor)) {
unwrapLink(editor)
}

const { selection } = editor
const isCollapsed = selection && Range.isCollapsed(selection)
const link: LinkElement = {
type: 'link',
url,
children: isCollapsed ? [{ text: url }] : [],
}

if (isCollapsed) {
Transforms.insertNodes(editor, link)
} else {
Transforms.wrapNodes(editor, link, { split: true })
Transforms.collapse(editor, { edge: 'end' })
}
}

最佳答案

我通过在 withLinks 插件中添加 normalizeNode 解决了这个问题。

const { normalizeNode } = editor
editor.normalizeNode = entry => {
const [node, path] = entry
if (Element.isElement(node) && node.type === 'paragraph') {
const children = Array.from(Node.children(editor, path))
for (const [child, childPath] of children) {
// remove link nodes whose text value is empty string.
// empty text links happen when you move from link to next line or delete link line.
if (Element.isElement(child) && child.type === 'link' && child.children[0].text === '') {
if (children.length === 1) {
Transforms.removeNodes(editor, { at: path })
Transforms.insertNodes(editor,
{
type: 'paragraph',
children: [{ text: '' }],
})
} else {
Transforms.removeNodes(editor, { at: childPath })
}
return
}
}
}
normalizeNode(entry)

关于javascript - 使用官方示例无法在Slate.js 编辑器中清楚地删除链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68511348/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com