diff --git a/packages/history/src/index.ts b/packages/history/src/index.ts index 852d90be1f9..72b2e6aec95 100644 --- a/packages/history/src/index.ts +++ b/packages/history/src/index.ts @@ -7,6 +7,7 @@ export interface NavigateOptions { } export interface RouterHistory { location: HistoryLocation + length: number subscribers: Set<() => void> subscribe: (cb: () => void) => () => void push: (path: string, state?: any, navigateOpts?: NavigateOptions) => void @@ -61,6 +62,7 @@ const stopBlocking = () => { export function createHistory(opts: { getLocation: () => HistoryLocation + getLength: () => number pushState: (path: string, state: any) => void replaceState: (path: string, state: any) => void go: (n: number) => void @@ -102,6 +104,9 @@ export function createHistory(opts: { get location() { return location }, + get length() { + return opts.getLength() + }, subscribers, subscribe: (cb: () => void) => { subscribers.add(cb) @@ -293,6 +298,7 @@ export function createBrowserHistory(opts?: { const history = createHistory({ getLocation, + getLength: () => win.history.length, pushState: (href, state) => queueHistoryAction('push', href, state), replaceState: (href, state) => queueHistoryAction('replace', href, state), back: () => win.history.back(), @@ -368,7 +374,7 @@ export function createMemoryHistory( return createHistory({ getLocation, - + getLength: () => entries.length, pushState: (path, state) => { currentState = state // Removes all subsequent entries after the current index to start a new branch diff --git a/packages/history/tests/createMemoryHistory.test.ts b/packages/history/tests/createMemoryHistory.test.ts index d4d2326f70c..aae09a9bf38 100644 --- a/packages/history/tests/createMemoryHistory.test.ts +++ b/packages/history/tests/createMemoryHistory.test.ts @@ -51,4 +51,17 @@ describe('createMemoryHistory', () => { history.back() expect(history.location.pathname).toBe('/b') }) + + test('length', () => { + const history = createMemoryHistory() + expect(history.length).toBe(1) + history.push('/a') + expect(history.length).toBe(2) + history.replace('/b') + expect(history.length).toBe(2) + history.back() + expect(history.length).toBe(2) + history.push('/c') + expect(history.length).toBe(2) + }) })