[英]Creating a slate.js editor component that keeps its state in markdown
[英]Unable to delete a link clearly in Slate.js editor using the official example
代碼沙盒示例:
https://codesandbox.io/s/slate-2-images-and-links-forked-s09wi
這基本上是官方文檔中的withLink() 示例。
當您按退格鍵或剪切鍵刪除鏈接時,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)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.