Re: [whatwg/dom] Add convenient, ergonomic, performant API for sorting siblings (#586)

Based in the discussion at the last triage meeting, I am interested in trying to satisfy both #586 and #891 with one new method: Element.reorderChildren().

Element.reorderChildren will take an array of nodes which are already children of the element and then reorder its children to match the provided list. If any nodes are in the given array but not in the child list, they are ignored. Similarly if any elements of the provided array aren’t Nodes, they are ignored. If any nodes are in the child list but not the array, they preserve their relative DOM order to each other but are placed at the end of the new child list. The purpose of all of these conditions is to ensure that `reorderChildren()` only reorders and can never add, remove, or reparent nodes.

No synchronous Mutation Events are fired. A MutationObserver “childList” observation will be emitted. This might need a new MutationRecord type such as `movedNodes` for this.

DOM Ranges which include a current child at the beginning or end of the Range will retain that same child after the reorder.

Images, iframes, input elements, embedded objects and other elements which maintain internal state retain that state and cannot observe the change internally to the element.

> I think solving the interoperability issues around #808 is a pre-requisite here.

I’m happy to help with interop issues here but I believe that it’s pretty straightforward: no script can run synchronously during a call to reorderChildren(). Since iframes and script elements can’t be inserted or removed, and no synchronous mutation events can be fired, this shouldn’t be possible.

> This is close to React keyed nodes so it allows somehow DOM diffing, a feature I’ve asked for years ago already, except is limited to always same list of nodes. Why not doing an extra step to handle also removed nodes and eventual new nodes, at this point? That way all diffing libraries can be gone and performance would win.

If we want to insert or remove nodes, then we have to not only resolve #808 but also [Ryosuke’s concerns](https://github.com/whatwg/html/issues/5484#issuecomment-619721168) about iframes and scripts. I’d like to help out with DOM diffing but I don’t think that is within scope of this method to simply reorder nodes. However, with the new (performant) `reorderChildren()` primitive, diffing libraries can use a combination of `remove()`, `appendChild()`, and `reorderChildren()` to optimally reconstruct the children of an Element.

-- 
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/dom/issues/586#issuecomment-1426042297

You are receiving this because you are subscribed to this thread.

Message ID: <whatwg/dom/issues/586/1426042297@github.com>

Received on Friday, 10 February 2023 16:21:35 UTC