| 20 | } |
| 21 | |
| 22 | export function useHistory(options: UseHistoryOptions = {}): UseHistoryReturn { |
| 23 | const { maxHistorySize = 50 } = options; |
| 24 | |
| 25 | // Use refs for history data to avoid unnecessary re-renders |
| 26 | const historyRef = useRef<HistoryState[]>([]); |
| 27 | const currentIndexRef = useRef(-1); |
| 28 | const isUndoRedoRef = useRef(false); |
| 29 | |
| 30 | // Use state for canUndo/canRedo to trigger re-renders |
| 31 | const [canUndo, setCanUndo] = useState(false); |
| 32 | const [canRedo, setCanRedo] = useState(false); |
| 33 | |
| 34 | // Update the button states |
| 35 | const updateButtonStates = useCallback(() => { |
| 36 | setCanUndo(currentIndexRef.current > 0); |
| 37 | setCanRedo(currentIndexRef.current < historyRef.current.length - 1); |
| 38 | }, []); |
| 39 | |
| 40 | // Deep clone state for history |
| 41 | const cloneState = useCallback((nodes: FlowNode[], edges: FlowEdge[]): HistoryState => { |
| 42 | return { |
| 43 | nodes: JSON.parse(JSON.stringify(nodes)), |
| 44 | edges: JSON.parse(JSON.stringify(edges)), |
| 45 | }; |
| 46 | }, []); |
| 47 | |
| 48 | // Compare two states |
| 49 | const statesEqual = useCallback((a: HistoryState, b: HistoryState): boolean => { |
| 50 | return JSON.stringify(a) === JSON.stringify(b); |
| 51 | }, []); |
| 52 | |
| 53 | // Push a new state to history |
| 54 | const pushHistory = useCallback((nodes: FlowNode[], edges: FlowEdge[]) => { |
| 55 | // Skip if this is an undo/redo operation |
| 56 | if (isUndoRedoRef.current) { |
| 57 | return; |
| 58 | } |
| 59 | |
| 60 | const newState = cloneState(nodes, edges); |
| 61 | |
| 62 | // Skip if same as current state |
| 63 | const currentState = historyRef.current[currentIndexRef.current]; |
| 64 | if (currentState && statesEqual(currentState, newState)) { |
| 65 | return; |
| 66 | } |
| 67 | |
| 68 | // If we're not at the end of history, truncate future states |
| 69 | if (currentIndexRef.current < historyRef.current.length - 1) { |
| 70 | historyRef.current = historyRef.current.slice(0, currentIndexRef.current + 1); |
| 71 | } |
| 72 | |
| 73 | // Add new state |
| 74 | historyRef.current.push(newState); |
| 75 | currentIndexRef.current = historyRef.current.length - 1; |
| 76 | |
| 77 | // Limit history size |
| 78 | if (historyRef.current.length > maxHistorySize) { |
| 79 | historyRef.current.shift(); |