Rename a note from Draft to Map to Trip. Undo twice. Redo once. You should see Map. Now rename it to Packing. If clicking Redo brings Trip back, the editor retained a future that belonged to a different edit.
Follow one edit through both stacks
Keep the visible title separate from two lists. The end of each list is the next title to restore. A rename pushes the visible title onto the past list and clears the future. Undo pushes the visible title onto the future before restoring the most recent past title. Redo mirrors that move.
class TitleEditor:
def __init__(self, title):
self.title = title
self.past = []
self.future = []
def rename(self, title):
if title != self.title:
self.past.append(self.title)
self.title = title
self.future.clear()
def undo(self):
if self.past:
self.future.append(self.title)
self.title = self.past.pop()
def redo(self):
if self.future:
self.past.append(self.title)
self.title = self.future.pop()
editor = TitleEditor("Draft")
editor.rename("Map")
editor.rename("Trip")
editor.undo()
editor.undo()
editor.redo()
assert editor.title == "Map"
editor.rename("Packing")
editor.redo()
assert editor.title == "Packing"
editor.undo()
assert editor.title == "Map"
Choose what counts as an edit
After that final undo, the future contains Packing. Imagine the UI saves Map again when the text box loses focus. The equality check makes this harmless. If you clear the future before checking equality, merely tabbing out of the box will break redo. Try adding an unchanged rename followed by redo to the example. You should get Packing again.
Strings work well as snapshots because subsequent edits cannot mutate an old string. If you extend the editor to a list of checklist items, storing repeated references to the same mutable list will corrupt history. Either snapshot the state to the depth you allow edits, or store an operation with enough information to reverse it. For example, undoing a deletion requires the deleted text and its position. Python lists as stacks
