Open History to see the last commit
1'use client'
2β
3import * as React from 'react'
4import { getLocationChangeInfo, trimPathRight } from '@tanstack/router-core'
5import { useLayoutEffect } from './utils'
6import { useRouter } from './useRouter'
7import type { AnyRouter } from '@tanstack/router-core'
8β
9export function settleOwner(
10 owner: NonNullable<AnyRouter['_rendered']>,
11 rendered: boolean,
12) {
13 const settle = owner[1 /* settle */]
14 owner.length = 0
15 settle?.(rendered)
16}
17β
18export function Transitioner({
19 t,
20}: {
21 t: React.Dispatch<React.SetStateAction<AnyRouter | undefined>>
22}) {
23 const router = useRouter()
24 const acknowledgement = (router._rendered ??= [])
25 const mounted =
26 process.env.NODE_ENV !== 'production'
27 ? // eslint-disable-next-line react-hooks/rules-of-hooks
28 React.useRef(false)
29 : undefined
30β
31 router.startTransition = (fn, expected) =>
32 new Promise((resolve) => {
33 settleOwner(acknowledgement, false)
34 acknowledgement.push(expected, resolve)
35 t(router)
36 React.startTransition(fn)
37 })
38β
39 // Subscribe before canonicalizing so the initial URL has exactly one load.
40 useLayoutEffect(() => {
41 const unsub = router.history.subscribe(router.load)
42β
43 if (mounted?.current) {
44 return unsub
45 }
46 if (mounted) {
47 mounted.current = true
48 }
49β
50 router.updateLatestLocation()
51 const location = router.latestLocation
52 const nextLocation = router.buildLocation({
53 to: location.pathname,
54 search: true,
55 params: true,
56 hash: true,
57 state: true,
58 _includeValidateSearch: true,
59 })
60β
61 // Check if the current URL matches the canonical form.
62 // Compare publicHref (browser-facing URL) consistently with server
63 // canonicalization.
64 if (
65 trimPathRight(location.publicHref) !==
66 trimPathRight(nextLocation.publicHref)
67 ) {
68 router.commitLocation({
69 ...nextLocation,
70 replace: true,
71 ignoreBlocker: true,
72 })
73 return unsub
74 }
75β
76 const resolvedLocation = router.stores.resolvedLocation.get()
77 if (
78 resolvedLocation?.href === location.href &&
79 resolvedLocation.state.__TSR_key === location.state.__TSR_key
80 ) {
81 acknowledgement.push(router.stores.matches.get(), (rendered) => {
82 if (rendered) {
83 router.emit({
84 type: 'onRendered',
85 ...getLocationChangeInfo(resolvedLocation, resolvedLocation),
86 })
87 }
88 })
89 } else if (!router._tx) {
90 router.load({ sync: true }).catch(console.error)
91 }
92β
93 return unsub
94 // `mounted` exists only in development and is a stable ref when present.
95 // eslint-disable-next-line react-hooks/exhaustive-deps
96 }, [router, router.history])
97β
98 return null
99}