forked from accordproject/template-playground
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseUndoRedo.ts
More file actions
39 lines (33 loc) · 1.33 KB
/
useUndoRedo.ts
File metadata and controls
39 lines (33 loc) · 1.33 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
import { useState } 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[]>([]);
const setValue = (newValue: T) => {
setPast((prevPast) => [...prevPast, present]);
setPresent(newValue);
setFuture([]);
if (onChange) onChange(newValue); // Update editor state
if (onSync) onSync(newValue); // Sync to main state and rebuild
};
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); // Update editor state
if (onSync) onSync(previous); // Sync to main state and rebuild
};
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); // Update editor state
if (onSync) onSync(next); // Sync to main state and rebuild
};
return { value: present, setValue, undo, redo };
}
export default useUndoRedo;