9月28日总结

发布时间 2023-10-03 14:32:55作者: lmyyyy

能够对于文字、段落乃至任何元素的精准定位 并做出增删改查,都是在开发一款富文本编辑器时一项最基本也是最重要的功能之一。让我们先来看看Slate中对于如何在文档树中定位元素是怎么定义的[源码]:

/**

  • The Location interface is a union of the ways to refer to a specific
  • location in a Slate document: paths, points or ranges.
  • Methods will often accept a Location instead of requiring only a Path,
  • Point or Range. This eliminates the need for developers to manage
  • converting between the different interfaces in their own code base.
    */
    export type Location = Path | Point | Range

Location是一个包含了Path、Point及Range的联合类型,代指了Slate中所有关于“定位”的概念,同时也方便了开发。例如在几乎所有的Transforms方法中,都可以通过传递Location参数来决定Transforms方法需要应用到文档中的哪些位置上[链接]。

All transforms support a parameter options. This includes options specific to the transform, and general NodeOptions to specify which Nodes in the document that the transform is applied to.

interface NodeOptions {
  at?: Location
  match?: (node: Node, path: Location) => boolean
  mode?: 'highest' | 'lowest'
  voids?: boolean
}

Path

Path是三个中最基本的概念,也是唯一一个不可拓展的类型。

/**

  • Path arrays are a list of indexes that describe a node's exact position in
  • a Slate node tree. Although they are usually relative to the root Editor
  • object, they can be relative to any Node object.
    */
    export type Path = number[]

Path类型就是一个数组,用来表示Slate文档树中自根节点root到指定node的绝对路径。我们以下边的示例来演示下各个node所代表的路径:

const initialValue: Descendant[] = [
// path: [0]
{
type: 'paragraph',
children: [
{ text: 'This is editable ' }, // path: [0, 0]
{ text: 'rich text!', bold: true } // path: [0, 1]
]
},
// path: [1]
{
type: 'paragraph',
children: [
{ text: 'It' so cool.' } // path: [1, 0]
]
}
]

虽然Path所代表的路径通常是以顶层Editor作为root节点的,但也会有其他情况,比如由Node提供的get方法中传入的Path参数则代表的是相对路径[源码]:

/**

  • Get the descendant node referred to by a specific path. If th