feat(history): add undo redo stack
This commit is contained in:
42
commands/history.ts
Normal file
42
commands/history.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import type { Command } from "./command";
|
||||
import { commandIds } from "./ids";
|
||||
|
||||
export const historyUndoCommand: Command = {
|
||||
id: commandIds.historyUndo,
|
||||
name: "Undo",
|
||||
execute({ state }) {
|
||||
const previous = state.history.past.at(-1);
|
||||
if (!previous) return state;
|
||||
|
||||
return {
|
||||
...state,
|
||||
document: previous.document,
|
||||
editor: previous.editor,
|
||||
history: {
|
||||
past: state.history.past.slice(0, -1),
|
||||
future: [{ document: state.document, editor: state.editor }, ...state.history.future],
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export const historyRedoCommand: Command = {
|
||||
id: commandIds.historyRedo,
|
||||
name: "Redo",
|
||||
execute({ state }) {
|
||||
const next = state.history.future[0];
|
||||
if (!next) return state;
|
||||
|
||||
return {
|
||||
...state,
|
||||
document: next.document,
|
||||
editor: next.editor,
|
||||
history: {
|
||||
past: [...state.history.past, { document: state.document, editor: state.editor }],
|
||||
future: state.history.future.slice(1),
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export const historyCommands = [historyUndoCommand, historyRedoCommand] satisfies Command<unknown>[];
|
||||
Reference in New Issue
Block a user