import { Section } from '../types' const MAX_HISTORY = 50 export interface UndoRedoState { past: Section[][] present: Section[] future: Section[][] } export function createUndoRedoState(initial: Section[]): UndoRedoState { return { past: [], present: initial, future: [], } } export function pushState(state: UndoRedoState, next: Section[]): UndoRedoState { const past = [...state.past, state.present] if (past.length > MAX_HISTORY) { past.shift() } return { past, present: next, future: [], } } export function undo(state: UndoRedoState): UndoRedoState { if (state.past.length === 0) return state const previous = state.past[state.past.length - 1] const newPast = state.past.slice(0, -1) return { past: newPast, present: previous, future: [state.present, ...state.future], } } export function redo(state: UndoRedoState): UndoRedoState { if (state.future.length === 0) return state const next = state.future[0] const newFuture = state.future.slice(1) return { past: [...state.past, state.present], present: next, future: newFuture, } } export function canUndo(state: UndoRedoState): boolean { return state.past.length > 0 } export function canRedo(state: UndoRedoState): boolean { return state.future.length > 0 }