1 import { useCallback, useState } from "react";
2
3 /**
4 * Base interface for a command that can be managed
5 * by the `useCommandHistory` hook.
6 */
7 export interface Command {
8 execute: () => void;
9 undo: () => void;
10 redo: () => void;
11 }
12
13 /**
14 * Hook to manage a history of commands that can be undone, redone, and executed.
15 */
16 export const useCommandHistory = (maxHistory = 20) => {
17 const [past, setPast] = useState<Command[]>([]);
18 const [future, setFuture] = useState<Command[]>([]);
19
20 const canUndo = past.length > 0;
21 const canRedo = future.length > 0;
22
23 const undo = useCallback(() => {
24 if (!canUndo) {
25 return;
26 }
27
28 const previous = past[past.length - 1];
29 const newPast = past.slice(0, past.length - 1);
30
31 previous.undo();
32
33 setPast(newPast);
34 setFuture([previous, ...future.slice(0, maxHistory - 1)]);
35 }, [canUndo, future, past, maxHistory]);
36
37 const redo = useCallback(() => {
38 if (!canRedo) {
39 return;
40 }
41
42 const next = future[0];
43 const newFuture = future.slice(1);
44
45 next.redo();
46
47 setPast([...past, next].slice(0, maxHistory - 1));
48 setFuture(newFuture);
49 }, [canRedo, future, past, maxHistory]);
50
51 const execute = useCallback(
52 (command: Command) => {
53 command.execute();
54 setPast((past) => [...past, command].slice(0, maxHistory - 1));
55 setFuture([]);
56 },
57 [maxHistory]
58 );
59
60 return {
61 undo,
62 redo,
63 execute,
64 canUndo,
65 canRedo,
66 };
67 };