Open History to see the last commit
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
21}
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 _getBlockers: () => Array<NavigationBlocker>
40 _ignoreSubscribers?: boolean
41 _ignoreNextBeforeUnload?: (href: string) => void
42}
43β
44export interface HistoryLocation extends ParsedPath {
45 state: ParsedHistoryState
46}
47β
48export interface ParsedPath {
49 href: string
50 pathname: string
51 search: string
52 hash: string
53}
54β
55export interface HistoryState {}
56β
57export type ParsedHistoryState = HistoryState & {
58 key?: string // TODO: Remove in v2 - use __TSR_key instead
59 __TSR_key?: string
60 __TSR_index: number
61}
62β
63type ShouldAllowNavigation = any
64β
65export type HistoryAction = 'PUSH' | 'REPLACE' | 'FORWARD' | 'BACK' | 'GO'
66β
67export type BlockerFnArgs = {
68 currentLocation: HistoryLocation
69 nextLocation: HistoryLocation
70 action: HistoryAction
71}
72β
73export type BlockerFn = (
74 args: BlockerFnArgs,
75) => Promise<ShouldAllowNavigation> | ShouldAllowNavigation
76β
77export type NavigationBlocker = {
78 blockerFn: BlockerFn
79 enableBeforeUnload?: (() => boolean) | boolean
80}
81β
82type TryNavigateArgs = {
83 task: () => void
84 type: 'PUSH' | 'REPLACE' | 'BACK' | 'FORWARD' | 'GO'
85 navigateOpts?: NavigateOptions
86} & (
87 | {
88 type: 'PUSH' | 'REPLACE'
89 path: string
90 state: any
91 }
92 | {
93 type: 'BACK' | 'FORWARD' | 'GO'
94 }
95)
96β
97const stateIndexKey = '__TSR_index'
98const popStateEvent = 'popstate'
99const beforeUnloadEvent = 'beforeunload'
100β
101/**
102 * Turn protocol-relative inputs such as "//evil.example" into paths
103 * such as "/evil.example", keeping navigation on the current origin.
104 *
105 * For HTTP(S) URLs, WHATWG parsing ignores leading C0 controls and spaces,
106 * removes tabs/newlines, and treats backslashes as slashes, so inputs like
107 * "/\evil.example" also need normalization. This only allocates when those
108 * rules would make the input protocol-relative.
109 */
110// eslint-disable-next-line no-control-regex
111const protocolRelativePrefix = /^[\x00-\x20]*(?:[\\/][\t\n\r]*){2,}/
112β
113export function normalizeProtocolRelative(url: string): string {
114 const match = protocolRelativePrefix.exec(url)
115 return match ? '/' + url.slice(match[0].length) : url
116}
117β
118function normalizeHref(href: string): string {
119 // eslint-disable-next-line no-control-regex
120 if (/[\x00-\x1f\x7f]/.test(href)) {
121 // eslint-disable-next-line no-control-regex
122 href = href.replace(/[\x00-\x1f\x7f]/g, (character) =>
123 '\t\n\r'.includes(character) ? '' : encodeURIComponent(character),
124 )
125 }
126 return normalizeProtocolRelative(href)
127}
128β
129export function createHistory(opts: {
130 getLocation: () => HistoryLocation
131 getLength: () => number
132 pushState: (path: string, state: any) => void
133 replaceState: (path: string, state: any) => void
134 go: (n: number, ignoreBlocker: boolean) => void
135 back: (ignoreBlocker: boolean) => void
136 forward: (ignoreBlocker: boolean) => void
137 createHref: (path: string) => string
138 flush?: () => void
139 destroy?: () => void
140 onBlocked?: () => void
141 getBlockers?: () => Array<NavigationBlocker>
142 setBlockers?: (blockers: Array<NavigationBlocker>) => void
143 // Avoid notifying on forward/back/go, used for browser history as we already get notified by the popstate event
144 notifyOnIndexChange?: boolean
145}): RouterHistory {
146 let location = opts.getLocation()
147 const subscribers = new Set<(opts: SubscriberArgs) => void>()
148β
149 const notify = (action: SubscriberHistoryAction) => {
150 location = opts.getLocation()
151 subscribers.forEach((subscriber) => subscriber({ location, action }))
152 }
153β
154 const handleIndexChange = (action: SubscriberHistoryAction) => {
155 if (opts.notifyOnIndexChange ?? true) notify(action)
156 else location = opts.getLocation()
157 }
158β
159 const tryNavigation = async (args: TryNavigateArgs) => {
160 const blockers = args.navigateOpts?.ignoreBlocker
161 ? undefined
162 : opts.getBlockers?.()
163 if (
164 typeof document !== 'undefined' &&
165 blockers?.length &&
166 (args.type === 'PUSH' || args.type === 'REPLACE')
167 ) {
168 for (const blocker of blockers) {
169 const nextLocation = parseHref(args.path, args.state)
170 const isBlocked = await blocker.blockerFn({
171 currentLocation: location,
172 nextLocation,
173 action: args.type,
174 })
175 if (isBlocked) {
176 opts.onBlocked?.()
177 return
178 }
179 }
180 }
181β
182 args.task()
183 }
184β
185 return {
186 get location() {
187 return location
188 },
189 get length() {
190 return opts.getLength()
191 },
192 subscribers,
193 subscribe: (cb: (opts: SubscriberArgs) => void) => {
194 subscribers.add(cb)
195β
196 return () => {
197 subscribers.delete(cb)
198 }
199 },
200 push: (path, state, navigateOpts) => {
201 const currentIndex = location.state[stateIndexKey]
202 state = assignKeyAndIndex(currentIndex + 1, state)
203 tryNavigation({
204 task: () => {
205 opts.pushState(path, state)
206 notify({ type: 'PUSH' })
207 },
208 navigateOpts,
209 type: 'PUSH',
210 path,
211 state,
212 })
213 },
214 replace: (path, state, navigateOpts) => {
215 const currentIndex = location.state[stateIndexKey]
216 state = assignKeyAndIndex(currentIndex, state)
217 tryNavigation({
218 task: () => {
219 opts.replaceState(path, state)
220 notify({ type: 'REPLACE' })
221 },
222 navigateOpts,
223 type: 'REPLACE',
224 path,
225 state,
226 })
227 },
228 go: (index, navigateOpts) => {
229 tryNavigation({
230 task: () => {
231 opts.go(index, navigateOpts?.ignoreBlocker ?? false)
232 handleIndexChange({ type: 'GO', index })
233 },
234 navigateOpts,
235 type: 'GO',
236 })
237 },
238 back: (navigateOpts) => {
239 tryNavigation({
240 task: () => {
241 opts.back(navigateOpts?.ignoreBlocker ?? false)
242 handleIndexChange({ type: 'BACK' })
243 },
244 navigateOpts,
245 type: 'BACK',
246 })
247 },
248 forward: (navigateOpts) => {
249 tryNavigation({
250 task: () => {
251 opts.forward(navigateOpts?.ignoreBlocker ?? false)
252 handleIndexChange({ type: 'FORWARD' })
253 },
254 navigateOpts,
255 type: 'FORWARD',
256 })
257 },
258 canGoBack: () => location.state[stateIndexKey] !== 0,
259 createHref: (str) => opts.createHref(str),
260 block: (blocker) => {
261 if (!opts.setBlockers) return () => {}
262 const blockers = opts.getBlockers?.() ?? []
263 opts.setBlockers([...blockers, blocker])
264β
265 return () => {
266 const blockers = opts.getBlockers?.() ?? []
267 opts.setBlockers?.(blockers.filter((b) => b !== blocker))
268 }
269 },
270 flush: () => opts.flush?.(),
271 destroy: () => opts.destroy?.(),
272 notify,
273 _getBlockers: () => opts.getBlockers?.() ?? [],
274 }
275}
276β
277function assignKeyAndIndex(index: number, state: HistoryState | undefined) {
278 const key = createRandomKey()
279 return {
280 ...state,
281 key, // TODO: Remove in v2 - use __TSR_key instead
282 __TSR_key: key,
283 [stateIndexKey]: index,
284 } as ParsedHistoryState
285}
286β
287/**
288 * Creates a history object that can be used to interact with the browser's
289 * navigation. This is a lightweight API wrapping the browser's native methods.
290 * It is designed to work with TanStack Router, but could be used as a standalone API as well.
291 * IMPORTANT: This API implements history throttling via a microtask to prevent
292 * excessive calls to the history API. In some browsers, calling history.pushState or
293 * history.replaceState in quick succession can cause the browser to ignore subsequent
294 * calls. This API smooths out those differences and ensures that your application
295 * state will *eventually* match the browser state. In most cases, this is not a problem,
296 * but if you need to ensure that the browser state is up to date, you can use the
297 * `history.flush` method to immediately flush all pending state changes to the browser URL.
298 * @param opts
299 * @param opts.getHref A function that returns the current href (path + search + hash)
300 * @param opts.createHref A function that takes a path and returns a href (path + search + hash)
301 * @returns A history instance
302 */
303export function createBrowserHistory(opts?: {
304 parseLocation?: () => HistoryLocation
305 createHref?: (path: string) => string
306 window?: any
307}): RouterHistory {
308 const win =
309 opts?.window ??
310 (typeof document !== 'undefined' ? window : (undefined as any))
311β
312 const originalPushState = win.history.pushState
313 const originalReplaceState = win.history.replaceState
314β
315 let blockers: Array<NavigationBlocker> = []
316 const _getBlockers = () => blockers
317 const _setBlockers = (newBlockers: Array<NavigationBlocker>) =>
318 (blockers = newBlockers)
319β
320 const createHref = (path: string) =>
321 normalizeHref(opts?.createHref ? opts.createHref(path) : path)
322 const parseLocation =
323 opts?.parseLocation ??
324 (() =>
325 parseHref(
326 `${win.location.pathname}${win.location.search}${win.location.hash}`,
327 win.history.state,
328 ))
329β
330 // Ensure there is always a key to start
331 if (!win.history.state?.__TSR_key && !win.history.state?.key) {
332 const addedKey = createRandomKey()
333 win.history.replaceState(
334 {
335 [stateIndexKey]: 0,
336 key: addedKey, // TODO: Remove in v2 - use __TSR_key instead
337 __TSR_key: addedKey,
338 },
339 '',
340 )
341 }
342β
343 let currentLocation = parseLocation()
344 let rollbackLocation: HistoryLocation | undefined
345β
346 let nextPopIsGo = false
347 let ignoreNextPop = false
348 // TODO: An ignored traversal past a history boundary emits neither popstate
349 // nor beforeunload, leaving these bypasses active for a later navigation.
350 // The History API provides no completion signal for such no-op traversals.
351 let skipBlockerNextPop = false
352 let ignoreNextBeforeUnload = false
353β
354 const getLocation = () => currentLocation
355β
356 let next:
357 | undefined
358 | [
359 // The latest location that we were attempting to push/replace
360 href: string,
361 // The latest state that we were attempting to push/replace
362 state: any,
363 // Whether any queued update needs to push rather than replace
364 isPush: boolean,
365 ]
366β
367 // This function flushes the next update to the browser history
368 const flush = () => {
369 if (!next) {
370 return
371 }
372β
373 // We need to ignore any updates to the subscribers while we update the browser history
374 history._ignoreSubscribers = true
375β
376 // Update the browser history
377 ;(next[2 /* is push */] ? win.history.pushState : win.history.replaceState)(
378 next[1 /* state */],
379 '',
380 next[0 /* href */],
381 )
382β
383 // Stop ignoring subscriber updates
384 history._ignoreSubscribers = false
385β
386 // Clear the queued action after it reaches browser history.
387 next = undefined
388 rollbackLocation = undefined
389 }
390β
391 // This function queues up a call to update the browser history
392 const queueHistoryAction = (
393 isPush: boolean,
394 destHref: string,
395 state: any,
396 ) => {
397 // A formatter changes the URL space and must receive the original input.
398 // Otherwise parseHref below already produces the browser destination.
399 const href = opts?.createHref ? createHref(destHref) : undefined
400 const hasPendingAction = !!next
401β
402 if (!hasPendingAction) {
403 rollbackLocation = currentLocation
404 }
405β
406 // Keep the optimistic location in the router's logical URL space.
407 currentLocation = parseHref(destHref, state)
408β
409 // Keep track of the next location we need to flush to the URL
410 next = [
411 href ?? currentLocation.href,
412 state,
413 next?.[2 /* is push */] || isPush,
414 ]
415β
416 if (!hasPendingAction) {
417 // Schedule an update to the browser history
418 queueMicrotask(() => flush())
419 }
420 }
421β
422 // NOTE: this function can probably be removed
423 const onPushPop = (type: 'PUSH' | 'REPLACE') => {
424 currentLocation = parseLocation()
425 history.notify({ type })
426 }
427β
428 const onPushPopEvent = async () => {
429 // Same-document traversals do not fire beforeunload, so consume their
430 // exemption here instead of carrying it into a later document navigation.
431 ignoreNextBeforeUnload = false
432β
433 if (ignoreNextPop) {
434 ignoreNextPop = false
435 return
436 }
437β
438 const nextLocation = parseLocation()
439 const delta =
440 nextLocation.state[stateIndexKey] - currentLocation.state[stateIndexKey]
441 const isForward = delta === 1
442 const isBack = delta === -1
443 const isGo = (!isForward && !isBack) || nextPopIsGo
444 nextPopIsGo = false
445β
446 const action = isGo ? 'GO' : isBack ? 'BACK' : 'FORWARD'
447 const notify: SubscriberHistoryAction = isGo
448 ? {
449 type: 'GO',
450 index: delta,
451 }
452 : {
453 type: isBack ? 'BACK' : 'FORWARD',
454 }
455β
456 if (skipBlockerNextPop) {
457 skipBlockerNextPop = false
458 } else {
459 const blockers = _getBlockers()
460 if (typeof document !== 'undefined' && blockers.length) {
461 for (const blocker of blockers) {
462 const isBlocked = await blocker.blockerFn({
463 currentLocation,
464 nextLocation,
465 action,
466 })
467 if (isBlocked) {
468 ignoreNextPop = true
469 win.history.go(-delta)
470 history.notify(notify)
471 return
472 }
473 }
474 }
475 }
476β
477 currentLocation = parseLocation()
478 history.notify(notify)
479 }
480β
481 const onBeforeUnload = (e: BeforeUnloadEvent) => {
482 if (ignoreNextBeforeUnload) {
483 ignoreNextBeforeUnload = false
484 return
485 }
486β
487 let shouldBlock = false
488β
489 // If one blocker has a non-disabled beforeUnload, we should block
490 const blockers = _getBlockers()
491 if (typeof document !== 'undefined' && blockers.length) {
492 for (const blocker of blockers) {
493 const shouldHaveBeforeUnload = blocker.enableBeforeUnload ?? true
494 if (shouldHaveBeforeUnload === true) {
495 shouldBlock = true
496 break
497 }
498β
499 if (
500 typeof shouldHaveBeforeUnload === 'function' &&
501 shouldHaveBeforeUnload() === true
502 ) {
503 shouldBlock = true
504 break
505 }
506 }
507 }
508β
509 if (shouldBlock) {
510 e.preventDefault()
511 return (e.returnValue = '')
512 }
513 return
514 }
515β
516 const history = createHistory({
517 getLocation,
518 getLength: () => win.history.length,
519 pushState: (href, state) => queueHistoryAction(true, href, state),
520 replaceState: (href, state) => queueHistoryAction(false, href, state),
521 back: (ignoreBlocker) => {
522 if (ignoreBlocker) {
523 skipBlockerNextPop = true
524 ignoreNextBeforeUnload = true
525 }
526 return win.history.back()
527 },
528 forward: (ignoreBlocker) => {
529 if (ignoreBlocker) {
530 skipBlockerNextPop = true
531 ignoreNextBeforeUnload = true
532 }
533 win.history.forward()
534 },
535 go: (n, ignoreBlocker) => {
536 nextPopIsGo = true
537 if (ignoreBlocker) {
538 skipBlockerNextPop = true
539 ignoreNextBeforeUnload = true
540 }
541 win.history.go(n)
542 },
543 createHref,
544 flush,
545 destroy: () => {
546 win.history.pushState = originalPushState
547 win.history.replaceState = originalReplaceState
548 win.removeEventListener(beforeUnloadEvent, onBeforeUnload, {
549 capture: true,
550 })
551 win.removeEventListener(popStateEvent, onPushPopEvent)
552 },
553 onBlocked: () => {
554 // If a navigation is blocked, we need to rollback the location
555 // that we optimistically updated in memory.
556 if (rollbackLocation && currentLocation !== rollbackLocation) {
557 currentLocation = rollbackLocation
558 }
559 },
560 getBlockers: _getBlockers,
561 setBlockers: _setBlockers,
562 notifyOnIndexChange: false,
563 })
564β
565 history._ignoreNextBeforeUnload = (href) => {
566 ignoreNextBeforeUnload = false
567 try {
568 href = new URL(href, win.document.baseURI).href
569 // External handlers and same-document fragments may emit neither
570 // beforeunload nor popstate, leaving an exemption for a later departure.
571 ignoreNextBeforeUnload =
572 /^https?:/.test(href) &&
573 (!href.includes('#') ||
574 href.split('#')[0] !== win.location.href.split('#')[0])
575 } catch {
576 // Invalid URLs cannot unload the document.
577 }
578 }
579β
580 win.addEventListener(beforeUnloadEvent, onBeforeUnload, { capture: true })
581 win.addEventListener(popStateEvent, onPushPopEvent)
582β
583 win.history.pushState = function (...args: Array<any>) {
584 const res = originalPushState.apply(win.history, args as any)
585 if (!history._ignoreSubscribers) onPushPop('PUSH')
586 return res
587 }
588β
589 win.history.replaceState = function (...args: Array<any>) {
590 const res = originalReplaceState.apply(win.history, args as any)
591 if (!history._ignoreSubscribers) onPushPop('REPLACE')
592 return res
593 }
594β
595 return history
596}
597β
598/**
599 * Create a hash-based history implementation.
600 * Useful for static hosts or environments without server URL rewriting.
601 * @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
602 */
603export function createHashHistory(opts?: { window?: any }): RouterHistory {
604 const win =
605 opts?.window ??
606 (typeof document !== 'undefined' ? window : (undefined as any))
607 return createBrowserHistory({
608 window: win,
609 parseLocation: () => {
610 // `#/path?query#fragment`: the router's own fragment starts at the
611 // second '#'. A non-empty `location.hash` always starts with '#'.
612 const hash = win.location.hash
613 let hashIndex = hash.indexOf('#', 1)
614 if (hashIndex < 0) {
615 hashIndex = hash.length
616 }
617 return parseHref(
618 `${hash ? hash.slice(1, hashIndex) : '/'}${win.location.search}${hash.slice(hashIndex)}`,
619 win.history.state,
620 )
621 },
622 createHref: (href) =>
623 `${win.location.pathname}${win.location.search}#${href}`,
624 })
625}
626β
627/**
628 * Create an in-memory history implementation.
629 * Ideal for server rendering, tests, and non-DOM environments.
630 * @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
631 */
632export function createMemoryHistory(
633 opts: {
634 initialEntries: Array<string>
635 initialIndex?: number
636 } = {
637 initialEntries: ['/'],
638 },
639): RouterHistory {
640 const entries = opts.initialEntries
641 let index = opts.initialIndex
642 ? Math.min(Math.max(opts.initialIndex, 0), entries.length - 1)
643 : entries.length - 1
644 const states = entries.map((_entry, index) =>
645 assignKeyAndIndex(index, undefined),
646 )
647β
648 const getLocation = () => parseHref(entries[index]!, states[index])
649β
650 let blockers: Array<NavigationBlocker> = []
651 const _getBlockers = () => blockers
652 const _setBlockers = (newBlockers: Array<NavigationBlocker>) =>
653 (blockers = newBlockers)
654β
655 return createHistory({
656 getLocation,
657 getLength: () => entries.length,
658 pushState: (path, state) => {
659 // Removes all subsequent entries after the current index to start a new branch
660 index = index < entries.length - 1 ? index + 1 : entries.length
661 states[index] = state
662 entries[index] = path
663 if (index < entries.length - 1) {
664 entries.length = index + 1
665 states.length = index + 1
666 }
667 },
668 replaceState: (path, state) => {
669 states[index] = state
670 entries[index] = path
671 },
672 back: () => {
673 index = Math.max(index - 1, 0)
674 },
675 forward: () => {
676 index = Math.min(index + 1, entries.length - 1)
677 },
678 go: (n) => {
679 index = Math.min(Math.max(index + n, 0), entries.length - 1)
680 },
681 createHref: normalizeHref,
682 getBlockers: _getBlockers,
683 setBlockers: _setBlockers,
684 })
685}
686β
687const noop = () => {}
688β
689class ServerHistory implements RouterHistory {
690 declare private _subscribers?: RouterHistory['subscribers']
691β
692 constructor(public location: HistoryLocation) {}
693β
694 get length() {
695 return 1
696 }
697β
698 // Preserve the history interface without allocating a Set for each request.
699 get subscribers() {
700 return (this._subscribers ??= new Set())
701 }
702β
703 subscribe() {
704 return noop
705 }
706β
707 push() {}
708 replace() {}
709 go() {}
710 back() {}
711 forward() {}
712β
713 canGoBack() {
714 return false
715 }
716β
717 createHref(href: string) {
718 return normalizeHref(href)
719 }
720β
721 block() {
722 return noop
723 }
724β
725 flush() {}
726 destroy() {}
727 notify() {}
728β
729 _getBlockers(): Array<NavigationBlocker> {
730 return []
731 }
732}
733β
734/** A fixed request location; server navigation is a no-op. */
735export function createServerHistory(href: string): RouterHistory {
736 return new ServerHistory(parseHref(href, undefined))
737}
738β
739export function parseHref(
740 href: string,
741 state: ParsedHistoryState | undefined,
742): HistoryLocation {
743 const sanitizedHref = normalizeHref(href)
744 const hashIndex = sanitizedHref.indexOf('#')
745 const searchIndex = sanitizedHref.indexOf('?')
746 if (!state) {
747 const key = createRandomKey()
748 state = { [stateIndexKey]: 0, key, __TSR_key: key }
749 }
750β
751 return {
752 href: sanitizedHref,
753 pathname: sanitizedHref.slice(
754 0,
755 hashIndex > -1
756 ? searchIndex > -1
757 ? Math.min(hashIndex, searchIndex)
758 : hashIndex
759 : searchIndex > -1
760 ? searchIndex
761 : sanitizedHref.length,
762 ),
763 hash: hashIndex > -1 ? sanitizedHref.slice(hashIndex) : '',
764 search:
765 searchIndex > -1
766 ? sanitizedHref.slice(
767 searchIndex,
768 hashIndex === -1 ? undefined : hashIndex,
769 )
770 : '',
771 state,
772 }
773}
774β
775// Thanks co-pilot!
776function createRandomKey() {
777 return (Math.random() + 1).toString(36).slice(7)
778}