Skip to content

Commit

Permalink
feat(components-react): add skipped state option to the useRedoUndo u…
Browse files Browse the repository at this point in the history
…pdater
  • Loading branch information
gary-Shen committed Oct 30, 2024
1 parent fa9d0e0 commit 701d562
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions packages/components-react/src/hooks/useRedoUndo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export function useRedoUndo<T>(initialValue: T, options: RedoUndoOptions<T>) {
const [currentValue, setCurrentValue] = useState<T>(initialValue);
const pastRef = useRef<T[]>([]);
const futureRef = useRef<T[]>([]);
const skippedHistories = useRef<T[]>([]);
const finalOptions = useMemo<RedoUndoOptions<T>>(() => {
return {
maxHistory: 20,
Expand Down Expand Up @@ -57,6 +58,7 @@ export function useRedoUndo<T>(initialValue: T, options: RedoUndoOptions<T>) {
const reset = useCallback(() => {
pastRef.current = [];
futureRef.current = [];
skippedHistories.current = [];
}, []);

useEffect(() => {
Expand All @@ -65,12 +67,19 @@ export function useRedoUndo<T>(initialValue: T, options: RedoUndoOptions<T>) {
}, [initialValue, reset]);

const update = useCallback(
(value: React.SetStateAction<T | undefined>) => {
(value: React.SetStateAction<T | undefined>, skip: boolean = false) => {
setCurrentValue((pre) => {
const newValue = typeof value === 'function' ? (value as Function)(pre) : value;

if (skip) {
skippedHistories.current.push(newValue);
}

if (pre) {
pastRef.current = [...pastRef.current, pre].slice(-finalOptions.maxHistory!);
// skip 来跳过不需要记录的历史
pastRef.current = [...pastRef.current, pre]
.filter((state) => !skippedHistories.current.includes(state))
.slice(-finalOptions.maxHistory!);
}

return newValue;
Expand Down

0 comments on commit 701d562

Please sign in to comment.