Synchronization between image and reference to image

In my editor, images can be referred. I define image node with an extra id attr, and ref node which just keeps the id of the referred image.

I also have a global imgs = {}, which stores id: image-dom-node. It works for two purpose:

  1. guarantee a unique id be generated for new image is inserted
  2. when a ref is hovered on, the referred image can be previewed instantly

However, it brings the sync problems

  1. images could be deleted, leaves the dom node invalid
  2. cut images and paste back also makes the dom node in imgs invalid
  3. other images and refs may be copied from another editor, new items (duplicated id being replaced with a unique id) should be inserted into imgs

How should I deal with each problem above?

You could use appendTransaction to, on every update, ensure that your invariants still hold and fix them up when necessary. It is often cheap enough to just scan the whole document every time, but if you have huge documents or expensive-to-check constraints, you could try to do it incrementally by looking at the step maps from the update to see which parts of the document were changed.

Thank you for your hint. I will give it a try.