use-travel
Version:
A React hook for state time travel with undo, redo, reset and archive functionalities.
85 lines • 2.43 kB
TypeScript
import { type Options as MutativeOptions, type Patches, type Draft, type Immutable } from 'mutative';
type TravelPatches = {
patches: Patches[];
inversePatches: Patches[];
};
type Options<F extends boolean, A extends boolean> = {
/**
* The maximum number of history to keep, by default `10`
*/
maxHistory?: number;
/**
* The initial position in the history, by default `0`
*/
initialPosition?: number;
/**
* The initial patches of the history
*/
initialPatches?: TravelPatches;
/**
* Whether to automatically archive the current state, by default `true`
*/
autoArchive?: A;
} & Omit<MutativeOptions<true, F>, 'enablePatches'>;
type InitialValue<I extends any> = I extends (...args: any) => infer R ? R : I;
type DraftFunction<S> = (draft: Draft<S>) => void;
type Updater<S> = (value: S | (() => S) | DraftFunction<S>) => void;
type Value<S, F extends boolean> = F extends true ? Immutable<InitialValue<S>> : InitialValue<S>;
interface Controls<S, F extends boolean> {
/**
* The current position in the history
*/
position: number;
/**
* Get the history of the state
*/
getHistory: () => Value<S, F>[];
/**
* The patches of the history
*/
patches: TravelPatches;
/**
* Go back in the history
*/
back: (amount?: number) => void;
/**
* Go forward in the history
*/
forward: (amount?: number) => void;
/**
* Reset the history
*/
reset: () => void;
/**
* Go to a specific position in the history
*/
go: (position: number) => void;
/**
* Check if it's possible to go back
*/
canBack: () => boolean;
/**
* Check if it's possible to go forward
*/
canForward: () => boolean;
}
type Result<S, F extends boolean, A extends boolean> = [
Value<S, F>,
Updater<InitialValue<S>>,
A extends false ? Controls<S, F> & {
/**
* Archive the current state
*/
archive: () => void;
/**
* Check if it's possible to archive the current state
*/
canArchive: () => boolean;
} : Controls<S, F>
];
/**
* A hook to travel in the history of a state
*/
export declare const useTravel: <S, F extends boolean, A extends boolean>(initialState: S, _options?: Options<F, A>) => Result<S, F, A>;
export {};
//# sourceMappingURL=index.d.ts.map