From a535fd5b119a7ca1750ad53e860167409fc4def5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9e=20Kooi?= Date: Tue, 19 Feb 2019 13:00:37 +0100 Subject: [PATCH] Treat single top-level array template part as a fragment (#74) Previously, this already generated a fragment, with 3 nodes: ```js hx` ${[1, 2]} ` ``` It would make sense for this to also generate a fragment, with 2 nodes: ```js hx` ${[1, 2]} ` ``` --- index.js | 10 ++++++++++ test/fragments.js | 24 ++++++++++++++++++------ 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/index.js b/index.js index de6fc07..ab16378 100644 --- a/index.js +++ b/index.js @@ -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]) diff --git a/test/fragments.js b/test/fragments.js index f6770cc..1855a6b 100644 --- a/test/fragments.js +++ b/test/fragments.js @@ -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`
  • 1
  • 2
    _
  • ` - t.equal(list.length, 3, '3 elements') - t.equal(vdom.create(list[0]).toString(), '
  • 1
  • ') - t.equal(list[1], ' ') - t.equal(vdom.create(list[2]).toString(), '
  • 2
    _
  • ') + t.ok(Array.isArray(list.frag)) + t.equal(list.frag.length, 3, '3 elements') + t.equal(vdom.create(list.frag[0]).toString(), '
  • 1
  • ') + t.equal(list.frag[1], ' ') + t.equal(vdom.create(list.frag[2]).toString(), '
  • 2
    _
  • ') + 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() })