2021-09-10 05:51:05 +08:00
|
|
|
import { Range, TextSerializer } from '../types'
|
|
|
|
import { Node as ProseMirrorNode } from 'prosemirror-model'
|
|
|
|
|
2021-12-06 19:00:09 +08:00
|
|
|
export function getTextBetween(
|
2021-09-10 05:51:05 +08:00
|
|
|
startNode: ProseMirrorNode,
|
|
|
|
range: Range,
|
|
|
|
options?: {
|
|
|
|
blockSeparator?: string,
|
|
|
|
textSerializers?: Record<string, TextSerializer>,
|
|
|
|
},
|
|
|
|
): string {
|
|
|
|
const { from, to } = range
|
|
|
|
const {
|
|
|
|
blockSeparator = '\n\n',
|
|
|
|
textSerializers = {},
|
|
|
|
} = options || {}
|
|
|
|
let text = ''
|
|
|
|
let separated = true
|
|
|
|
|
|
|
|
startNode.nodesBetween(from, to, (node, pos, parent, index) => {
|
|
|
|
const textSerializer = textSerializers?.[node.type.name]
|
|
|
|
|
|
|
|
if (textSerializer) {
|
|
|
|
if (node.isBlock && !separated) {
|
|
|
|
text += blockSeparator
|
|
|
|
separated = true
|
|
|
|
}
|
|
|
|
|
|
|
|
text += textSerializer({
|
|
|
|
node,
|
|
|
|
pos,
|
|
|
|
parent,
|
|
|
|
index,
|
2022-04-05 23:27:25 +08:00
|
|
|
range,
|
2021-09-10 05:51:05 +08:00
|
|
|
})
|
|
|
|
} else if (node.isText) {
|
|
|
|
text += node?.text?.slice(Math.max(from, pos) - pos, to - pos)
|
|
|
|
separated = false
|
|
|
|
} else if (node.isBlock && !separated) {
|
|
|
|
text += blockSeparator
|
|
|
|
separated = true
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
return text
|
|
|
|
}
|