From 13d82941bcda3cfd308e8a8dc831df92b136843b Mon Sep 17 00:00:00 2001 From: Jason Miller Date: Thu, 3 Nov 2016 20:39:39 -0400 Subject: [PATCH] Add support for sortof components! Fixes #1 --- src/vhtml.js | 28 ++++++++++++++-------------- test/vhtml.js | 26 ++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 14 deletions(-) diff --git a/src/vhtml.js b/src/vhtml.js index f641ece..10962fe 100644 --- a/src/vhtml.js +++ b/src/vhtml.js @@ -6,6 +6,18 @@ 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) { @@ -13,8 +25,7 @@ export default function h(name, attrs) { } } s += '>'; - let stack=[]; - for (let i=arguments.length; i-- > 2; ) stack.push(arguments[i]); + while (stack.length) { let child = stack.pop(); if (child) { @@ -26,18 +37,7 @@ export default function h(name, attrs) { } } } + sanitized[s += ``] = true; return s; } - - - -// for fun: -/* -export default const h = (tag, attrs, ...kids) => ( - `<${tag}${h.attrs(attrs)}>${[].concat(...kids).join('')}` -); -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'}; -*/ diff --git a/test/vhtml.js b/test/vhtml.js index 46c4745..0ab297c 100644 --- a/test/vhtml.js +++ b/test/vhtml.js @@ -51,4 +51,30 @@ describe('vhtml', () => { `
abdefg
` ); }); + + it('should support sortof components', () => { + let items = ['one', 'two']; + + const Item = ({ item, index, children }) => ( +
  • +

    {item}

    + {children} +
  • + ); + + expect( +
    +

    Hi!

    + +
    + ).to.equal( + `

    Hi!

    ` + ); + }); });