feat: add findChildrenInRange helper

This commit is contained in:
Philipp Kühn
2021-05-17 11:29:41 +02:00
parent 2bd17c7dc6
commit 463661c5ed
4 changed files with 27 additions and 6 deletions

View File

@@ -1,10 +1,5 @@
import { Node as ProseMirrorNode } from 'prosemirror-model'
import { Predicate } from '../types'
type NodeWithPos = {
node: ProseMirrorNode,
pos: number,
}
import { Predicate, NodeWithPos } from '../types'
export default function findChildren(node: ProseMirrorNode, predicate: Predicate): NodeWithPos[] {
const nodesWithPos: NodeWithPos[] = []

View File

@@ -0,0 +1,20 @@
import { Node as ProseMirrorNode } from 'prosemirror-model'
import { Predicate, Range, NodeWithPos } from '../types'
/**
* Same as `findChildren` but searches only within a `range`.
*/
export default function findChildrenInRange(node: ProseMirrorNode, range: Range, predicate: Predicate): NodeWithPos[] {
const nodesWithPos: NodeWithPos[] = []
node.nodesBetween(range.from, range.to, (child, pos) => {
if (predicate(child)) {
nodesWithPos.push({
node: child,
pos,
})
}
})
return nodesWithPos
}

View File

@@ -15,6 +15,7 @@ export { default as mergeAttributes } from './utilities/mergeAttributes'
export { default as coordsAtPos } from './helpers/coordsAtPos'
export { default as getExtensionField } from './helpers/getExtensionField'
export { default as findChildren } from './helpers/findChildren'
export { default as findChildrenInRange } from './helpers/findChildrenInRange'
export { default as findParentNode } from './helpers/findParentNode'
export { default as findParentNodeClosestToPos } from './helpers/findParentNodeClosestToPos'
export { default as generateHTML } from './helpers/generateHTML'

View File

@@ -194,3 +194,8 @@ export type MarkRange = {
}
export type Predicate = (node: ProseMirrorNode) => boolean
export type NodeWithPos = {
node: ProseMirrorNode,
pos: number,
}