Skip to content

Commit

Permalink
Add support for sortof components! Fixes #1
Browse files Browse the repository at this point in the history
  • Loading branch information
developit committed Nov 4, 2016
1 parent c5a465c commit 13d8294
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 14 deletions.
28 changes: 14 additions & 14 deletions src/vhtml.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,26 @@ let sanitized = {};

/** Hyperscript reviver that constructs a sanitized HTML string. */
export default function h(name, attrs) {
let stack=[];
for (let i=arguments.length; i-- > 2; ) {
stack.push(arguments[i]);
}

// Sortof component support!
if (typeof name==='function') {
attrs.children = stack.reverse();
return name(attrs);
// return name(attrs, stack.reverse());
}

let s = `<${name}`;
if (attrs) for (let i in attrs) {
if (attrs[i]!==false && attrs[i]!=null) {
s += ` ${esc(i)}="${esc(attrs[i])}"`;
}
}
s += '>';
let stack=[];
for (let i=arguments.length; i-- > 2; ) stack.push(arguments[i]);

while (stack.length) {
let child = stack.pop();
if (child) {
Expand All @@ -26,18 +37,7 @@ export default function h(name, attrs) {
}
}
}

sanitized[s += `</${name}>`] = true;
return s;
}



// for fun:
/*
export default const h = (tag, attrs, ...kids) => (
`<${tag}${h.attrs(attrs)}>${[].concat(...kids).join('')}</${tag}>`
);
h.attrs = a => Object.keys(a || {}).reduce( (s,i) => `${s} ${h.esc(i)}="${h.esc(a[i]+'')}"`, '');
h.esc = str => str.replace(/[&<>"']/g, s=>`&${h.map[s]};`);
h.map = {'&':'amp','<':'lt','>':'gt','"':'quot',"'":'apos'};
*/
26 changes: 26 additions & 0 deletions test/vhtml.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,30 @@ describe('vhtml', () => {
`<div>ab<c>d</c>efg</div>`
);
});

it('should support sortof components', () => {
let items = ['one', 'two'];

const Item = ({ item, index, children }) => (
<li id={index}>
<h4>{item}</h4>
{children}
</li>
);

expect(
<div class="foo">
<h1>Hi!</h1>
<ul>
{ items.map( (item, index) => (
<Item {...{ item, index }}>
This is item {item}!
</Item>
)) }
</ul>
</div>
).to.equal(
`<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>`
);
});
});

0 comments on commit 13d8294

Please sign in to comment.