Skip to content

Proposal: New method to reorder child nodes #891

Open

Description

@josepharhar

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, Preact, and Mithril.

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:

<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:

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 #808

@annevk is #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: whatwg/html#5484

Activity

  1. annevk commented on Sep 10, 2020

    @annevk
    Member

    I think without fully understanding (and specifying) #808 it's hard to reason about how moving-within-a-parent should work. I.e., what side effects we need and do not need.

    I think the most logical API that follows existing conventions would be parent.moveChildBefore(Node child, Node? referenceChild). However, if sole use case is reordering multiple children parent.moveChildren(Node...) probably makes more sense. Either way this also requires designing new mutation records as this is a new mutation primitive. And we should probably forbid firing (legacy) mutation events.

    I would also like to see some more rationale as to why an arbitrary move (with both parents sharing a common root) is less feasible. What are the particular implementation challenges that we would only expose a more restricted move?

  2. dead-claudia commented on Sep 10, 2020

    @dead-claudia

    I'm not convinced of spec complexity of modifying existing operations being that much higher (though it would technically be somewhat higher): #880 (comment)

  3. bathos commented on Sep 10, 2020

    @bathos

    If there are any sites out there which rely on the full reparenting logic, they could become broken.

    The disconnectedCallback and connectedCallback reactions fire on custom elements when nodes are shuffled like this. It seems very unlikely to me that this would not break sites (including ours).

  4. josepharhar commented on Sep 10, 2020

    @josepharhar
    ContributorAuthor

    I would also like to see some more rationale as to why an arbitrary move (with both parents sharing a common root) is less feasible. What are the particular implementation challenges that we would only expose a more restricted move?

    This is due to @rniwa's comments in whatwg/html#5484 against reparenting iframes without reloading them.

  5. josepharhar commented on Sep 10, 2020

    @josepharhar
    ContributorAuthor

    I think without fully understanding (and specifying) #808 it's hard to reason about how moving-within-a-parent should work. I.e., what side effects we need and do not need.

    Moving within a parent should:

    • Not fire mutation events
    • Not run script inside of <script> elements, since that is supposed to be run on insertion
    • Not fire loading/unloading events for iframes, since those are supposed to happen when the iframe is appended or removed.

    Are there other types of side effects I'm not aware of?

  6. dead-claudia commented on Sep 10, 2020

    @dead-claudia

    @josepharhar Why shouldn't it fire a mutation event of a new type? If a new method is added specifically for moving elements around, they can't possibly fire that mutation without invoking that previously-unknown method anyways, so in theory, a page would have to have its contents updated to experience breakage.

    Also, I would expect it to invoke a new hook within custom elements to notify it of nodes being reordered. (This is very useful info for them, BTW, as libraries like A-Frame don't use shadow roots to render their data but otherwise need to know layout order at all times.)

    As for the rest, I agree.

  7. josepharhar commented on Sep 10, 2020

    @josepharhar
    ContributorAuthor

    @josepharhar Why shouldn't it fire a mutation event of a new type? If a new method is added specifically for moving elements around, they can't possibly fire that mutation without invoking that previously-unknown method anyways, so in theory, a page would have to have its contents updated to experience breakage.

    Yeah I presume that we would add new mutation signaling stuff for MutationObserver and whatever the equivalent is for custom elements (I'm not super familiar with either yet). I don't think that we should make new mutation events since they seem to be deprecated and people are interested in removing them from the web - I don't have historical context on this though. Right now I'm just trying to work through the relationship between this new proposed method and #808, which is interested in mutation events.
    To clarify - when I say "mutation events," I am referring to this: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events

  8. rniwa commented on Sep 11, 2020

    @rniwa

    I would really like to better understand what the use cases are. Could someone provide a concrete scenario (not just framework X does Y so they need it) in which this capability is desirable?

  9. josepharhar commented on Sep 11, 2020

    @josepharhar
    ContributorAuthor

    I would really like to better understand what the use cases are. Could someone provide a concrete scenario (not just framework X does Y so they need it) in which this capability is desirable?

    @sebmarkbage @isiahmeadows @marvinhagemeister @developit could any/all of you elaborate on scenarios where state is lost when reordering child nodes? Links to issues would be greatly appreciated, as well as live examples if possible.

    @isiahmeadows already made some live examples with four different frameworks listed in the description of #880. It does sound like appendChild has the desired behavior in that particular case though...?

  10. dead-claudia commented on Sep 11, 2020

    @dead-claudia

    @josepharhar The transitions issue is that of this:

    • Partial removal + reinsertion leaves unexpected transition state
    • Full removal + reinsertion resets everything

    Though now that I'm taking a closer look, I'm not sure movement semantics would help with transitions, as it reproduces even with simple add/remove. So my issue is independent of this.

    Edit: Further confirmed that the transitions issue is independent of this.

  11. annevk commented on Sep 11, 2020

    @annevk
    Member

    This is due to @rniwa's comments in whatwg/html#5484 against reparenting iframes without reloading them.

    I don't think that discussion was really settled though. Those arguments would apply to moving within a parent as well as you have to contend with subtrees and multiple elements there too.

  12. josepharhar commented on Sep 11, 2020

    @josepharhar
    ContributorAuthor

    I don't think that discussion was really settled though. Those arguments would apply to moving within a parent as well as you have to contend with subtrees and multiple elements there too.

    @rniwa said that "Since a node can't have multiple parents, it needs to be disconnected at some point in some internal engine state. That's precisely what caused the problem."
    When reordering children instead of reparenting them across the DOM, we will never have to change the pointer to the parent node, only the node's sibling pointers and the parent's first/last node pointers. @rniwa this does address your concern, right?

  13. rniwa commented on Sep 16, 2020

    @rniwa

    I don't think that discussion was really settled though. Those arguments would apply to moving within a parent as well as you have to contend with subtrees and multiple elements there too.

    @rniwa said that "Since a node can't have multiple parents, it needs to be disconnected at some point in some internal engine state. That's precisely what caused the problem."
    When reordering children instead of reparenting them across the DOM, we will never have to change the pointer to the parent node, only the node's sibling pointers and the parent's first/last node pointers. @rniwa this does address your concern, right?

    Well, it does address the previous concern but re-ordering nodes isn't something we've ever done so we'd likely encounter new list of issues with it. I'd still like to learn more about what specific use cases would require this new capability, and why careful manipulations of nodes in the user land won't suffice.

  14. annevk commented on Sep 17, 2020

    @annevk
    Member

    @rniwa what problem would be caused by disconnecting an <iframe> from its parent if we can also guarantee that no script would run until it is attached again?

  15. rniwa commented on Sep 20, 2020

    @rniwa

    @rniwa what problem would be caused by disconnecting an <iframe> from its parent if we can also guarantee that no script would run until it is attached again?

    Well, that's a big "if". Something like that is not possible to implement in WebKit today.

  16. 26 remaining items

  17. WebReflection commented on Apr 20, 2022

    @WebReflection

    @annevk we already all know what happens when you remove and insert one, right?

    ‘cause if we don’t to date, I don’t see why that’s relevant at all to decide what happens when these move instead 🤔

  18. samuelmtimbo commented on May 17, 2022

    @samuelmtimbo

    Having this proposal taken forward and still having iframes (and other elements) losing state when moving between different parents would feel like a big opportunity loss, because reordering within the same parent will only cover a portion of the use cases. For example, if iframes are part of a drag and drop interaction, they might need to change parents. Moreover, there are many complex interaction patterns that relly on reparenting.

    Is this more general version of "moving" being planned somewhere else? Should a new parallel proposal be started?

  19. fantasai commented on Aug 16, 2022

    @fantasai

    Just want to note that we see abuse of the CSS order property to perform semantic ordering because it's easier/faster than using the DOM. I think it would be helpful if we could redirect such people to an appropriate DOM API that made such reordering (for e.g. sorting lists, table rows, etc.) both easy and fast.

  20. wlib commented on Sep 25, 2022

    @wlib

    I think that the closest practical solution to this is the shadow dom with the imperative slot api.

    // Initially <body>abc</body>
    const a = document.createTextNode("a")
    const b = document.createTextNode("b")
    const c = document.createTextNode("c")
    document.body.append(a, b, c)
    
    // body is a shadow host with a manually assigned slot
    const slot = document.createElement("slot")
    document.body
      .attachShadow({
        mode: "open",
        slotAssignment: "manual"
      })
      .append(slot)
    // can put child nodes in any order, exclude them, &c.
    // even iframes will behave as if nothing happened
    slot.assign(c, b, a)

    Screen Shot 2022-09-25 at 2 42 51 PM

    Since it's just a slot, there's no fumbling with style sheets or anything either, and it works without custom elements. However, there are restrictions on what elements can be shadow hosts.

  21. mindplay-dk commented on Sep 26, 2022

    @mindplay-dk

    I think that the closest practical solution to this is the shadow dom with the imperative slot api.

    I don't think this is viable as an alternative - but since this API is already spec'ed and has concensus, a spec for generic DOM reordering should probably reference this.

    // even iframes will behave as if nothing happened

    The proposal makes no mention of preserving state of iframes, input elements, etc. - it doesn't look like this was spec'ed? So if it happens to work that way, that could be just luck. A generic DOM API likely needs to carefully spec this behavior.

  22. bathos commented on Sep 26, 2022

    @bathos

    makes no mention of preserving state of iframes, input elements, etc.

    There’s nothing unique about that proposal AFAIK — this is how slots themselves behave. Adding and removing slots dynamically is also possible but it isn’t reparenting the things that get non-manually assigned to them, just assigning em.

    let shadow = document.body.attachShadow({ mode: "closed" });
    document.body.innerHTML = "<iframe name=iframe>";
    iframe.document.bgColor = "slot assignment isn’t connection/disconnection";
    shadow.innerHTML = "<slot>";
  23. barneycarroll commented on Oct 26, 2022

    @barneycarroll

    Thanks @wlib, @bathos for highlighting this slot assignment behaviour. This interests me in the context of a few attempts I've made in the past to get predictable behaviour when moving chunks of DOM diagonally (ie from one parent node to another) in the least destructive way possible. I tried playing with this API to see if it could be used as a generic solution for re-ordering.

    CSS positional selectors stick to DOM ordering and don't reflect assignment order, which is fair enough. More interesting was that CSS list markers and counter increments seemed to respect assignment order in Firefox, while in Chrome they first fell out of sync, and in subsequent reorderings stuck to their last update.

    Here's a sandbox demonstrating the inconsistent behaviour.

    This indicates some ambiguity in the 'moving without moving' behaviour – perhaps useful in future API considerations.

  24. bathos commented on Oct 26, 2022

    @bathos

    @barneycarroll that’s a great find + demo.

    In CSS Lists 3, the “tree” whose tree order is used to determine counter inheritance is the flattened tree. It takes/updates any resolved counter values during that algorithm, and though it talks about parents and siblings, the note at the end specifically clarifies that the tree in question is the flattened tree. I think that would mean the Firefox behavior is consistent with what’s specified.

    An element inherits its initial set of counters from its parent and preceding sibling. It then takes the values for those counters from the values of the matching counters on its preceding element in tree order (which might be its parent, its preceding sibling, or a descendant of its previous sibling).
    [...]
    Note: Counter inheritance, like regular CSS inheritance, operates on the “flattened element tree” in the context of the [DOM].

    I’m not good at reading CSS specs, though and may be looking in the wrong place or misinterpreting. @tabatkins would you know whether Blink or Gecko (or neither) is rendering @barneycarroll’s demo correctly?

    (aside 4 barney: been off twitter for most of a year now but yr name is among the few I miss encountering. nice to see ya)

  25. tabatkins commented on Oct 26, 2022

    @tabatkins
    Contributor

    Unless otherwise specified, Selectors/Cascade is based on the DOM tree, and then everything else in CSS is based on the flattened tree. When this isn't true, it's almost certainly a browser bug; we're still shaking out wrong assumptions that predate the introduction of the flat tree.

    Chrome's "out of sync" counters are absolutely a counter invalidation bug; there is no world in which the counter going from 5-9 is correct.

  26. wlib commented on Oct 27, 2022

    @wlib

    in Chrome they first fell out of sync, and in subsequent reorderings stuck to their last update.

    Here's a sandbox demonstrating the inconsistent behaviour.

    screenshot demonstrating chrome list counter glitch

    Absolutely great to see this technique is being used; you should tell them about this in [this bug](https://bugs.chromium.org/p/chromium/issues/detail?id=1330383) report.

    Unless otherwise specified, Selectors/Cascade is based on the DOM tree, and then everything else in CSS is based on the flattened tree.

    Maybe I'm totally off, but there are use cases for having both. Is there any way that selectors can apply within the context of a slot? Like ::slotted(), but accepting, say, :first-assigned instead of :first-child?

  27. annevk commented on Feb 6, 2023

    @annevk
    Member

    Closing this as a duplicate of #586 as this is both newer and that issue appears to have more traction.

  28. chrishtr commented on Feb 6, 2023

    @chrishtr

    This issue is not a duplicate of #586, since the use case desired in this issue was avoiding reload of iframes and other resource/animation state.

  29. annevk commented on Feb 7, 2023

    @annevk
    Member

    I guess that's fair, but we really shouldn't offer both I think, especially if they end up looking identical to mutation observers. I'll reopen for now and instead consider it a blocker of sorts to come up with a reasonable story.

  30. reopened this on Feb 7, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions