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

Commit 35ef399

Browse files
committed
feat: add path.remove
1 parent f6472c8 commit 35ef399

File tree

4 files changed

+36
-3
lines changed

4 files changed

+36
-3
lines changed

packages/h2x-traverse/src/NodePath.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,15 +56,21 @@ class NodePath {
5656
this.context.visit(this.container, this.key)
5757
}
5858

59+
remove() {
60+
this.shouldStop = true
61+
this.node = null
62+
this.container[this.key] = null
63+
}
64+
5965
_call(fns) {
6066
if (!fns) return false
6167
if (!Array.isArray(fns)) fns = [fns]
6268

6369
for (const fn of fns) {
6470
if (!fn) continue
6571

66-
// Node has been removed, it will have been requeued
6772
const node = this.node
73+
if (!node) return true
6874

6975
const ret = fn(this, this.state)
7076
if (ret)

packages/h2x-traverse/src/TraversalContext.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,12 @@ class TraversalContext {
1919
visitMultiple(container, parent, listKey) {
2020
if (container.length === 0) return false
2121
let shouldStop = false
22-
for (let key = 0; key < container.length; key += 1) {
22+
23+
Array.from(container).forEach((value, key) => {
24+
if (!value) return
2325
const nodePath = this.create(parent, container, key, listKey)
2426
if (nodePath && nodePath.visit()) shouldStop = true
25-
}
27+
})
2628

2729
return shouldStop
2830
}

packages/h2x-traverse/src/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { getNodeVisitorKeys } from 'h2x-types'
33
import TraversalContext from './TraversalContext'
44

55
function traverse(ast, opts = {}, state = {}) {
6+
if (!ast) return
67
const keys = getNodeVisitorKeys(ast)
78
if (!keys) return
89

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,4 +122,28 @@ describe('traverse', () => {
122122
expect(enter.mock.calls[0][0].type).toBe('HTMLElement')
123123
expect(enter.mock.calls[1][0].type).toBe('HTMLElement')
124124
})
125+
126+
it('should be possible to remove', () => {
127+
const enter = jest.fn(path => {
128+
if (path.node.tagName === 'DIV') {
129+
path.remove()
130+
}
131+
})
132+
133+
const ast = parse(`<header><div></div><span></span></header>`)
134+
135+
traverse(ast, {
136+
enter,
137+
})
138+
139+
expect(enter).toHaveBeenCalledTimes(3)
140+
expect(enter.mock.calls[0][0].type).toBe('HTMLElement')
141+
expect(enter.mock.calls[1][0].type).toBe('HTMLElement')
142+
143+
traverse(ast, {
144+
enter,
145+
})
146+
147+
expect(enter).toHaveBeenCalledTimes(5)
148+
})
125149
})

0 commit comments

Comments
 (0)