Mutate document without side effect

Hi, I’m attaching collaborative editing library to ProseMirror, and the following problems arise.

  1. Client A edit the document, and broadcast edited range to other client.
  • The broadcast function is called from plugin.state.apply
  1. Client B receives changes and applies them to documents.
  • plugin.state.apply called again when apply changes.
  1. Client A receives changes and applies them to documents… and step 2-3 repeat forever.

Is there any way to change the contents of the document without side effects? or Am I using something wrong? (I think I am, but I don’t know what it is)

The code of my plugin is like this.

{
  state: {
    apply(tr) {
      if (tr.docChanged) {
        broadcastChanges(foo(tr));
      }
    }
  },
  view(view) {
    collabDocument.onChange((change) => {
      if (client.id === change.user.id) {
        return;
      }
      let { state } = view;
      state = state.apply(state.tr.insertText(change.text, changes.from));
      view.updateState(state);
    });
  },
}

I would check how prosemirror-collab does it. prosemirror-collab/collab.js at master · ProseMirror/prosemirror-collab · GitHub

You can use transaction.setMeta and transaction.getMeta to keep track of whats caused by the current user and should be broadcasted and what is coming in and shouldn’t be broadcasted again.