Skip to content

Commit

Permalink
feat: useHistoryTravel add manual option
Browse files Browse the repository at this point in the history
  • Loading branch information
Debbl committed Aug 2, 2023
1 parent 5b056d0 commit 863e974
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions packages/hooks/src/useHistoryTravel/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,25 @@ const split = <T>(step: number, targetArr: T[]) => {
};
};

export default function useHistoryTravel<T>(initialValue?: T, maxLength: number = 0) {
export default function useHistoryTravel<T>(
initialValue?: T,
options?:
| {
maxLength: number;
manual: boolean;
}
| number,
) {
let maxLength = 0;
let manual = false;

if (typeof options === 'number') {
maxLength = options;
} else if (typeof options === 'object') {
maxLength = options.maxLength;
manual = options.manual;
}

const [history, setHistory] = useState<IData<T | undefined>>({
present: initialValue,
past: [],
Expand Down Expand Up @@ -69,6 +87,14 @@ export default function useHistoryTravel<T>(initialValue?: T, maxLength: number
});
};

const updateValueWithoutRecord = (val: T) => {
setHistory({
present: val,
future: future,
past: past,
});
};

const _forward = (step: number = 1) => {
if (future.length === 0) {
return;
Expand Down Expand Up @@ -109,7 +135,8 @@ export default function useHistoryTravel<T>(initialValue?: T, maxLength: number
value: present,
backLength: past.length,
forwardLength: future.length,
setValue: useMemoizedFn(updateValue),
setValue: manual ? useMemoizedFn(updateValueWithoutRecord) : useMemoizedFn(updateValue),
commit: useMemoizedFn(updateValue),
go: useMemoizedFn(go),
back: useMemoizedFn(() => {
go(-1);
Expand Down

0 comments on commit 863e974

Please sign in to comment.