How to use UndoManager in best practice

import * as Y from '../src/index.js'
const doc = new Y.Doc()
const ymap = doc.getMap('map')
const undoManager = new Y.UndoManager(ymap, {
  trackedOrigins: new Set(['track'])
})
// initial value is 1
doc.transact(() => {
  ymap.set('prop', 1)
}, 'track')
// change to value 2 but undoManager not track it
doc.transact(() => {
  ymap.set('prop', 2)
})
// if now undoManager.undo() then it doesn't change anything
// ymap.toJSON() // {prop: 2} 
doc.transact(() => {
  ymap.set('prop', 3)
}, 'track')
// ymap.toJSON() {prop: 3}
undoManager.undo()
// ymao.toJSON() {prop: 2}

as you can see. The Ymap initial value is {prop : 1} .
Then when I update it, but I don’t want undoManager track it。 So simply not set origin.

Then I continue to update Ymap with {prop : 3}.
At now, If I call undoManger.undo then its value is {prop: 2}. But that’s not what I want. I want it to {prop: 1}

So is there a sort of mechanism to solve this problem?
In my thought, One Way is when I update its value to 3, I can add some metainformation to tell yjs original value like 1 in this example.
Second way is not to update YModel, but to comminicate these changes that I don’t want track throught network to other clients。 In this way, ymodel doesn’t get changed during middel process.

By default, the Y.UndoManager never overrides remote changes. If a change happens by a remote user, you usually don’t want to override it with an older value. That’s why this is the default behavior.

However, you can specify that you don’t want this behavior. Just add ignoreRemoteMapChanges: true to the options of the Y.UndoManager. Note that this feature is experimental.

1 Like
doc.transact(() => {
  ymap.set('prop', 1)
}, 'track')
doc.transact(() => {
  ymap.set('prop', 2)
})
doc.transact(() => {
  ymap.set('prop', 3)
}, 'track')

Would ignoreRemoteMapChanges work in local?
I mean when I call undoManager.undo after a series of update above. Can I get ymap with prop of 1 not 2.

because I don’t want to track {prop: 2} but I need to transfer these changes to other clients.
So if I undo in local, it returns to {prop: 1} would be better.

Yes, that is how it works.

1 Like