2023-02-03 00:37:33 +08:00
|
|
|
import { Node as ProseMirrorNode } from '@tiptap/pm/model'
|
2021-09-10 05:51:05 +08:00
|
|
|
|
2023-07-01 03:03:49 +08:00
|
|
|
import { Range, TextSerializer } from '../types.js'
|
2022-06-08 20:10:25 +08:00
|
|
|
|
2024-05-14 00:28:53 +08:00
|
|
|
/**
|
|
|
|
* Gets the text between two positions in a Prosemirror node
|
|
|
|
* and serializes it using the given text serializers and block separator (see getText)
|
|
|
|
* @param startNode The Prosemirror node to start from
|
|
|
|
* @param range The range of the text to get
|
|
|
|
* @param options Options for the text serializer & block separator
|
|
|
|
* @returns The text between the two positions
|
|
|
|
*/
|
2021-12-06 19:00:09 +08:00
|
|
|
export function getTextBetween(
|
2021-09-10 05:51:05 +08:00
|
|
|
startNode: ProseMirrorNode,
|
|
|
|
range: Range,
|
|
|
|
options?: {
|
2023-02-03 00:37:33 +08:00
|
|
|
blockSeparator?: string
|
|
|
|
textSerializers?: Record<string, TextSerializer>
|
2021-09-10 05:51:05 +08:00
|
|
|
},
|
|
|
|
): string {
|
|
|
|
const { from, to } = range
|
2023-02-03 00:37:33 +08:00
|
|
|
const { blockSeparator = '\n\n', textSerializers = {} } = options || {}
|
2021-09-10 05:51:05 +08:00
|
|
|
let text = ''
|
|
|
|
|
|
|
|
startNode.nodesBetween(from, to, (node, pos, parent, index) => {
|
2024-05-10 08:51:22 +08:00
|
|
|
if (node.isBlock && pos > from) {
|
|
|
|
text += blockSeparator
|
|
|
|
}
|
|
|
|
|
2021-09-10 05:51:05 +08:00
|
|
|
const textSerializer = textSerializers?.[node.type.name]
|
|
|
|
|
|
|
|
if (textSerializer) {
|
2022-06-20 17:45:37 +08:00
|
|
|
if (parent) {
|
|
|
|
text += textSerializer({
|
|
|
|
node,
|
|
|
|
pos,
|
|
|
|
parent,
|
|
|
|
index,
|
|
|
|
range,
|
|
|
|
})
|
|
|
|
}
|
2024-04-06 07:29:46 +08:00
|
|
|
// do not descend into child nodes when there exists a serializer
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
if (node.isText) {
|
2022-06-08 20:10:25 +08:00
|
|
|
text += node?.text?.slice(Math.max(from, pos) - pos, to - pos) // eslint-disable-line
|
2021-09-10 05:51:05 +08:00
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
return text
|
|
|
|
}
|