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

Commit f172bc4

Browse files
committed
fix: fix node removing
1 parent 964c0ab commit f172bc4

File tree

3 files changed

+32
-11
lines changed

3 files changed

+32
-11
lines changed

packages/h2x-traverse/src/NodePath.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,16 @@ class NodePath {
5858

5959
remove() {
6060
this.shouldStop = true
61+
if (this.type === 'HTMLElement') {
62+
this.parent.removeChild(this.node)
63+
} else if (this.type === 'HTMLAttribute') {
64+
this.parent.removeAttribute(this.node.name)
65+
} else if (Array.isArray(this.container)) {
66+
this.container.splice(this.key, 1)
67+
} else {
68+
this.container[this.key] = null
69+
}
6170
this.node = null
62-
this.container[this.key] = null
6371
}
6472

6573
_call(fns) {

packages/h2x-traverse/src/TraversalContext.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,14 @@ class TraversalContext {
2020
if (container.length === 0) return false
2121
let shouldStop = false
2222

23+
const paths = []
24+
2325
Array.from(container).forEach((value, key) => {
24-
if (!value) return
2526
const nodePath = this.create(parent, container, key, listKey)
27+
paths.push(nodePath)
28+
})
29+
30+
paths.forEach(nodePath => {
2631
if (nodePath && nodePath.visit()) shouldStop = true
2732
})
2833

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

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ describe('traverse', () => {
123123
expect(enter.mock.calls[1][0].type).toBe('HTMLElement')
124124
})
125125

126-
it('should be possible to remove', () => {
126+
it('should be possible to remove elements', () => {
127127
const enter = jest.fn(path => {
128128
if (path.node.tagName === 'DIV') {
129129
path.remove()
@@ -132,18 +132,26 @@ describe('traverse', () => {
132132

133133
const ast = parse(`<header><div></div><span></span></header>`)
134134

135-
traverse(ast, {
136-
enter,
137-
})
138-
135+
traverse(ast, { enter })
139136
expect(enter).toHaveBeenCalledTimes(3)
140-
expect(enter.mock.calls[0][0].type).toBe('HTMLElement')
141-
expect(enter.mock.calls[1][0].type).toBe('HTMLElement')
142137

143-
traverse(ast, {
144-
enter,
138+
traverse(ast, { enter })
139+
expect(enter).toHaveBeenCalledTimes(5)
140+
})
141+
142+
it('should be possible to remove attribute', () => {
143+
const enter = jest.fn(path => {
144+
if (path.node.name === 'foo') {
145+
path.remove()
146+
}
145147
})
146148

149+
const ast = parse(`<div foo bar x></div>`)
150+
151+
traverse(ast, { HTMLAttribute: { enter } })
152+
expect(enter).toHaveBeenCalledTimes(3)
153+
154+
traverse(ast, { HTMLAttribute: { enter } })
147155
expect(enter).toHaveBeenCalledTimes(5)
148156
})
149157
})

0 commit comments

Comments
 (0)