choojs / hyperx

🏷 - tagged template string virtual dom builder
BSD 2-Clause "Simplified" License
1.01k stars 48 forks source link

How to handle multiple roots? #65

Closed finnp closed 5 years ago

finnp commented 6 years ago

Right now, this will throw the error multiple root elements must be wrapped in an enclosing tag if more than one root element are given.

For nanohtml it would be pretty great to support multiple root elements, probably using DocumentFragment.

However it seems to me like all hyperscript-style modules also don't support multiple roots. There is a proposal, but it was never implemented: https://github.com/hyperhype/hyperscript/issues/37

I suggest that maybe for now, we can allow an option on hyperx like createFragment. If it's spacified hyperx will call that function with the array of nodes instead of throwing an error.

The change would simply be:

      if (opts.createFragment) return opts.createFragment(tree[2])
      throw new Error(
        'multiple root elements must be wrapped in an enclosing tag'
      )

Then whoever uses hyperx (like nanohtml) could do something like for example:

function createFragment (nodes) {
  var fragment = document.createDocumentFragment()
  for (var i = 0; i < nodes.length; i++) {
    if (typeof nodes[i] === 'string') nodes[i] = document.createTextNode(nodes[i])
    fragment.appendChild(nodes[i])
  }
  return fragment  
}

hyperx(createElement, {
  comments: true
  createFragment: createFragment
})

I just tried this and it seemed to work, but I want to get some feedback first :)

yoshuawuyts commented 6 years ago

@finnp I think that's a pretty reasonable approach. Defaults to safety, but allows opting-in to new behavior for those of us that can support it. Neat!