检测在 slate-react 文本编辑器中选择了哪个节点
Detecting which node is selected within a slate-react text editor
我目前正在开发一个 slate 文本编辑器,用户可以在其中添加图像和文本。我还想要一个悬停工具栏,它根据用户选择的元素类型提供不同的按钮。
例如,如果用户选择了一张图片,那么我想提供一组按钮。如果用户选择了一个段落,我想提供另一组按钮。
查看此处找到的示例后:
https://www.slatejs.org/examples/richtext
我拼凑了一个我想要的文本编辑器的粗略示例,没有上下文相关的悬停工具栏按钮:
https://codesandbox.io/s/suspicious-pine-lrxgw
但我正在努力弄清楚如何检测在编辑器中选择了哪种类型的元素?我不知道是否有办法使用 slate-react 来做到这一点?或者甚至在普通 JS 中?
理想情况下,我还可以获得有关该元素的其他信息。例如图像的高度和宽度,因为这有助于样式化。
感谢任何帮助
您可以使用编辑器中的 selection
属性 获取当前聚焦的节点,这是一个 Range。然后,您使用 anchor
或 focus
来 select 当前 selected children。
anchor
& focus
是点,它们基本上是一个数组,第一项是当前块,第二项表示块中的位置。
Point objects refer to a specific location in a text node in a Slate
document. Its path refers to the location of the node in the tree, and
its offset refers to distance into the node's string of text. Points
may only refer to Text nodes.
使用 selection 数组,我们可以像这样获得当前的 selected 块
if (selection !== null && selection.anchor !== null) {
selected = editor.children[selection.anchor.path[0]];
} else {
selected = null;
}
稍后在您的渲染函数中,您可以检查渲染您想要的内容。
我目前正在开发一个 slate 文本编辑器,用户可以在其中添加图像和文本。我还想要一个悬停工具栏,它根据用户选择的元素类型提供不同的按钮。
例如,如果用户选择了一张图片,那么我想提供一组按钮。如果用户选择了一个段落,我想提供另一组按钮。
查看此处找到的示例后:
https://www.slatejs.org/examples/richtext
我拼凑了一个我想要的文本编辑器的粗略示例,没有上下文相关的悬停工具栏按钮:
https://codesandbox.io/s/suspicious-pine-lrxgw
但我正在努力弄清楚如何检测在编辑器中选择了哪种类型的元素?我不知道是否有办法使用 slate-react 来做到这一点?或者甚至在普通 JS 中?
理想情况下,我还可以获得有关该元素的其他信息。例如图像的高度和宽度,因为这有助于样式化。
感谢任何帮助
您可以使用编辑器中的 selection
属性 获取当前聚焦的节点,这是一个 Range。然后,您使用 anchor
或 focus
来 select 当前 selected children。
anchor
& focus
是点,它们基本上是一个数组,第一项是当前块,第二项表示块中的位置。
Point objects refer to a specific location in a text node in a Slate document. Its path refers to the location of the node in the tree, and its offset refers to distance into the node's string of text. Points may only refer to Text nodes.
使用 selection 数组,我们可以像这样获得当前的 selected 块
if (selection !== null && selection.anchor !== null) {
selected = editor.children[selection.anchor.path[0]];
} else {
selected = null;
}
稍后在您的渲染函数中,您可以检查渲染您想要的内容。