Skip to content

Commit 9b2400b

Browse files
matthiasschwarzautofix-ci[bot]SeanCassiere
authored
feat(history): expose length in RouterHistory (#2440)
* feat(history): expose length in `RouterHistory` * ci: apply automated fixes --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> Co-authored-by: Sean Cassiere <33615041+SeanCassiere@users.noreply.github.com>
1 parent fcbc2f8 commit 9b2400b

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

packages/history/src/index.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ export interface NavigateOptions {
77
}
88
export interface RouterHistory {
99
location: HistoryLocation
10+
length: number
1011
subscribers: Set<() => void>
1112
subscribe: (cb: () => void) => () => void
1213
push: (path: string, state?: any, navigateOpts?: NavigateOptions) => void
@@ -61,6 +62,7 @@ const stopBlocking = () => {
6162

6263
export function createHistory(opts: {
6364
getLocation: () => HistoryLocation
65+
getLength: () => number
6466
pushState: (path: string, state: any) => void
6567
replaceState: (path: string, state: any) => void
6668
go: (n: number) => void
@@ -102,6 +104,9 @@ export function createHistory(opts: {
102104
get location() {
103105
return location
104106
},
107+
get length() {
108+
return opts.getLength()
109+
},
105110
subscribers,
106111
subscribe: (cb: () => void) => {
107112
subscribers.add(cb)
@@ -293,6 +298,7 @@ export function createBrowserHistory(opts?: {
293298

294299
const history = createHistory({
295300
getLocation,
301+
getLength: () => win.history.length,
296302
pushState: (href, state) => queueHistoryAction('push', href, state),
297303
replaceState: (href, state) => queueHistoryAction('replace', href, state),
298304
back: () => win.history.back(),
@@ -368,7 +374,7 @@ export function createMemoryHistory(
368374

369375
return createHistory({
370376
getLocation,
371-
377+
getLength: () => entries.length,
372378
pushState: (path, state) => {
373379
currentState = state
374380
// Removes all subsequent entries after the current index to start a new branch

packages/history/tests/createMemoryHistory.test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,4 +51,17 @@ describe('createMemoryHistory', () => {
5151
history.back()
5252
expect(history.location.pathname).toBe('/b')
5353
})
54+
55+
test('length', () => {
56+
const history = createMemoryHistory()
57+
expect(history.length).toBe(1)
58+
history.push('/a')
59+
expect(history.length).toBe(2)
60+
history.replace('/b')
61+
expect(history.length).toBe(2)
62+
history.back()
63+
expect(history.length).toBe(2)
64+
history.push('/c')
65+
expect(history.length).toBe(2)
66+
})
5467
})

0 commit comments

Comments
 (0)