55 lines
1.2 KiB
TypeScript
55 lines
1.2 KiB
TypeScript
|
|
'use client';
|
||
|
|
|
||
|
|
import * as React from 'react';
|
||
|
|
import { HistoryManager } from '@/lib/history/history-manager';
|
||
|
|
import type { HistoryState } from '@/lib/history/history-manager';
|
||
|
|
import type { Command } from '@/lib/history/command';
|
||
|
|
|
||
|
|
export interface UseHistoryReturn {
|
||
|
|
execute: (command: Command) => void;
|
||
|
|
undo: () => boolean;
|
||
|
|
redo: () => boolean;
|
||
|
|
clear: () => void;
|
||
|
|
state: HistoryState;
|
||
|
|
}
|
||
|
|
|
||
|
|
export function useHistory(maxHistorySize: number = 50): UseHistoryReturn {
|
||
|
|
const [manager] = React.useState(() => new HistoryManager(maxHistorySize));
|
||
|
|
const [state, setState] = React.useState<HistoryState>(manager.getState());
|
||
|
|
|
||
|
|
React.useEffect(() => {
|
||
|
|
const unsubscribe = manager.subscribe(() => {
|
||
|
|
setState(manager.getState());
|
||
|
|
});
|
||
|
|
|
||
|
|
return unsubscribe;
|
||
|
|
}, [manager]);
|
||
|
|
|
||
|
|
const execute = React.useCallback(
|
||
|
|
(command: Command) => {
|
||
|
|
manager.execute(command);
|
||
|
|
},
|
||
|
|
[manager]
|
||
|
|
);
|
||
|
|
|
||
|
|
const undo = React.useCallback(() => {
|
||
|
|
return manager.undo();
|
||
|
|
}, [manager]);
|
||
|
|
|
||
|
|
const redo = React.useCallback(() => {
|
||
|
|
return manager.redo();
|
||
|
|
}, [manager]);
|
||
|
|
|
||
|
|
const clear = React.useCallback(() => {
|
||
|
|
manager.clear();
|
||
|
|
}, [manager]);
|
||
|
|
|
||
|
|
return {
|
||
|
|
execute,
|
||
|
|
undo,
|
||
|
|
redo,
|
||
|
|
clear,
|
||
|
|
state,
|
||
|
|
};
|
||
|
|
}
|