Skip to content

Commit b40a41f

Browse files
committed
Fix bug when replacing and then not
Closes remarkjs/remark-github#40.
1 parent a5910c7 commit b40a41f

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

lib/index.js

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,7 @@ export const findAndReplace =
137137
let start = 0
138138
// @ts-expect-error: TS is wrong, some of these children can be text.
139139
const index = parent.children.indexOf(node)
140+
let change = false
140141
/** @type {Array<PhrasingContent>} */
141142
let nodes = []
142143
/** @type {number|undefined} */
@@ -160,9 +161,7 @@ export const findAndReplace =
160161
value = value.length > 0 ? {type: 'text', value} : undefined
161162
}
162163

163-
if (value === false) {
164-
position = undefined
165-
} else {
164+
if (value !== false) {
166165
if (start !== position) {
167166
nodes.push({
168167
type: 'text',
@@ -177,6 +176,7 @@ export const findAndReplace =
177176
}
178177

179178
start = position + match[0].length
179+
change = true
180180
}
181181

182182
if (!find.global) {
@@ -186,14 +186,14 @@ export const findAndReplace =
186186
match = find.exec(node.value)
187187
}
188188

189-
if (position === undefined) {
190-
nodes = [node]
191-
} else {
189+
if (change) {
192190
if (start < node.value.length) {
193191
nodes.push({type: 'text', value: node.value.slice(start)})
194192
}
195193

196194
parent.children.splice(index, 1, ...nodes)
195+
} else {
196+
nodes = [node]
197197
}
198198

199199
return index + nodes.length

test.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,25 @@ test('findAndReplace', (t) => {
236236
'should not be order-sensitive with regexes'
237237
)
238238

239+
t.deepEqual(
240+
findAndReplace(u('paragraph', [u('text', 'aaa bbb')]), [
241+
[
242+
/\b\w+\b/g,
243+
function (/** @type {string} */ value) {
244+
return value === 'aaa' ? u('strong', [u('text', value)]) : false
245+
}
246+
]
247+
]),
248+
{
249+
type: 'paragraph',
250+
children: [
251+
{type: 'strong', children: [{type: 'text', value: 'aaa'}]},
252+
{type: 'text', value: ' bbb'}
253+
]
254+
},
255+
'should support a match, and then a `false`'
256+
)
257+
239258
t.deepEqual(
240259
findAndReplace(create(), 'emphasis', () => false),
241260
u('paragraph', [

0 commit comments

Comments
 (0)