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

@josepharhar 

`reorderChildren` is *almost* ideal as far as reordering goes (no addition/removals). I'd let users specify a `previousNode` though. It would not complicate the implementation (unlike ranges which require a linear check to verify the bounds are in the right order in the children list, lest you end up with a circular result).

It can be implemented in linear time with the following algo (I suppose this is what you had in mind).

- given `parent.reorderChildren(nodes: Array<ChildNode|Cruft>, previousNode?: ChildNode|null = null)`

- let lastNode be the last non-cruft item of `nodes`
- repeat for each non-cruft `node` of `nodes`: 
  - if (`node` isn't `lastNode`) remove `node` from `parent`, turning its former neighbors into siblings.
  - attach `node.previousSibling` as the `nextSibling` of `previousNode` (a double link except when `previousNode` is `null`).
  - set `previousNode` to `node`.

This lets the child list in the state you described.

`parent.firstChild` and friends can now be fixed up. As an optimization, you can first scan `nodes` from both ends looking for contiguous nodes, narrowing the `[previousNode, lastNode]` range.

Having the possibility to specify the `previousNode` lets user avoid wasteful scenarios where they know where they want things to happen (like, say, swap the last two nodes of a list). In the most extreme case not having `previousNode` could lead to N x M operations: suppose `<List><Sublist /><Sublist />...</List>` Where `SubList` returns a fragment, and all sublists are sorted according to the same criterion. When the criterion changes, In order to rely on `reorderChildren` each sublist would have to scan its previous siblings and pass them all to the browser which would have to skip them. A two way trip for naught.

I still would like to have a way to re-parent nodes without reinitializing them (assuming there is implementer interest too), but this would require a different API. I'm therefore mapping and compiling the state of affairs re. #808 and side effects timelines. There are many inconsistencies but I think UAs could be brought in line with a consistent model without breaking WebCompat™ (relying on the fact that, since the timeline is inconsistent, relying on it right now is not viable).

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

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

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

Received on Tuesday, 14 February 2023 11:22:26 UTC