[whatwg/dom] Update the "convert nodes into a node" to accept arrays of nodes. (#828)

The natural container for nodes is the DocumentFragment, but since it loses its children on insertion, it can't be used to hold onto them.

It would be nice if `.append()`, `.before` and friends could accept JS Arrays of nodes and domstrings as well The "convert nodes" algo can be updated to:

```JS
// TODO: translate to standardese :-)

function convert(...nodes) {
  const accumulator = document.createDocumentFragment()
  const circularCheck = new Set()
  const depth = 0

  nodes.forEach(node => _convert(node, accumulator, circularCheck, depth))

  return accumulator
}

function _convert(node, acc, circularCheck, depth) {
  if (depth > MAX_RECURSION_DEPTH) throw new Error("Max recursion depth exceeded")
  if (Array.isArray(node) {
    if circularCheck.has(node) throw new Error("Circular reference in Array<Node>")
    circularCheck.add(node)
    node.forEach(n => _convert(n, acc, circular, depth + 1))
  else {
    // convert strings to TextNode if needed, and insert
  }
}
```

`depth` and `circularCheck` may seem redundant, but they serve distinct purposes:

The circular ref check being there to help with accidental misuse, providing more accurate feedback to autors.

The depth check is there to prevent stack overflows triggered by passing an array that misuses getters:

```JS
function misuse(a) {
  a[0] = null
  Object.defineProperty(a, '0', {get() {return misuse([])}})
  return a  
}
node.append(misuse([])) // boom
```

----

As a side note, I see that the spec graduated without #433 being implemented, and I suppose that it may be too late now to change it, for Web compat reasons (re. mutation records)...

If it isn't can we revisit it? It is a shame that the new, ergonomic API is slower than the clunkier one. Especially because it could be faster, since it lend itself to fewer JS/native round-trips.

The spec for the DOM4 methods would become more complex though.

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/dom/issues/828

Received on Tuesday, 4 February 2020 09:47:28 UTC