How to update content of the document from outside source?

I am generating document content from some data from the server.

function generateDoc(words) {
  return schema.node(
    "doc",
    null,
    words.map(word => schema.node("paragraph", null, [schema.text(word)]))
  );
}

User can edit the generated document. But in many cases, I have some updated data from the server (usually validations). And I want to update user’s document, but I need to save its selection, undo history, etc.

If I will do just this:

  // emulate external changes
  words[0] = "Something";

  // how to update doc here in state to save history, selection, etc?
  state = EditorState.create({
    doc: generateDoc(words),
    plugins: [
      history(),
      keymap({ "Mod-z": undo, "Mod-y": redo }),
      keymap(baseKeymap)
    ]
  });
  view.updateState(state);

the history and selection will be lost.

Are there any ways to generate transaction from old to new docs?

Demo: https://codesandbox.io/s/8yxj3qkj70

Well, yes. That is what transactions do. Don’t create a new state, but create a transaction that modifies the old one. Figuring out the proper range to replace is something that you’ll have to figure out for your domain, but it looks like it shouldn’t be too hard.

1 Like