选区
选区系统,是文档操作里面最重要的一个模块
我们先看prosemirror selection的数据结构
光标位置
我们看几个例子再说明具体的字段意义
- 只有光标
from=to=head=anchor, empty=true
- 从左往右选中内容
from=anchor, to=head, empty=false, from-to=5为选区长度
- 从右往左选
from=head, to=anchor, empty=false
可以看出
- from 视觉上开始位置
- to 视觉上结束位置
- anchor 动作上,开始拖动的位置
- head 动作上,结束拖动结束
- empty 选区是否为空,true则证明只有光标
ResolvePos
带$开头的都为ResolvePos对象
- $anchor: resolve(selection.anchor)
- $head: resolve(selection.head)
这些对象都是通过 editorView.state.doc.resolve(pos) 来得到这个位置的更丰富的信息
- depth: 深度
- path:经过了哪些Node节点
- pos: 当前pos
- nodeAfter: pos后面的Node节点
- nodeBefore: pos前面的Node节点
- parent: parent Node节点
位置计算
建议大家安装chrome的prosemirror developer tools插件
查看structure
具体的位置计算从dom结构上来看
// 原dom结构
<div contenteditable="true" translate="no" class="ProseMirror">
<div class="block_tile">
<p>中文</p>
</div>
</div>
// pos位置
<div contenteditable="true" translate="no" class="ProseMirror">0
<div class="block_tile">1
<p>2中3文4</p>5
</div>7
</div>8
0是doc开始的位置,每遇到一个<tag>或</tag>都加1,遇到字符+1。
所以根据dom的结构,很好算光标落到哪里的pos数值,也能算出距离目标位置的距离
选区实例
大家可以回头看 第二章schema的selectable juejin.cn/post/739253…
选区实例分为NodeSelection和TextSelection, 由schema的selectable控制
选中图片查看selection, 会看到selection是继承自NodeSelection对象
选区ranges
ranges是个数组,里面装的是SelectionRange,里面包含2个ResolvePos: to
选中多个块, 数据都会放到ranges里面
总结
这个章节只讲了选区的基础,还是希望大家多去操作看下
后续会专门讲一下UIL方面的东西