How to detect whether an update comes from history

I am trying to integrate the CM6 history with an outer app undo stack.

For that purpose, I am looking for a way to detect whether a view update is coming from an undo/redo command. Here’s some stripped down code showing the approach:

const noop = () => true;

const state = EditorState.create({
  doc,
  extensions: [
    // Override the default keybindings, as these are handled by the app undo stack
    keymap.of([
      {key: 'Mod-z', run: noop},
      {key: 'Mod-y', mac: 'Mod-Shift-z', run: noop},
    ]),
    basicSetup,
    EditorView.updateListener.of(update => {
      // Can we determine whether the update was done by a undo/redo command?
      if (update.docChanged) {
        undoStack.push('Template Change',
          () => undo(update.view),
          () => redo(update.view)
        );
      }
    })
  ]
}));

(I know that the undo stack architecture is suboptimal, but this is an old code base)

The history module has the fromHistory annotation, but that is not exported.

Is there a way to handle this situation?

1 Like

Not currently, but it would probably be a good idea to make the history annotate the transactions it produces. Would having a userEvent annotation for this be useful for you?

So the view would automatically set the userEvent to type "undo" or "redo", right? That would make a lot of sense, and solve the problem I am facing.

Great. It’ll do this in the next major release (which I’m working on and should drop sometime this week).

I saw that this change landed in 0.19, so thanks a lot!

(I still have more work to do to properly integrate with the app undo stack, but this is a good step)

By the way, I wonder why you opted not to prefix the undo and redo events with history, so that we could more easily match using transaction.isUserEvent('history'). It works well as is, but a prefixed version would’ve been a bit more convenient.

I just saw that you also added select.undo and select.redo, which would explain why there’s no history. prefix.