Slate文档编辑器-Node节点与Path路径映射
在之前我们聊到了slate
中的Decorator
装饰器实现,装饰器可以为我们方便地在编辑器渲染调度时处理range
的渲染,这在实现搜索替换、代码高亮等场景非常有用。那么在这篇文章中,我们聊一下Node
节点与Path
路径映射,这里的Node
指的是渲染的节点对象,Path
则是节点对象在当前JSON
中的路径,即本文的重点是如何确定渲染出的节点处于文档数据定义中的位置。
- 在线编辑: https://windrunnermax.github.io/DocEditor
- 开源地址: https://github.com/WindRunnerMax/DocEditor
关于slate
文档编辑器项目的相关文章:
- 基于Slate构建文档编辑器
- Slate文档编辑器-WrapNode数据结构与操作变换
- Slate文档编辑器-TS类型扩展与节点类型检查
- Slate文档编辑器-Decorator装饰器渲染调度
- Slate文档编辑器-Node节点与Path路径映射
渲染与命令
在slate
的文档中的03-defining-custom-elements
一节中,我们可以看到我们可以看到slate
中的Element
节点是可以自定义渲染的,渲染的逻辑是需要我们根据props
的element
对象来判断类型,如果类型是code
的话那就要渲染我们预定义好的CodeElement
组件,否则渲染DefaultElement
组件,这里的type
是我们预设的init
数据结构值,是数据结构的形式约定。
// https://docs.slatejs.org/walkthroughs/03-defining-custom-elements
const App = () => {
const [editor] = useState(() => withReact(createEditor()))
// Define a rendering function based on the element passed to `props`. We use
// `useCallback` here to memoize the function for subsequent renders.
const renderElement = useCallback(props => {
switch (props.element.type) {
case 'code':
return <CodeElement {
...props} />
default:
return <DefaultElement {
...props} />
}
}, [])
return (
<Slate editor={
editor} initialValue={
initialValue}>
<Editable
// Pass in the `renderElement` function.
renderElement={
renderElement}
/>
</Slate>
)
}
那么这里的渲染自然是不会有什么问题,我们的编辑器实际上必然不仅仅是要渲染内容,执行命令来变更文档结构/内容也是非常重要的事情。那么在05-executing-commands
中一节中,我们可以看到对于文本内容加粗与代码块的切换分别是执行了addMark/removeMark
以及Transforms.setNodes
的函数来执行的。
// https://docs.slatejs.org/walkthroughs/05-executing-commands
toggleBoldMark(editor) {
const isActive = CustomEditor.isBoldMarkActive(editor)
if (isActive) {
Editor.removeMark(editor, 'bold')
} else