class_name SnapshotHistory extends RefCounted ## Undo and redo by whole snapshots (Dictionaries), for small documents such ## as a sheet. The caller records the state before each edit (record) and ## gets back the state to show on undo or redo. Spreads use EditHistory, which ## keeps per-card strings because spreads can be large. const MAX_STEPS := 200 var _undo: Array = [] # [{"state", "label"}] var _redo: Array = [] func can_undo() -> bool: return not _undo.is_empty() func can_redo() -> bool: return not _redo.is_empty() func undo_label() -> String: return str(_undo.back()["label"]) if can_undo() else "" func redo_label() -> String: return str(_redo.back()["label"]) if can_redo() else "" func clear() -> void: _undo.clear() _redo.clear() ## Records `before`, the state just before an edit called `label`. Clears redo. func record(before: Dictionary, label: String) -> void: _undo.append({"state": before.duplicate(true), "label": label}) if _undo.size() > MAX_STEPS: _undo.pop_front() _redo.clear() ## Steps back: give the current state, get the one to show ({} if none). func undo(current: Dictionary) -> Dictionary: if not can_undo(): return {} var step: Dictionary = _undo.pop_back() _redo.append({"state": current.duplicate(true), "label": step["label"]}) return step["state"] func redo(current: Dictionary) -> Dictionary: if not can_redo(): return {} var step: Dictionary = _redo.pop_back() _undo.append({"state": current.duplicate(true), "label": step["label"]}) return step["state"]