From e08765dacd8b3f2dcd5854b48875c0f09f0b5513 Mon Sep 17 00:00:00 2001 From: unadlib Date: Tue, 19 Mar 2024 00:20:51 +0800 Subject: [PATCH] fix(history): fix getHistory issue --- src/index.ts | 10 +++----- test/index.test.ts | 64 ++++++++++++++++++++++++++++++++++++++++------ 2 files changed, 60 insertions(+), 14 deletions(-) diff --git a/src/index.ts b/src/index.ts index 5d87fa8..ae33956 100644 --- a/src/index.ts +++ b/src/index.ts @@ -144,21 +144,19 @@ export const useTravel = ( currentState as object, allPatches.patches[i] ) as S; + console.log('i', i, JSON.stringify(currentState)); history.push(currentState); } currentState = state as any; - const inversePatches = allPatches.inversePatches; - const stateIndex = - inversePatches.length === cachedPosition - ? inversePatches.length - 1 - : inversePatches.length - cachedPosition - 1; - for (let i = stateIndex; i > -1; i--) { + for (let i = cachedPosition - 1; i > -1; i--) { currentState = apply( currentState as object, allPatches.inversePatches[i] ) as S; + console.log('j', i, JSON.stringify(currentState)); history.unshift(currentState); } + console.log('history', JSON.stringify(history)); return history; }, patches: allPatches, diff --git a/test/index.test.ts b/test/index.test.ts index f514567..49bf050 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -130,13 +130,13 @@ describe('useTravel', () => { [nextState, setState, controls] = result.current; act(() => - setState((draft) => { - draft.todos.push({ - name: 'todo 5', - }); - }) - ); - [nextState, setState, controls] = result.current; + setState((draft) => { + draft.todos.push({ + name: 'todo 5', + }); + }) + ); + [nextState, setState, controls] = result.current; expect(nextState).toEqual({ todos: [ @@ -154,7 +154,55 @@ describe('useTravel', () => { }, ], }); - console.log(controls.patches.patches.length, 'CCCC'); + + expect(controls.getHistory()).toEqual([ + { + todos: [], + }, + { + todos: [ + { + name: 'todo 1', + }, + { + name: 'todo 2', + }, + ], + }, + { + todos: [ + { + name: 'todo 1', + }, + { + name: 'todo 2', + }, + { + name: 'todo 4', + }, + ], + }, + { + todos: [ + { + name: 'todo 1', + }, + { + name: 'todo 2', + }, + { + name: 'todo 4', + }, + { + name: 'todo 5', + }, + ], + }, + ]); + + act(() => controls.go(1)); + [nextState, setState, controls] = result.current; + expect(controls.getHistory()).toEqual([ { todos: [],