28
28
29
29
/**
30
30
* @callback ReplaceFunction
31
- * @param {...unknown } parameters
31
+ * @param {...any } parameters
32
32
* @returns {Array.<Content>|Content|string|false|undefined|null }
33
33
*/
34
34
@@ -47,7 +47,7 @@ export const defaultIgnore = ['title', 'script', 'style', 'svg', 'math']
47
47
* @param {Options } [options]
48
48
*/
49
49
export function findAndReplace ( tree , find , replace , options ) {
50
- /** @type {Options } */
50
+ /** @type {Options|undefined } */
51
51
let settings
52
52
/** @type {FindAndReplaceSchema|FindAndReplaceList } */
53
53
let schema
@@ -79,7 +79,7 @@ export function findAndReplace(tree, find, replace, options) {
79
79
/** @type {import('unist-util-visit-parents').Visitor<Text> } */
80
80
function visitor ( node , parents ) {
81
81
let index = - 1
82
- /** @type {Parent } */
82
+ /** @type {Parent|undefined } */
83
83
let grandparent
84
84
85
85
while ( ++ index < parents . length ) {
@@ -100,7 +100,9 @@ export function findAndReplace(tree, find, replace, options) {
100
100
grandparent = parent
101
101
}
102
102
103
- return handler ( node , grandparent )
103
+ if ( grandparent ) {
104
+ return handler ( node , grandparent )
105
+ }
104
106
}
105
107
106
108
/**
@@ -115,7 +117,7 @@ export function findAndReplace(tree, find, replace, options) {
115
117
let index = parent . children . indexOf ( node )
116
118
/** @type {Array.<Content> } */
117
119
let nodes = [ ]
118
- /** @type {number } */
120
+ /** @type {number|undefined } */
119
121
let position
120
122
121
123
find . lastIndex = 0
@@ -127,17 +129,19 @@ export function findAndReplace(tree, find, replace, options) {
127
129
// @ts -expect-error this is perfectly fine, typescript.
128
130
let value = replace ( ...match , { index : match . index , input : match . input } )
129
131
130
- if ( typeof value === 'string' && value . length > 0 ) {
131
- value = { type : 'text' , value}
132
+ if ( typeof value === 'string' ) {
133
+ value = value . length > 0 ? { type : 'text' , value} : undefined
132
134
}
133
135
134
136
if ( value !== false ) {
135
137
if ( start !== position ) {
136
138
nodes . push ( { type : 'text' , value : node . value . slice ( start , position ) } )
137
139
}
138
140
139
- if ( value ) {
140
- nodes = [ ] . concat ( nodes , value )
141
+ if ( Array . isArray ( value ) ) {
142
+ nodes . push ( ...value )
143
+ } else if ( value ) {
144
+ nodes . push ( value )
141
145
}
142
146
143
147
start = position + match [ 0 ] . length
0 commit comments