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

Commit

Permalink
fix: fix replace / remove, resync keys
Browse files Browse the repository at this point in the history
  • Loading branch information
gregberge committed Sep 1, 2017
1 parent 85b6bc1 commit 4502a6b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
8 changes: 8 additions & 0 deletions packages/h2x-traverse/src/NodePath.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import traverse from './'
class NodePath {
static get({ parent, container, listKey, key, context }) {
const node = container[key]
if (!node) return null
return new NodePath({
listKey,
key,
Expand Down Expand Up @@ -49,6 +50,13 @@ class NodePath {
return false
}

resyncKey() {
if (!this.container) return
for (let i = 0; i < this.container.length; i += 1) {
if (this.container[i] === this.node) this.key = i
}
}

replace(node) {
this.shouldStop = true
this.node = node
Expand Down
15 changes: 12 additions & 3 deletions packages/h2x-traverse/src/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,18 +143,27 @@ describe('traverse', () => {
})

it('should be possible to remove attribute', () => {
let replaced = false

const enter = jest.fn(path => {
if (path.node.name === 'foo') {
if (path.node.name === 'bar') {
path.remove()
// replace with remove should work
if (replaced) path.replace(path.node)
}

if (!replaced) {
replaced = true
path.replace(path.node)
}
})

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

traverse(ast, { HTMLAttribute: { enter } })
expect(enter).toHaveBeenCalledTimes(3)
expect(enter).toHaveBeenCalledTimes(6)

traverse(ast, { HTMLAttribute: { enter } })
expect(enter).toHaveBeenCalledTimes(5)
expect(enter).toHaveBeenCalledTimes(7)
})
})

0 comments on commit 4502a6b

Please sign in to comment.