-
-
Notifications
You must be signed in to change notification settings - Fork 362
Expand file tree
/
Copy path__root.tsx
More file actions
324 lines (293 loc) · 10.2 KB
/
Copy path__root.tsx
File metadata and controls
324 lines (293 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import * as React from 'react'
import {
createRootRouteWithContext,
redirect,
useMatches,
useRouterState,
HeadContent,
Scripts,
} from '@tanstack/react-router'
import { QueryClient } from '@tanstack/react-query'
import '~/styles/app.css'
import {
canonicalUrl,
getCanonicalPath,
seo,
shouldIndexPath,
} from '~/utils/seo'
import ogImage from '~/images/og.png'
const LazyAppDevtools = import.meta.env.DEV
? React.lazy(() =>
import('~/components/AppDevtools').then((m) => ({
default: m.AppDevtools,
})),
)
: null
import { NotFound } from '~/components/NotFound'
import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary'
import { SearchProvider } from '~/contexts/SearchContext'
import { ToastProvider } from '~/components/ToastProvider'
import { LoginModalProvider } from '~/contexts/LoginModalContext'
import { Spinner } from '~/components/Spinner'
import { ThemeProvider, useHtmlClass } from '~/components/ThemeProvider'
import { Navbar } from '~/components/Navbar'
import { THEME_COLORS } from '~/utils/utils'
import { trackPageView } from '~/utils/analytics'
import { createPartnerPlacementSessionSeed } from '~/utils/partner-placement'
import { twMerge } from 'tailwind-merge'
const GOOGLE_ANALYTICS_ID = 'G-JMT1Z50SPS'
const GOOGLE_ANALYTICS_PROXY_PREFIX = '/_a'
const GOOGLE_ANALYTICS_SCRIPT_SRC = `${GOOGLE_ANALYTICS_PROXY_PREFIX}/gtag.js`
const GOOGLE_ANALYTICS_BOOTSTRAP = `(function(){var id='${GOOGLE_ANALYTICS_ID}';var src='${GOOGLE_ANALYTICS_SCRIPT_SRC}';window.dataLayer=window.dataLayer||[];window.gtag=window.gtag||function(){window.dataLayer.push(arguments)};window.gtag('js',new Date());window.gtag('config',id,{transport_url:window.location.origin+'${GOOGLE_ANALYTICS_PROXY_PREFIX}'});var loaded=false;var load=function(){if(loaded)return;loaded=true;var script=document.createElement('script');script.async=true;script.src=src;script.setAttribute('data-ga-loader','true');document.head.appendChild(script)};if(typeof window.requestIdleCallback==='function'){window.requestIdleCallback(load,{timeout:3000});return}if(document.readyState==='complete'){window.setTimeout(load,1500);return}window.addEventListener('load',function(){window.setTimeout(load,1500)},{once:true})})();`
class OptionalDevtoolsBoundary extends React.Component<
{ children: React.ReactNode },
{ hasError: boolean }
> {
state = { hasError: false }
static getDerivedStateFromError() {
return { hasError: true }
}
componentDidCatch(error: Error) {
if (import.meta.env.DEV) {
console.warn('TanStack Devtools failed to load', error)
}
}
render() {
if (this.state.hasError) {
return null
}
return this.props.children
}
}
export const Route = createRootRouteWithContext<{
queryClient: QueryClient
}>()({
loader: () => ({
partnerPlacementSessionSeed: createPartnerPlacementSessionSeed(),
}),
head: () => ({
meta: [
{
charSet: 'utf-8',
},
{
name: 'viewport',
content: 'width=device-width, initial-scale=1',
},
{
name: 'theme-color',
content: THEME_COLORS.light,
media: '(prefers-color-scheme: light)',
},
{
name: 'theme-color',
content: THEME_COLORS.dark,
media: '(prefers-color-scheme: dark)',
},
...seo({
title:
'TanStack | High Quality Open-Source Software for Web Developers',
description: `Headless, type-safe, powerful utilities for complex workflows like Data Management, Data Visualization, Charts, Tables, and UI Components.`,
image: `https://tanstack.com${ogImage}`,
keywords:
'tanstack,react,reactjs,react query,react table,open source,open source software,oss,software',
}),
],
links: [
{
rel: 'preload',
href: '/fonts/Inter-latin.woff2',
as: 'font',
type: 'font/woff2',
crossOrigin: 'anonymous',
},
{
rel: 'apple-touch-icon',
sizes: '180x180',
href: '/apple-touch-icon.png',
},
{
rel: 'icon',
type: 'image/png',
sizes: '32x32',
href: '/favicon-32x32.png',
},
{
rel: 'icon',
type: 'image/png',
sizes: '16x16',
href: '/favicon-16x16.png',
},
{ rel: 'manifest', href: '/site.webmanifest', color: '#fffff' },
{ rel: 'icon', href: '/favicon.ico' },
],
scripts: [
// Theme detection script - must run before body renders to prevent flash
{
children: `(function(){try{var t=localStorage.getItem('theme')||'auto';var v=['light','dark','auto'].includes(t)?t:'auto';if(v==='auto'){var a=matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';document.documentElement.classList.add(a,'auto')}else{document.documentElement.classList.add(v)}}catch(e){var a=matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';document.documentElement.classList.add(a,'auto')}})()`,
},
{
children: GOOGLE_ANALYTICS_BOOTSTRAP,
},
],
}),
beforeLoad: async (ctx) => {
if (
ctx.location.href.match(/\/docs\/(react|vue|angular|svelte|solid)\//gm)
) {
throw redirect({
href: ctx.location.href.replace(
/\/docs\/(react|vue|angular|svelte|solid)\//gm,
'/docs/framework/$1/',
),
})
}
// Initialize user as undefined - routes can opt-in to load auth if needed
// Use undefined instead of null to distinguish between "not loaded" and "no user"
},
staleTime: Infinity,
shellComponent: ({ children }) => {
return <RootShell>{children}</RootShell>
},
errorComponent: DefaultCatchBoundary,
notFoundComponent: () => <NotFound />,
})
function RootShell({ children }: { children: React.ReactNode }) {
return (
<ThemeProvider>
<SearchProvider>
<ShellComponent>{children}</ShellComponent>
</SearchProvider>
</ThemeProvider>
)
}
function ShellComponent({ children }: { children: React.ReactNode }) {
const hasBaseParent = useMatches({
select: (matches) => matches.find((d) => d.staticData?.baseParent),
})
const isNavigating = useRouterState({
select: (s) => s.isLoading || s.isTransitioning,
})
const [canShowDevtools, setCanShowDevtools] = React.useState(false)
const [showNavigationSpinner, setShowNavigationSpinner] =
React.useState(false)
React.useEffect(() => {
const timeout = setTimeout(() => {
setCanShowDevtools(true)
}, 2000)
return () => {
clearTimeout(timeout)
}
}, [])
React.useEffect(() => {
if (!isNavigating) {
setShowNavigationSpinner(false)
return
}
const timeout = window.setTimeout(() => {
setShowNavigationSpinner(true)
}, 1000)
return () => {
window.clearTimeout(timeout)
}
}, [isNavigating])
const canonicalPath = useRouterState({
select: (s) => s.location?.pathname || '/',
})
const canonicalSearchStr = useRouterState({
select: (s) => s.location?.searchStr || '',
})
const includeSearchInCanonical = useMatches({
select: (s) =>
s.some((d) => d.staticData?.includeSearchInCanonical === true),
})
const preferredCanonicalPath = getCanonicalPath(canonicalPath)
const canonicalSearch = includeSearchInCanonical ? canonicalSearchStr : ''
const pageUrl = canonicalUrl(
preferredCanonicalPath ?? canonicalPath,
canonicalSearch,
)
const showDevtools = import.meta.env.DEV && canShowDevtools
const hideNavbar = useMatches({
select: (s) => s.some((d) => d.staticData?.showNavbar === false),
})
const htmlClass = useHtmlClass()
return (
<html lang="en" className={htmlClass} suppressHydrationWarning>
<head>
{preferredCanonicalPath ? (
<link
rel="canonical"
href={canonicalUrl(preferredCanonicalPath, canonicalSearch)}
/>
) : null}
<meta property="og:url" content={pageUrl} />
<meta name="twitter:url" content={pageUrl} />
{!shouldIndexPath(canonicalPath) ? (
<meta name="robots" content="noindex, nofollow" />
) : null}
<HeadContent />
{hasBaseParent ? <base target="_parent" /> : null}
</head>
<body className="overflow-x-hidden">
<LoginModalProvider>
<ToastProvider>
<PageViewTracker />
{hideNavbar ? children : <Navbar>{children}</Navbar>}
{showDevtools && LazyAppDevtools ? (
<OptionalDevtoolsBoundary>
<React.Suspense fallback={null}>
<LazyAppDevtools />
</React.Suspense>
</OptionalDevtoolsBoundary>
) : null}
<div
aria-hidden="true"
className={twMerge(
'pointer-events-none fixed top-0 left-0 z-99999999 h-[320px] w-full select-none',
)}
>
<div
className={twMerge(
'absolute top-0 w-full h-80 rounded-[100%] bg-amber-500/30 blur-3xl transition-all duration-500 dark:bg-sky-400/25',
showNavigationSpinner
? '-translate-y-1/2 opacity-100'
: '-translate-y-full opacity-0',
)}
/>
<div
className={twMerge(
'absolute top-6 left-1/2 -translate-x-1/2 rounded-full bg-white/75 p-2 shadow-lg backdrop-blur-lg transition-all duration-300 dark:bg-slate-900/40',
showNavigationSpinner
? 'translate-y-0 opacity-100'
: '-translate-y-6 opacity-0',
)}
>
<Spinner className="text-4xl" />
</div>
</div>
</ToastProvider>
</LoginModalProvider>
<Scripts />
</body>
</html>
)
}
function PageViewTracker() {
const pagePath = useRouterState({
select: (s) => {
const pathname = s.resolvedLocation?.pathname || '/'
const search = s.resolvedLocation?.searchStr || ''
return `${pathname}${search}`
},
})
const hasTrackedInitialPage = React.useRef(false)
React.useEffect(() => {
if (!hasTrackedInitialPage.current) {
hasTrackedInitialPage.current = true
return
}
trackPageView(pagePath)
}, [pagePath])
return null
}