How to turn my client-side DOM manipulations into DOM-patch aware manipulations?

I want to accomplish something similar as Phoenix.LiveView.JS, per the docs:

While these operations can be accomplished via client-side hooks, JS commands are DOM-patch aware, so operations applied by the JS APIs will stick to elements across patches from the server.

so I wonder, what’s the “trick” that makes LiveView.JS DOM-patch aware?

Because I want to use this “trick” for my own client-side DOM manipulation. I searched the source code for a while but I did not find the mechanism by which JS.operations are able to be DOM-patch aware.

Some alternatives that serve a similar purpose but feel too blunt for me:

  • phx-update="ignore": This is easy, it works mostly, but I don’t like it because the children cannot leverage LiveView events, it also feels clunky to sprinkle the HEEX template with this directive.
  • cloning nodes inside onBeforeElUpdated (docs): I don’t like this, there’s very little documentation about how the cloning function should work. It is also a tricky operation, if you clone a node then it might discard any LiveView operations that should have been applied to the node and its subtree. On top of that, it becomes necessary to “mark” with an HTML attribute the nodes that would get cloned.