Undo/Redo with Store History
Build a history stack around a writable store to support undo and redo.
History Stack
Wrap a writable store with past/present/future arrays to support undo/redo.
Basic Implementation
Maintain a list of previous states.
function createHistory(initial) {
let past = [], future = [];
const state = writable(initial);
return {
subscribe: state.subscribe,
set(v) { past.push(get(state)); future = []; state.set(v); },
undo() { if (past.length) { future.push(get(state)); state.set(past.pop()); } },
redo() { if (future.length) { past.push(get(state)); state.set(future.pop()); } }
};
}All lessons in this course
- Store Architecture: Feature Modules
- Event Bus Pattern with Stores
- Optimistic UI Updates
- Undo/Redo with Store History