Terra Draw supports two independent history scopes for undo/redo functionality. Both must be explicitly enabled in the TerraDraw constructor.
History Scopes
modeLevel (TerraDrawModeUndoRedo): Handles in-progress drawing history within a specific mode. For example, in TerraDrawPolygonMode, it allows undoing/redoing recently added coordinates before the polygon is finished.sessionLevel (TerraDrawSessionUndoRedo): Handles completed edit history across the entire session. It tracks operations like creating, updating, or deleting fully formed features.
Implementation
To use undo/redo, include the appropriate mode and optionally TerraDrawUndoRedoKeyboardShortcuts in your configuration. You can limit memory usage by setting maxStackSize.
Listen to the history event to sync your UI (e.g., enabling/disabling buttons).
import {
TerraDraw,
TerraDrawPolygonMode,
TerraDrawModeUndoRedo,
TerraDrawSessionUndoRedo,
TerraDrawUndoRedoKeyboardShortcuts,
} from "terra-draw";
const draw = new TerraDraw({
adapter,
modes: [new TerraDrawPolygonMode()],
undoRedo: {
modeLevel: new TerraDrawModeUndoRedo({ maxStackSize: 100 }),
sessionLevel: new TerraDrawSessionUndoRedo({ maxStackSize: 100 }),
keyboardShortcuts: new TerraDrawUndoRedoKeyboardShortcuts(),
},
});
draw.start();
draw.on("history", ({ cause, stack, undoSize, redoSize }) => {
// cause: "push" | "undo" | "redo"
// stack: "mode" | "session"
// undoSize / redoSize: current stack sizes
undoButton.disabled = undoSize === 0;
redoButton.disabled = redoSize === 0;
});