Skip to content

Commit

Permalink
Treat single top-level array template part as a fragment (#74)
Browse files Browse the repository at this point in the history
Previously, this already generated a fragment, with 3 nodes:

```js
hx`
  <a></a>
  ${[1, 2]}
`
```

It would make sense for this to also generate a fragment, with 2 nodes:

```js
hx`
  ${[1, 2]}
`
```
  • Loading branch information
goto-bus-stop committed Feb 19, 2019
1 parent 8361482 commit a535fd5
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
10 changes: 10 additions & 0 deletions index.js
Expand Up @@ -137,6 +137,16 @@ module.exports = function (h, opts) {
tree[2].shift()
}

// handle single top-level array template part
if ((
// hx`${[ ...els ]}`
tree[2].length === 1 ||
// trailing whitespace: hx`${[ ...els ]} `
tree[2].length === 2 && /^\s*$/.test(tree[2][1])
) && Array.isArray(tree[2][0])) {
tree[2] = tree[2][0]
}

if (tree[2].length > 2
|| (tree[2].length === 2 && /\S/.test(tree[2][1]))) {
if (opts.createFragment) return opts.createFragment(tree[2])
Expand Down
24 changes: 18 additions & 6 deletions test/fragments.js
Expand Up @@ -4,14 +4,26 @@ var hyperx = require('../')
var hx = hyperx(vdom.h, {createFragment: createFragment})

function createFragment (nodes) {
return nodes
return { frag: nodes }
}

test('mutliple root, fragments as array', function (t) {
test('multiple root, fragments as array', function (t) {
var list = hx`<li>1</li> <li>2<div>_</div></li>`
t.equal(list.length, 3, '3 elements')
t.equal(vdom.create(list[0]).toString(), '<li>1</li>')
t.equal(list[1], ' ')
t.equal(vdom.create(list[2]).toString(), '<li>2<div>_</div></li>')
t.ok(Array.isArray(list.frag))
t.equal(list.frag.length, 3, '3 elements')
t.equal(vdom.create(list.frag[0]).toString(), '<li>1</li>')
t.equal(list.frag[1], ' ')
t.equal(vdom.create(list.frag[2]).toString(), '<li>2<div>_</div></li>')
t.end()
})

test('multiple root embeds, fragments as array', function (t) {
var list = hx`
${[1,2]}
`
t.ok(Array.isArray(list.frag))
t.deepEqual(list, {
frag: [1, 2]
})
t.end()
})

0 comments on commit a535fd5

Please sign in to comment.