-
-
Notifications
You must be signed in to change notification settings - Fork 215
Expand file tree
/
Copy pathuseUndoRedo.ts
More file actions
47 lines (40 loc) · 1.37 KB
/
useUndoRedo.ts
File metadata and controls
47 lines (40 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { useState, useEffect } from 'react';
function useUndoRedo<T>(initialValue: T, onChange?: (value: T) => void, onSync?: (value: T) => Promise<void>) {
const [past, setPast] = useState<T[]>([]);
const [present, setPresent] = useState<T>(initialValue);
const [future, setFuture] = useState<T[]>([]);
useEffect(() => {
if (initialValue !== present) {
setPresent(initialValue);
setPast([]);
setFuture([]);
}
}, [initialValue, present]);
const setValue = (newValue: T) => {
setPast((prevPast) => [...prevPast, present]);
setPresent(newValue);
setFuture([]);
if (onChange) onChange(newValue); // Update editor state
if (onSync) void onSync(newValue);
};
const undo = () => {
if (past.length === 0) return;
const previous = past[past.length - 1];
setPast((prevPast) => prevPast.slice(0, -1));
setFuture((prevFuture) => [present, ...prevFuture]);
setPresent(previous);
if (onChange) onChange(previous);
if (onSync) void onSync(previous);
};
const redo = () => {
if (future.length === 0) return;
const next = future[0];
setFuture((prevFuture) => prevFuture.slice(1));
setPast((prevPast) => [...prevPast, present]);
setPresent(next);
if (onChange) onChange(next);
if (onSync) void onSync(next);
};
return { value: present, setValue, undo, redo };
}
export default useUndoRedo;