Skip to content

Commit 13d8294

Browse files
committed
Add support for sortof components! Fixes #1
1 parent c5a465c commit 13d8294

2 files changed

Lines changed: 40 additions & 14 deletions

File tree

src/vhtml.js

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,26 @@ let sanitized = {};
66

77
/** Hyperscript reviver that constructs a sanitized HTML string. */
88
export default function h(name, attrs) {
9+
let stack=[];
10+
for (let i=arguments.length; i-- > 2; ) {
11+
stack.push(arguments[i]);
12+
}
13+
14+
// Sortof component support!
15+
if (typeof name==='function') {
16+
attrs.children = stack.reverse();
17+
return name(attrs);
18+
// return name(attrs, stack.reverse());
19+
}
20+
921
let s = `<${name}`;
1022
if (attrs) for (let i in attrs) {
1123
if (attrs[i]!==false && attrs[i]!=null) {
1224
s += ` ${esc(i)}="${esc(attrs[i])}"`;
1325
}
1426
}
1527
s += '>';
16-
let stack=[];
17-
for (let i=arguments.length; i-- > 2; ) stack.push(arguments[i]);
28+
1829
while (stack.length) {
1930
let child = stack.pop();
2031
if (child) {
@@ -26,18 +37,7 @@ export default function h(name, attrs) {
2637
}
2738
}
2839
}
40+
2941
sanitized[s += `</${name}>`] = true;
3042
return s;
3143
}
32-
33-
34-
35-
// for fun:
36-
/*
37-
export default const h = (tag, attrs, ...kids) => (
38-
`<${tag}${h.attrs(attrs)}>${[].concat(...kids).join('')}</${tag}>`
39-
);
40-
h.attrs = a => Object.keys(a || {}).reduce( (s,i) => `${s} ${h.esc(i)}="${h.esc(a[i]+'')}"`, '');
41-
h.esc = str => str.replace(/[&<>"']/g, s=>`&${h.map[s]};`);
42-
h.map = {'&':'amp','<':'lt','>':'gt','"':'quot',"'":'apos'};
43-
*/

test/vhtml.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,4 +51,30 @@ describe('vhtml', () => {
5151
`<div>ab<c>d</c>efg</div>`
5252
);
5353
});
54+
55+
it('should support sortof components', () => {
56+
let items = ['one', 'two'];
57+
58+
const Item = ({ item, index, children }) => (
59+
<li id={index}>
60+
<h4>{item}</h4>
61+
{children}
62+
</li>
63+
);
64+
65+
expect(
66+
<div class="foo">
67+
<h1>Hi!</h1>
68+
<ul>
69+
{ items.map( (item, index) => (
70+
<Item {...{ item, index }}>
71+
This is item {item}!
72+
</Item>
73+
)) }
74+
</ul>
75+
</div>
76+
).to.equal(
77+
`<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>`
78+
);
79+
});
5480
});

0 commit comments

Comments
 (0)