|
| 1 | +import produce from "immer"; |
| 2 | +import { ActionType, HistoryAction } from "core/actions"; |
| 3 | +import { EditorState, HistoryEntry, HistoryState } from "core/states"; |
| 4 | +import { editorReducer } from "../editor-reducer"; |
| 5 | + |
| 6 | +export function historyReducer(state: HistoryState, action: HistoryAction) { |
| 7 | + const currentState = state.present; |
| 8 | + switch (action.type) { |
| 9 | + case "undo": |
| 10 | + if (state.past.length === 0) { |
| 11 | + return state; |
| 12 | + } else { |
| 13 | + return produce(state, (draft) => { |
| 14 | + const nextPresent = draft.past.pop(); |
| 15 | + if (nextPresent) { |
| 16 | + draft.future.unshift( |
| 17 | + createHistoryEntry(nextPresent.actionType, currentState) |
| 18 | + ); |
| 19 | + draft.present = nextPresent.state; |
| 20 | + } |
| 21 | + }); |
| 22 | + } |
| 23 | + case "redo": |
| 24 | + if (state.future.length === 0) { |
| 25 | + return state; |
| 26 | + } else { |
| 27 | + return produce(state, (draft) => { |
| 28 | + const nextPresent = draft.future.shift(); |
| 29 | + if (nextPresent) { |
| 30 | + draft.past.push( |
| 31 | + createHistoryEntry(nextPresent.actionType, currentState) |
| 32 | + ); |
| 33 | + draft.present = nextPresent.state; |
| 34 | + } |
| 35 | + }); |
| 36 | + } |
| 37 | + default: |
| 38 | + const nextState = editorReducer(currentState, action); |
| 39 | + const mergableEntry = getMergableHistoryEntry(state, action[0]); |
| 40 | + |
| 41 | + return produce(state, (draft) => { |
| 42 | + const historyEntry = createHistoryEntry(action[0], { |
| 43 | + ...currentState, |
| 44 | + }); |
| 45 | + |
| 46 | + if (mergableEntry) { |
| 47 | + draft.past[draft.past.length - 1] = { |
| 48 | + ...historyEntry, |
| 49 | + state: mergableEntry.state, |
| 50 | + }; |
| 51 | + } else { |
| 52 | + draft.past.push(historyEntry); |
| 53 | + } |
| 54 | + draft.future = []; |
| 55 | + draft.present = nextState; |
| 56 | + }); |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +function createHistoryEntry( |
| 61 | + actionType: ActionType, |
| 62 | + state: EditorState |
| 63 | +): HistoryEntry { |
| 64 | + return { |
| 65 | + actionType, |
| 66 | + state, |
| 67 | + timestamp: Date.now(), |
| 68 | + }; |
| 69 | +} |
| 70 | + |
| 71 | +const CHANGE_DIFF_DURATION_MS = 300; |
| 72 | + |
| 73 | +function getMergableHistoryEntry( |
| 74 | + state: HistoryState, |
| 75 | + actionType: ActionType |
| 76 | +): HistoryEntry | undefined { |
| 77 | + if (state.past.length === 0) { |
| 78 | + return; |
| 79 | + } |
| 80 | + |
| 81 | + const newTimestamp = Date.now(); |
| 82 | + const previousEntry = state.past[state.past.length - 1]; |
| 83 | + |
| 84 | + if ( |
| 85 | + actionType !== previousEntry.actionType || |
| 86 | + newTimestamp - previousEntry.timestamp > CHANGE_DIFF_DURATION_MS |
| 87 | + ) { |
| 88 | + return; |
| 89 | + } |
| 90 | + |
| 91 | + return previousEntry; |
| 92 | +} |
0 commit comments