tiptap/packages/core/src/helpers/getMarkRange.ts

69 lines
1.6 KiB
TypeScript
Raw Normal View History

import { Mark as ProseMirrorMark, MarkType, ResolvedPos } from 'prosemirror-model'
import objectIncludes from '../utilities/objectIncludes'
2021-01-28 16:50:17 +08:00
import { Range } from '../types'
2020-04-22 20:22:31 +08:00
function findMarkInSet(
marks: ProseMirrorMark[],
type: MarkType,
attributes: Record<string, any> = {},
): ProseMirrorMark | undefined {
return marks.find(item => {
return item.type === type && objectIncludes(item.attrs, attributes)
})
}
function isMarkInSet(
marks: ProseMirrorMark[],
type: MarkType,
attributes: Record<string, any> = {},
): boolean {
return !!findMarkInSet(marks, type, attributes)
}
export default function getMarkRange(
$pos: ResolvedPos,
type: MarkType,
attributes: Record<string, any> = {},
): Range | void {
2020-04-22 20:22:31 +08:00
if (!$pos || !type) {
return
}
const start = $pos.parent.childAfter($pos.parentOffset)
if (!start.node) {
return
}
const mark = findMarkInSet(start.node.marks, type, attributes)
if (!mark) {
2020-04-22 20:22:31 +08:00
return
}
let startIndex = $pos.index()
let startPos = $pos.start() + start.offset
let endIndex = startIndex + 1
let endPos = startPos + start.node.nodeSize
findMarkInSet(start.node.marks, type, attributes)
while (startIndex > 0 && mark.isInSet($pos.parent.child(startIndex - 1).marks)) {
2020-04-22 20:22:31 +08:00
startIndex -= 1
startPos -= $pos.parent.child(startIndex).nodeSize
}
while (
endIndex < $pos.parent.childCount
&& isMarkInSet($pos.parent.child(endIndex).marks, type, attributes)
) {
2020-04-22 20:22:31 +08:00
endPos += $pos.parent.child(endIndex).nodeSize
endIndex += 1
}
return {
from: startPos,
to: endPos,
}
2020-04-22 20:22:31 +08:00
}