I feel I must mention that there exists a completely different approach to solving this problem, with HTMX or other "hypermedia" (let's keep all state on server) tools:
As soon as I started reading the docs on hx-sync and started imagining scenarios where that sort of functionality has been needed, I started thinking “man once the state gets this complex I’d really rather manage it in a proper programming language instead.”
I think it’s often reasonable to consider the DOM the “database” of the frontend, but it can also be nice to have an intermediary representation to create the appropriate transition. Inversion of control, you might say.