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
41 lines (35 loc) · 1.17 KB
/
useUndoRedo.ts
File metadata and controls
41 lines (35 loc) · 1.17 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
import { useState,useEffect } from 'react';
function useUndoRedo<T>(initialValue: T, onChange?: (value: T) => void) {
const [past, setPast] = useState<T[]>([]);
const [present, setPresent] = useState<T>(initialValue);
const [future, setFuture] = useState<T[]>([]);
useEffect(() => {
setPresent(initialValue);
setPast([]);
setFuture([]);
}, [initialValue]);
const setValue = (newValue: T) => {
setPast((prevPast) => [...prevPast, present]);
setPresent(newValue);
setFuture([]);
if (onChange) onChange(newValue); // Ensure preview updates
};
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);
};
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);
};
return { value: present, setValue, undo, redo };
}
export default useUndoRedo;