Skip to content

Commit 58e2218

Browse files
committed
Refactor code-style
* Add more docs to JSDoc * Replace dependency
1 parent 1444c33 commit 58e2218

File tree

3 files changed

+49
-16
lines changed

3 files changed

+49
-16
lines changed

lib/index.js

+40-15
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,55 @@
11
/**
2-
* @typedef {import('mdast').Root|import('mdast').Content} Node
2+
* @typedef {import('mdast').Root} Root
3+
* @typedef {import('mdast').Content} Content
34
* @typedef {import('mdast').Paragraph} Paragraph
45
*/
56

6-
import {remove} from 'unist-util-remove'
7+
/**
8+
* @typedef {Content | Root} Node
9+
*/
10+
11+
import {visit} from 'unist-util-visit'
712

813
/**
914
* Remove empty paragraphs in `tree`.
1015
*
1116
* @template {Node} Tree
17+
* Node type.
1218
* @param {Tree} tree
19+
* Tree to change.
1320
* @returns {Tree extends Paragraph ? Tree | null : Tree}
21+
* Changed tree, or `null` if it was an empty paragraph.
1422
*/
1523
export function squeezeParagraphs(tree) {
16-
/**
17-
* @param {Node} node
18-
* @returns {boolean}
19-
*/
20-
const filter = (node) =>
21-
Boolean(
22-
node.type === 'paragraph' &&
23-
node.children.every(
24-
(node) => node.type === 'text' && /^\s*$/.test(node.value)
25-
)
26-
)
24+
if (emptyParagraph(tree)) {
25+
// @ts-expect-error: it’s an empty paragraph.
26+
return null
27+
}
28+
29+
visit(tree, function (node, index, parent) {
30+
if (index !== null && parent && emptyParagraph(node)) {
31+
parent.children.splice(index, 1)
32+
return index
33+
}
34+
})
2735

28-
// @ts-expect-error: `remove` can’t narrow the above test.
29-
return remove(tree, {cascade: false}, filter)
36+
// @ts-expect-error: it’s not an empty paragraph.
37+
return tree
38+
}
39+
40+
/**
41+
* Check if a node is an empty paragraph.
42+
*
43+
* @param {Node} node
44+
* Node to check.
45+
* @returns {boolean}
46+
* Whether `node` was an empty paragraph.
47+
*/
48+
function emptyParagraph(node) {
49+
return (
50+
node.type === 'paragraph' &&
51+
node.children.every(
52+
(child) => child.type === 'text' && /^\s*$/.test(child.value)
53+
)
54+
)
3055
}

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
],
4242
"dependencies": {
4343
"@types/mdast": "^3.0.0",
44-
"unist-util-remove": "^3.0.0"
44+
"unist-util-visit": "^4.0.0"
4545
},
4646
"devDependencies": {
4747
"@types/tape": "^4.0.0",

test.js

+8
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
/**
22
* @typedef {import('mdast').Root} Root
3+
* @typedef {import('mdast').Paragraph} Paragraph
34
*/
45

56
import test from 'tape'
@@ -39,5 +40,12 @@ test((t) => {
3940
])
4041
])
4142
)
43+
44+
t.deepEqual(
45+
squeezeParagraphs(/** @type {Paragraph} */ (u('paragraph', []))),
46+
null,
47+
'should return `null` for empty paragraphs'
48+
)
49+
4250
t.end()
4351
})

0 commit comments

Comments
 (0)