Skip to content

Commit

Permalink
add ability to render children
Browse files Browse the repository at this point in the history
  • Loading branch information
jescalan committed May 1, 2017
1 parent e4ef83d commit 707dc08
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 6 deletions.
29 changes: 23 additions & 6 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,29 @@ module.exports = (components) => {
return util.modifyNodes(tree, (node) => {
return Object.keys(components).indexOf(node.name) > -1
}, (node) => {
const Component = components[node.name]
const props = {}
for (let k in node.attrs) {
props[k] = node.attrs[k].map((n) => n.content).join('')
}
return parse(render(h(Component, props)))
return parse(render(toVnode(components, node)))
})
}
}

function toVnode (components, node) {
// get element name or component name if registered
const name = components[node.name] || node.name
// convert props to strings
const props = {}
for (let k in node.attrs) {
props[k] = node.attrs[k].map((n) => n.content).join('')
}
// content is either a string, a subtree, or there isn't any
if (typeof node.content === 'string') {
return h(name, props, node.content)
} else if (Array.isArray(node.content)) {
const subtree = node.content.map((n) => {
if (n.type === 'tag') return toVnode(components, n)
if (n.type === 'text') return n.content
})
return h(name, props, subtree)
} else {
return h(name, props)
}
}
18 changes: 18 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,21 @@ test('multi element, different props', (t) => {
t.is(res.output(), '<p>the value of foo is "bar"</p><p>wow</p><p>the value of foo is "wow"</p>')
})
})

test('renders children', (t) => {
const MyComponent = ({ foo, children }) => {
return h('div', { class: 'parent' }, children)
}

const c2 = () => {
return h('div', { class: 'wow' }, 'hello from c2')
}

const html = "<my-component foo='bar'><p>wow</p><div><c2></c2></div></my-component>"

return reshape({ plugins: [ssr({ 'my-component': MyComponent, c2 })] })
.process(html)
.then((res) => {
t.is(res.output(), '<div class="parent"><p>wow</p><div><div class="wow">hello from c2</div></div></div>')
})
})

0 comments on commit 707dc08

Please sign in to comment.