Skip to content
This repository was archived by the owner on Aug 24, 2019. It is now read-only.

Commit 4502a6b

Browse files
committed
fix: fix replace / remove, resync keys
1 parent 85b6bc1 commit 4502a6b

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

packages/h2x-traverse/src/NodePath.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import traverse from './'
55
class NodePath {
66
static get({ parent, container, listKey, key, context }) {
77
const node = container[key]
8+
if (!node) return null
89
return new NodePath({
910
listKey,
1011
key,
@@ -49,6 +50,13 @@ class NodePath {
4950
return false
5051
}
5152

53+
resyncKey() {
54+
if (!this.container) return
55+
for (let i = 0; i < this.container.length; i += 1) {
56+
if (this.container[i] === this.node) this.key = i
57+
}
58+
}
59+
5260
replace(node) {
5361
this.shouldStop = true
5462
this.node = node

packages/h2x-traverse/src/index.test.js

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -143,18 +143,27 @@ describe('traverse', () => {
143143
})
144144

145145
it('should be possible to remove attribute', () => {
146+
let replaced = false
147+
146148
const enter = jest.fn(path => {
147-
if (path.node.name === 'foo') {
149+
if (path.node.name === 'bar') {
148150
path.remove()
151+
// replace with remove should work
152+
if (replaced) path.replace(path.node)
153+
}
154+
155+
if (!replaced) {
156+
replaced = true
157+
path.replace(path.node)
149158
}
150159
})
151160

152161
const ast = parse(`<div foo bar x></div>`)
153162

154163
traverse(ast, { HTMLAttribute: { enter } })
155-
expect(enter).toHaveBeenCalledTimes(3)
164+
expect(enter).toHaveBeenCalledTimes(6)
156165

157166
traverse(ast, { HTMLAttribute: { enter } })
158-
expect(enter).toHaveBeenCalledTimes(5)
167+
expect(enter).toHaveBeenCalledTimes(7)
159168
})
160169
})

0 commit comments

Comments
 (0)