Skip to content

Commit

Permalink
Extend textBetween API by accepting function to stringify leaf nodes
Browse files Browse the repository at this point in the history
FEATURE: `textBetween` now allows its leaf text argument to be a function.
  • Loading branch information
kepta authored Oct 25, 2021
1 parent babdac8 commit 039a2ee
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/fragment.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export class Fragment {
this.nodesBetween(0, this.size, f)
}

// :: (number, number, ?string, ?string) → string
// :: (number, number, ?string, ?string | ?(leafNode: Node) -> string) → string
// Extract the text between `from` and `to`. See the same method on
// [`Node`](#model.Node.textBetween).
textBetween(from, to, blockSeparator, leafText) {
Expand All @@ -50,7 +50,7 @@ export class Fragment {
text += node.text.slice(Math.max(from, pos) - pos, to - pos)
separated = !blockSeparator
} else if (node.isLeaf && leafText) {
text += leafText
text += typeof leafText === 'function' ? leafText(node): leafText
separated = !blockSeparator
} else if (!separated && node.isBlock) {
text += blockSeparator
Expand Down
2 changes: 1 addition & 1 deletion src/node.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ export class Node {
// children.
get textContent() { return this.textBetween(0, this.content.size, "") }

// :: (number, number, ?string, ?string) → string
// :: (number, number, ?string, ?string | ?(leafNode: Node) -> string) → string
// Get all text between positions `from` and `to`. When
// `blockSeparator` is given, it will be inserted whenever a new
// block node is started. When `leafText` is given, it'll be
Expand Down
14 changes: 14 additions & 0 deletions test/test-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,20 @@ describe("Node", () => {
"paragraph", "foo", "bar", "image", "baz", "hard_break", "quux", "xyz"))
})

describe("textBetween", () => {
it("works when passing a custom function as leafText", () => {
const d = doc(p("foo", img, br))
ist(d.textBetween(0, d.content.size, '', (node) => {
if (node.type.name === 'image') {
return '<image>'
}
if (node.type.name === 'hard_break') {
return '<break>'
}
}), 'foo<image><break>')
})
})

describe("textContent", () => {
it("works on a whole doc", () => {
ist(doc(p("foo")).textContent, "foo")
Expand Down

0 comments on commit 039a2ee

Please sign in to comment.