Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

index.ts

659 lines18.4 KB

1// While the public API was clearly inspired by the "history" npm package,
2// This implementation attempts to be more lightweight by
3// making assumptions about the way TanStack Router works
4​
5export interface NavigateOptions {
6 ignoreBlocker?: boolean
7}
8​
9type SubscriberHistoryAction =
10 | {
11 type: Exclude<HistoryAction, 'GO'>
12 }
13 | {
14 type: 'GO'
15 index: number
16 }
17​
18type SubscriberArgs = {
19 location: HistoryLocation
20 action: SubscriberHistoryAction
22​
23export interface RouterHistory {
24 location: HistoryLocation
25 length: number
26 subscribers: Set<(opts: SubscriberArgs) => void>
27 subscribe: (cb: (opts: SubscriberArgs) => void) => () => void
28 push: (path: string, state?: any, navigateOpts?: NavigateOptions) => void
29 replace: (path: string, state?: any, navigateOpts?: NavigateOptions) => void
30 go: (index: number, navigateOpts?: NavigateOptions) => void
31 back: (navigateOpts?: NavigateOptions) => void
32 forward: (navigateOpts?: NavigateOptions) => void
33 canGoBack: () => boolean
34 createHref: (href: string) => string
35 block: (blocker: NavigationBlocker) => () => void
36 flush: () => void
37 destroy: () => void
38 notify: (action: SubscriberHistoryAction) => void
39 _ignoreSubscribers?: boolean
41​
42export interface HistoryLocation extends ParsedPath {
43 state: ParsedHistoryState
45​
46export interface ParsedPath {
47 href: string
48 pathname: string
49 search: string
50 hash: string
52​
53export interface HistoryState {}
54​
55export type ParsedHistoryState = HistoryState & {
56 key?: string // TODO: Remove in v2 - use __TSR_key instead
57 __TSR_key?: string
58 __TSR_index: number
60​
61type ShouldAllowNavigation = any
62​
63export type HistoryAction = 'PUSH' | 'REPLACE' | 'FORWARD' | 'BACK' | 'GO'
64​
65export type BlockerFnArgs = {
66 currentLocation: HistoryLocation
67 nextLocation: HistoryLocation
68 action: HistoryAction
70​
71export type BlockerFn = (
72 args: BlockerFnArgs,
73) => Promise<ShouldAllowNavigation> | ShouldAllowNavigation
74​
75export type NavigationBlocker = {
76 blockerFn: BlockerFn
77 enableBeforeUnload?: (() => boolean) | boolean
79​
80type TryNavigateArgs = {
81 task: () => void
82 type: 'PUSH' | 'REPLACE' | 'BACK' | 'FORWARD' | 'GO'
83 navigateOpts?: NavigateOptions
84} & (
85 | {
86 type: 'PUSH' | 'REPLACE'
87 path: string
88 state: any
89 }
90 | {
91 type: 'BACK' | 'FORWARD' | 'GO'
92 }
94​
95const stateIndexKey = '__TSR_index'
96const popStateEvent = 'popstate'
97const beforeUnloadEvent = 'beforeunload'
98​
99export function createHistory(opts: {
100 getLocation: () => HistoryLocation
101 getLength: () => number
102 pushState: (path: string, state: any) => void
103 replaceState: (path: string, state: any) => void
104 go: (n: number) => void
105 back: (ignoreBlocker: boolean) => void
106 forward: (ignoreBlocker: boolean) => void
107 createHref: (path: string) => string
108 flush?: () => void
109 destroy?: () => void
110 onBlocked?: () => void
111 getBlockers?: () => Array<NavigationBlocker>
112 setBlockers?: (blockers: Array<NavigationBlocker>) => void
113 // Avoid notifying on forward/back/go, used for browser history as we already get notified by the popstate event
114 notifyOnIndexChange?: boolean
115}): RouterHistory {
116 let location = opts.getLocation()
117 const subscribers = new Set<(opts: SubscriberArgs) => void>()
118​
119 const notify = (action: SubscriberHistoryAction) => {
120 location = opts.getLocation()
121 subscribers.forEach((subscriber) => subscriber({ location, action }))
122 }
123​
124 const handleIndexChange = (action: SubscriberHistoryAction) => {
125 if (opts.notifyOnIndexChange ?? true) notify(action)
126 else location = opts.getLocation()
127 }
128​
129 const tryNavigation = async ({
130 task,
131 navigateOpts,
132 ...actionInfo
133 }: TryNavigateArgs) => {
134 const ignoreBlocker = navigateOpts?.ignoreBlocker ?? false
135 if (ignoreBlocker) {
136 task()
137 return
138 }
139​
140 const blockers = opts.getBlockers?.() ?? []
141 const isPushOrReplace =
142 actionInfo.type === 'PUSH' || actionInfo.type === 'REPLACE'
143 if (typeof document !== 'undefined' && blockers.length && isPushOrReplace) {
144 for (const blocker of blockers) {
145 const nextLocation = parseHref(actionInfo.path, actionInfo.state)
146 const isBlocked = await blocker.blockerFn({
147 currentLocation: location,
148 nextLocation,
149 action: actionInfo.type,
150 })
151 if (isBlocked) {
152 opts.onBlocked?.()
153 return
154 }
155 }
156 }
157​
158 task()
159 }
160​
161 return {
162 get location() {
163 return location
164 },
165 get length() {
166 return opts.getLength()
167 },
168 subscribers,
169 subscribe: (cb: (opts: SubscriberArgs) => void) => {
170 subscribers.add(cb)
171​
172 return () => {
173 subscribers.delete(cb)
174 }
175 },
176 push: (path, state, navigateOpts) => {
177 const currentIndex = location.state[stateIndexKey]
178 state = assignKeyAndIndex(currentIndex + 1, state)
179 tryNavigation({
180 task: () => {
181 opts.pushState(path, state)
182 notify({ type: 'PUSH' })
183 },
184 navigateOpts,
185 type: 'PUSH',
186 path,
187 state,
188 })
189 },
190 replace: (path, state, navigateOpts) => {
191 const currentIndex = location.state[stateIndexKey]
192 state = assignKeyAndIndex(currentIndex, state)
193 tryNavigation({
194 task: () => {
195 opts.replaceState(path, state)
196 notify({ type: 'REPLACE' })
197 },
198 navigateOpts,
199 type: 'REPLACE',
200 path,
201 state,
202 })
203 },
204 go: (index, navigateOpts) => {
205 tryNavigation({
206 task: () => {
207 opts.go(index)
208 handleIndexChange({ type: 'GO', index })
209 },
210 navigateOpts,
211 type: 'GO',
212 })
213 },
214 back: (navigateOpts) => {
215 tryNavigation({
216 task: () => {
217 opts.back(navigateOpts?.ignoreBlocker ?? false)
218 handleIndexChange({ type: 'BACK' })
219 },
220 navigateOpts,
221 type: 'BACK',
222 })
223 },
224 forward: (navigateOpts) => {
225 tryNavigation({
226 task: () => {
227 opts.forward(navigateOpts?.ignoreBlocker ?? false)
228 handleIndexChange({ type: 'FORWARD' })
229 },
230 navigateOpts,
231 type: 'FORWARD',
232 })
233 },
234 canGoBack: () => location.state[stateIndexKey] !== 0,
235 createHref: (str) => opts.createHref(str),
236 block: (blocker) => {
237 if (!opts.setBlockers) return () => {}
238 const blockers = opts.getBlockers?.() ?? []
239 opts.setBlockers([...blockers, blocker])
240​
241 return () => {
242 const blockers = opts.getBlockers?.() ?? []
243 opts.setBlockers?.(blockers.filter((b) => b !== blocker))
244 }
245 },
246 flush: () => opts.flush?.(),
247 destroy: () => opts.destroy?.(),
248 notify,
249 }
251​
252function assignKeyAndIndex(index: number, state: HistoryState | undefined) {
253 if (!state) {
254 state = {} as HistoryState
255 }
256 const key = createRandomKey()
257 return {
258 ...state,
259 key, // TODO: Remove in v2 - use __TSR_key instead
260 __TSR_key: key,
261 [stateIndexKey]: index,
262 } as ParsedHistoryState
264​
265/**
266 * Creates a history object that can be used to interact with the browser's
267 * navigation. This is a lightweight API wrapping the browser's native methods.
268 * It is designed to work with TanStack Router, but could be used as a standalone API as well.
269 * IMPORTANT: This API implements history throttling via a microtask to prevent
270 * excessive calls to the history API. In some browsers, calling history.pushState or
271 * history.replaceState in quick succession can cause the browser to ignore subsequent
272 * calls. This API smooths out those differences and ensures that your application
273 * state will *eventually* match the browser state. In most cases, this is not a problem,
274 * but if you need to ensure that the browser state is up to date, you can use the
275 * `history.flush` method to immediately flush all pending state changes to the browser URL.
276 * @param opts
277 * @param opts.getHref A function that returns the current href (path + search + hash)
278 * @param opts.createHref A function that takes a path and returns a href (path + search + hash)
279 * @returns A history instance
280 */
281export function createBrowserHistory(opts?: {
282 parseLocation?: () => HistoryLocation
283 createHref?: (path: string) => string
284 window?: any
285}): RouterHistory {
286 const win =
287 opts?.window ??
288 (typeof document !== 'undefined' ? window : (undefined as any))
289​
290 const originalPushState = win.history.pushState
291 const originalReplaceState = win.history.replaceState
292​
293 let blockers: Array<NavigationBlocker> = []
294 const _getBlockers = () => blockers
295 const _setBlockers = (newBlockers: Array<NavigationBlocker>) =>
296 (blockers = newBlockers)
297​
298 const createHref = opts?.createHref ?? ((path) => path)
299 const parseLocation =
300 opts?.parseLocation ??
301 (() =>
302 parseHref(
303 `${win.location.pathname}${win.location.search}${win.location.hash}`,
304 win.history.state,
305 ))
306​
307 // Ensure there is always a key to start
308 if (!win.history.state?.__TSR_key && !win.history.state?.key) {
309 const addedKey = createRandomKey()
310 win.history.replaceState(
311 {
312 [stateIndexKey]: 0,
313 key: addedKey, // TODO: Remove in v2 - use __TSR_key instead
314 __TSR_key: addedKey,
315 },
316 '',
317 )
318 }
319​
320 let currentLocation = parseLocation()
321 let rollbackLocation: HistoryLocation | undefined
322​
323 let nextPopIsGo = false
324 let ignoreNextPop = false
325 let skipBlockerNextPop = false
326 let ignoreNextBeforeUnload = false
327​
328 const getLocation = () => currentLocation
329​
330 let next:
331 | undefined
332 | {
333 // This is the latest location that we were attempting to push/replace
334 href: string
335 // This is the latest state that we were attempting to push/replace
336 state: any
337 // This is the latest type that we were attempting to push/replace
338 isPush: boolean
339 }
340​
341 // We need to track the current scheduled update to prevent
342 // multiple updates from being scheduled at the same time.
343 let scheduled: Promise<void> | undefined
344​
345 // This function flushes the next update to the browser history
346 const flush = () => {
347 if (!next) {
348 return
349 }
350​
351 // We need to ignore any updates to the subscribers while we update the browser history
352 history._ignoreSubscribers = true
353​
354 // Update the browser history
355 ;(next.isPush ? win.history.pushState : win.history.replaceState)(
356 next.state,
357 '',
358 next.href,
359 )
360​
361 // Stop ignoring subscriber updates
362 history._ignoreSubscribers = false
363​
364 // Reset the nextIsPush flag and clear the scheduled update
365 next = undefined
366 scheduled = undefined
367 rollbackLocation = undefined
368 }
369​
370 // This function queues up a call to update the browser history
371 const queueHistoryAction = (
372 type: 'push' | 'replace',
373 destHref: string,
374 state: any,
375 ) => {
376 const href = createHref(destHref)
377​
378 if (!scheduled) {
379 rollbackLocation = currentLocation
380 }
381​
382 // Update the location in memory
383 currentLocation = parseHref(destHref, state)
384​
385 // Keep track of the next location we need to flush to the URL
386 next = {
387 href,
388 state,
389 isPush: next?.isPush || type === 'push',
390 }
391​
392 if (!scheduled) {
393 // Schedule an update to the browser history
394 scheduled = Promise.resolve().then(() => flush())
395 }
396 }
397​
398 // NOTE: this function can probably be removed
399 const onPushPop = (type: 'PUSH' | 'REPLACE') => {
400 currentLocation = parseLocation()
401 history.notify({ type })
402 }
403​
404 const onPushPopEvent = async () => {
405 if (ignoreNextPop) {
406 ignoreNextPop = false
407 return
408 }
409​
410 const nextLocation = parseLocation()
411 const delta =
412 nextLocation.state[stateIndexKey] - currentLocation.state[stateIndexKey]
413 const isForward = delta === 1
414 const isBack = delta === -1
415 const isGo = (!isForward && !isBack) || nextPopIsGo
416 nextPopIsGo = false
417​
418 const action = isGo ? 'GO' : isBack ? 'BACK' : 'FORWARD'
419 const notify: SubscriberHistoryAction = isGo
420 ? {
421 type: 'GO',
422 index: delta,
423 }
424 : {
425 type: isBack ? 'BACK' : 'FORWARD',
426 }
427​
428 if (skipBlockerNextPop) {
429 skipBlockerNextPop = false
430 } else {
431 const blockers = _getBlockers()
432 if (typeof document !== 'undefined' && blockers.length) {
433 for (const blocker of blockers) {
434 const isBlocked = await blocker.blockerFn({
435 currentLocation,
436 nextLocation,
437 action,
438 })
439 if (isBlocked) {
440 ignoreNextPop = true
441 win.history.go(1)
442 history.notify(notify)
443 return
444 }
445 }
446 }
447 }
448​
449 currentLocation = parseLocation()
450 history.notify(notify)
451 }
452​
453 const onBeforeUnload = (e: BeforeUnloadEvent) => {
454 if (ignoreNextBeforeUnload) {
455 ignoreNextBeforeUnload = false
456 return
457 }
458​
459 let shouldBlock = false
460​
461 // If one blocker has a non-disabled beforeUnload, we should block
462 const blockers = _getBlockers()
463 if (typeof document !== 'undefined' && blockers.length) {
464 for (const blocker of blockers) {
465 const shouldHaveBeforeUnload = blocker.enableBeforeUnload ?? true
466 if (shouldHaveBeforeUnload === true) {
467 shouldBlock = true
468 break
469 }
470​
471 if (
472 typeof shouldHaveBeforeUnload === 'function' &&
473 shouldHaveBeforeUnload() === true
474 ) {
475 shouldBlock = true
476 break
477 }
478 }
479 }
480​
481 if (shouldBlock) {
482 e.preventDefault()
483 return (e.returnValue = '')
484 }
485 return
486 }
487​
488 const history = createHistory({
489 getLocation,
490 getLength: () => win.history.length,
491 pushState: (href, state) => queueHistoryAction('push', href, state),
492 replaceState: (href, state) => queueHistoryAction('replace', href, state),
493 back: (ignoreBlocker) => {
494 if (ignoreBlocker) skipBlockerNextPop = true
495 ignoreNextBeforeUnload = true
496 return win.history.back()
497 },
498 forward: (ignoreBlocker) => {
499 if (ignoreBlocker) skipBlockerNextPop = true
500 ignoreNextBeforeUnload = true
501 win.history.forward()
502 },
503 go: (n) => {
504 nextPopIsGo = true
505 win.history.go(n)
506 },
507 createHref: (href) => createHref(href),
508 flush,
509 destroy: () => {
510 win.history.pushState = originalPushState
511 win.history.replaceState = originalReplaceState
512 win.removeEventListener(beforeUnloadEvent, onBeforeUnload, {
513 capture: true,
514 })
515 win.removeEventListener(popStateEvent, onPushPopEvent)
516 },
517 onBlocked: () => {
518 // If a navigation is blocked, we need to rollback the location
519 // that we optimistically updated in memory.
520 if (rollbackLocation && currentLocation !== rollbackLocation) {
521 currentLocation = rollbackLocation
522 }
523 },
524 getBlockers: _getBlockers,
525 setBlockers: _setBlockers,
526 notifyOnIndexChange: false,
527 })
528​
529 win.addEventListener(beforeUnloadEvent, onBeforeUnload, { capture: true })
530 win.addEventListener(popStateEvent, onPushPopEvent)
531​
532 win.history.pushState = function (...args: Array<any>) {
533 const res = originalPushState.apply(win.history, args as any)
534 if (!history._ignoreSubscribers) onPushPop('PUSH')
535 return res
536 }
537​
538 win.history.replaceState = function (...args: Array<any>) {
539 const res = originalReplaceState.apply(win.history, args as any)
540 if (!history._ignoreSubscribers) onPushPop('REPLACE')
541 return res
542 }
543​
544 return history
546​
547/**
548 * Create a hash-based history implementation.
549 * Useful for static hosts or environments without server URL rewriting.
550 * @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
551 */
552export function createHashHistory(opts?: { window?: any }): RouterHistory {
553 const win =
554 opts?.window ??
555 (typeof document !== 'undefined' ? window : (undefined as any))
556 return createBrowserHistory({
557 window: win,
558 parseLocation: () => {
559 const hashSplit = win.location.hash.split('#').slice(1)
560 const pathPart = hashSplit[0] ?? '/'
561 const searchPart = win.location.search
562 const hashEntries = hashSplit.slice(1)
563 const hashPart =
564 hashEntries.length === 0 ? '' : `#${hashEntries.join('#')}`
565 const hashHref = `${pathPart}${searchPart}${hashPart}`
566 return parseHref(hashHref, win.history.state)
567 },
568 createHref: (href) =>
569 `${win.location.pathname}${win.location.search}#${href}`,
570 })
572​
573/**
574 * Create an in-memory history implementation.
575 * Ideal for server rendering, tests, and non-DOM environments.
576 * @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
577 */
578export function createMemoryHistory(
579 opts: {
580 initialEntries: Array<string>
581 initialIndex?: number
582 } = {
583 initialEntries: ['/'],
584 },
585): RouterHistory {
586 const entries = opts.initialEntries
587 let index = opts.initialIndex
588 ? Math.min(Math.max(opts.initialIndex, 0), entries.length - 1)
589 : entries.length - 1
590 const states = entries.map((_entry, index) =>
591 assignKeyAndIndex(index, undefined),
592 )
593​
594 const getLocation = () => parseHref(entries[index]!, states[index])
595​
596 return createHistory({
597 getLocation,
598 getLength: () => entries.length,
599 pushState: (path, state) => {
600 // Removes all subsequent entries after the current index to start a new branch
601 if (index < entries.length - 1) {
602 entries.splice(index + 1)
603 states.splice(index + 1)
604 }
605 states.push(state)
606 entries.push(path)
607 index = Math.max(entries.length - 1, 0)
608 },
609 replaceState: (path, state) => {
610 states[index] = state
611 entries[index] = path
612 },
613 back: () => {
614 index = Math.max(index - 1, 0)
615 },
616 forward: () => {
617 index = Math.min(index + 1, entries.length - 1)
618 },
619 go: (n) => {
620 index = Math.min(Math.max(index + n, 0), entries.length - 1)
621 },
622 createHref: (path) => path,
623 })
625​
626export function parseHref(
627 href: string,
628 state: ParsedHistoryState | undefined,
629): HistoryLocation {
630 const hashIndex = href.indexOf('#')
631 const searchIndex = href.indexOf('?')
632​
633 const addedKey = createRandomKey()
634​
635 return {
636 href,
637 pathname: href.substring(
638 0,
639 hashIndex > 0
640 ? searchIndex > 0
641 ? Math.min(hashIndex, searchIndex)
642 : hashIndex
643 : searchIndex > 0
644 ? searchIndex
645 : href.length,
646 ),
647 hash: hashIndex > -1 ? href.substring(hashIndex) : '',
648 search:
649 searchIndex > -1
650 ? href.slice(searchIndex, hashIndex === -1 ? undefined : hashIndex)
651 : '',
652 state: state || { [stateIndexKey]: 0, key: addedKey, __TSR_key: addedKey },
653 }
655​
656// Thanks co-pilot!
657function createRandomKey() {
658 return (Math.random() + 1).toString(36).substring(7)