Open History to see the last commit
1import * as Solid from 'solid-js'
2import { getLocationChangeInfo, trimPathRight } from '@tanstack/router-core'
3import { isServer } from '@tanstack/router-core/isServer'
4import { useRouter } from './useRouter'
5β
6function getResolvedLocation(router: ReturnType<typeof useRouter>) {
7 const resolvedLocation = router.stores.resolvedLocation.get()
8 if (
9 resolvedLocation?.href === router.latestLocation.href &&
10 resolvedLocation.state.__TSR_key === router.latestLocation.state.__TSR_key
11 ) {
12 return resolvedLocation
13 }
14 return
15}
16β
17export function Transitioner() {
18 const router = useRouter()
19β
20 if (isServer ?? router.isServer) {
21 return null
22 }
23β
24 let settleCurrent: ((rendered: boolean) => void) | undefined
25 router.startTransition = (fn) => {
26 settleCurrent?.(false)
27β
28 return new Promise((resolve, reject) => {
29 const settle = (rendered: boolean) => {
30 if (settleCurrent !== settle) {
31 return
32 }
33 settleCurrent = undefined
34 resolve(rendered)
35 }
36 const fail = (cause: unknown) => {
37 if (settleCurrent !== settle) {
38 return
39 }
40 settleCurrent = undefined
41 reject(cause)
42 }
43 settleCurrent = settle
44β
45 void Solid.startTransition(() => {
46 // A newer publication may supersede this deferred callback.
47 if (settleCurrent === settle) {
48 try {
49 fn()
50 } catch (cause) {
51 fail(cause)
52 }
53 }
54 }).then(() => settle(true), fail)
55 })
56 }
57β
58 Solid.onCleanup(() => {
59 settleCurrent?.(false)
60 })
61β
62 // Subscribe to location changes
63 // and try to load the new location
64 Solid.onMount(() => {
65 Solid.onCleanup(router.history.subscribe(router.load))
66β
67 const nextLocation = router.buildLocation({
68 to: router.latestLocation.pathname,
69 search: true,
70 params: true,
71 hash: true,
72 state: true,
73 _includeValidateSearch: true,
74 })
75β
76 // Check if the current URL matches the canonical form.
77 // Compare publicHref (browser-facing URL) consistently with server
78 // canonicalization.
79 if (
80 trimPathRight(router.latestLocation.publicHref) !==
81 trimPathRight(nextLocation.publicHref)
82 ) {
83 router.commitLocation({
84 ...nextLocation,
85 replace: true,
86 ignoreBlocker: true,
87 })
88 return
89 }
90β
91 if (!getResolvedLocation(router) && !router._tx) {
92 router.load().catch(console.error)
93 }
94 })
95β
96 return null
97}
98β
99export function Rendered() {
100 const router = useRouter()
101 Solid.onMount(() => {
102 const resolvedLocation = getResolvedLocation(router)
103 if (resolvedLocation) {
104 router.emit({
105 type: 'onRendered',
106 ...getLocationChangeInfo(resolvedLocation, resolvedLocation),
107 })
108 }
109 })
110 return null
111}