[whatwg/dom] Proposal: New method to reorder child nodes (#891)

### Summary
The goal of this method is to allow for the reordering of child nodes without the need to remove them and re-append them. Currently, reordering child nodes (by re-appending) causes several undesired side effects:
- Reloading of iframes
- Restarting of animations
- Loss of selection which cannot be restored in certain input types

This is a problem for several frameworks, including [React](https://github.com/facebook/react), [Preact](https://github.com/preactjs/preact), and [Mithril](https://github.com/MithrilJS/mithril.js).

### Adding a new API vs changing existing APIs
Instead of adding a new API, we could change existing uses of DOM APIs to avoid reparenting. For example:
```html
<div id=parent>
  <div id=firstchild></div>
  <div id=secondchild></div>
</div>
<script>
  parent.appendChild(firstchild);
</script>
```
In this case, you can see that the script wants to move `firstchild` past `secondchild` and doesn't *necessarily* want the browser to remove `firstchild` from the DOM and reparent it, so we could try to change `appendChild` to keep the parent throughout the DOM modification and avoid the loss of state. 

However, I think a new API would be a better solution:
- Changing `appendChild` and other DOM modification methods would get more complicated due to [difficulties defining and standardizing the existing behavior](https://github.com/whatwg/dom/issues/808).
- If there are any sites out there which rely on the full reparenting logic, they could become broken.

### API shape
I have some ideas for what this method could look like:
- Provide a full list with all children in desired order.
`parentNode.reorderChildren([childOne, childTwo, childThree])`
- Move one child one spot forward or one spot backwards.
`childNode.movePastNextSibling()`
`childNode.moveBeforePreviousSibling()`
- Move child before or after another child.
`childNode.moveBefore(otherChildNode)`
`childNode.moveAfter(otherChildNode)`

I don't want to bikeshed too much on this until it really sounds like we will add a new method, but if any API shape seems particularly good please speak up so I can start prototyping.

### Relationship to https://github.com/whatwg/dom/issues/808
@annevk is https://github.com/whatwg/dom/issues/808 blocking us from having a new way to reorder child nodes? That issue seems more concerned about insertions and mutation events which don't really seem to apply to reordering. Couldn't we just have new spec steps with no special functionality for iframes and scripts and no mutation events?

I made this issue based on feedback in this discussion: https://github.com/whatwg/html/issues/5484

-- 
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/891

Received on Wednesday, 9 September 2020 23:09:20 UTC