Skip to content

Commit f7489d9

Browse files
NekRdevelopit
authored andcommitted
Support empty (void) tags (#3)
* Support empty tags * Improve test for empty (void) tags * Rename test for empty (void) tags * Inline empty-tags module in the project * Add forgotten empty-tags file * Simplify sanitization mapping
1 parent 7f14eae commit f7489d9

3 files changed

Lines changed: 66 additions & 10 deletions

File tree

src/empty-tags.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
export default [
2+
'area',
3+
'base',
4+
'br',
5+
'col',
6+
'command',
7+
'embed',
8+
'hr',
9+
'img',
10+
'input',
11+
'keygen',
12+
'link',
13+
'meta',
14+
'param',
15+
'source',
16+
'track',
17+
'wbr'
18+
];

src/vhtml.js

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import emptyTags from './empty-tags';
2+
13
// escape an attribute
24
let esc = str => String(str).replace(/[&<>"']/g, s=>`&${map[s]};`);
35
let map = {'&':'amp','<':'lt','>':'gt','"':'quot',"'":'apos'};
@@ -24,20 +26,27 @@ export default function h(name, attrs) {
2426
s += ` ${esc(i)}="${esc(attrs[i])}"`;
2527
}
2628
}
27-
s += '>';
2829

29-
while (stack.length) {
30-
let child = stack.pop();
31-
if (child) {
32-
if (child.pop) {
33-
for (let i=child.length; i--; ) stack.push(child[i]);
34-
}
35-
else {
36-
s += sanitized[child]===true ? child : esc(child);
30+
if (emptyTags.indexOf(name) === -1) {
31+
s += '>';
32+
33+
while (stack.length) {
34+
let child = stack.pop();
35+
if (child) {
36+
if (child.pop) {
37+
for (let i=child.length; i--; ) stack.push(child[i]);
38+
}
39+
else {
40+
s += sanitized[child]===true ? child : esc(child);
41+
}
3742
}
3843
}
44+
45+
s += `</${name}>`;
46+
} else {
47+
s += '>';
3948
}
4049

41-
sanitized[s += `</${name}>`] = true;
50+
sanitized[s] = true;
4251
return s;
4352
}

test/vhtml.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,4 +77,33 @@ describe('vhtml', () => {
7777
`<div class="foo"><h1>Hi!</h1><ul><li id="0"><h4>one</h4>This is item one!</li><li id="1"><h4>two</h4>This is item two!</li></ul></div>`
7878
);
7979
});
80+
81+
it('should support empty (void) tags', () => {
82+
expect(
83+
<div>
84+
<area />
85+
<base />
86+
<br />
87+
<col />
88+
<command />
89+
<embed />
90+
<hr />
91+
<img />
92+
<input />
93+
<keygen />
94+
<link />
95+
<meta />
96+
<param />
97+
<source />
98+
<track />
99+
<wbr />
100+
{/* Not void elements */}
101+
<div />
102+
<span />
103+
<p />
104+
</div>
105+
).to.equal(
106+
`<div><area><base><br><col><command><embed><hr><img><input><keygen><link><meta><param><source><track><wbr><div></div><span></span><p></p></div>`
107+
);
108+
});
80109
});

0 commit comments

Comments
 (0)