How to replace prosemirror content in ydoc on server side?

I have a prosemirror ydoc running in the browser that is connected using a websocket to a prosemirror ydoc running in my server to sync state. Everything works well as long as all updates are entered inside the browser.
However in some cases I need to update the document on the server as changes come in from a different source.
I’m applying those changes as follows (document is the new value):

const json = DOMParser.fromSchema(getSchema()).parse(document);
prosemirrorToYXmlFragment(json, ydoc.getXmlFragment('prosemirror'));

In most cases however, this adds the new values to the ydoc rather than replacing the ydoc with them, so I have the old document and the new document both in my ydoc.

What should I do to replace the content in the ydoc with my new content? It would be similar to doing CTRL-A in the editor and typing something new there, but then in the server component.

I answered long time ago to a thread about using default doc value, it probably applies here Initial offline value of a shared document - #21 by TeemuKoivisto

Not sure how it affects selections et cetera and does it make GC less efficient.

1 Like

@bosschaert

First you need to delete the existing content. Then you can insert new content. Ideally, you do this within a transaction, to avoid that the client temporarily sees empty content. Something like this might work:

const rootType = ydoc.getXmlFragment('prosemirror')
ydoc.transact(() => {
  rootType.delete(0, rootType.length)
  const json = DOMParser.fromSchema(getSchema()).parse(document);
  prosemirrorToYXmlFragment(json, rootType);
})