From 039a2ee3c411a85f0bbc812454aac55423113cd9 Mon Sep 17 00:00:00 2001 From: Kushan Joshi <0o3ko0@gmail.com> Date: Mon, 25 Oct 2021 02:28:22 -0400 Subject: [PATCH] Extend textBetween API by accepting function to stringify leaf nodes FEATURE: `textBetween` now allows its leaf text argument to be a function. --- src/fragment.js | 4 ++-- src/node.js | 2 +- test/test-node.js | 14 ++++++++++++++ 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/fragment.js b/src/fragment.js index 7badf09..8eae0e4 100644 --- a/src/fragment.js +++ b/src/fragment.js @@ -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) { @@ -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 diff --git a/src/node.js b/src/node.js index 9763c74..5552be6 100644 --- a/src/node.js +++ b/src/node.js @@ -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 diff --git a/test/test-node.js b/test/test-node.js index 35335ed..69a2b96 100644 --- a/test/test-node.js +++ b/test/test-node.js @@ -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 '' + } + if (node.type.name === 'hard_break') { + return '' + } + }), 'foo') + }) + }) + describe("textContent", () => { it("works on a whole doc", () => { ist(doc(p("foo")).textContent, "foo")