-
-
Notifications
You must be signed in to change notification settings - Fork 335
Expand file tree
/
Copy path__root.tsx
More file actions
315 lines (281 loc) · 9.03 KB
/
__root.tsx
File metadata and controls
315 lines (281 loc) · 9.03 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
import * as React from 'react'
import {
createRootRouteWithContext,
redirect,
useMatches,
useRouterState,
HeadContent,
Scripts,
} from '@tanstack/react-router'
import { QueryClient } from '@tanstack/react-query'
import appCss from '~/styles/app.css?url'
import {
canonicalUrl,
getCanonicalPath,
seo,
shouldIndexPath,
} from '~/utils/seo'
import ogImage from '~/images/og.png'
const LazyRouterDevtools = React.lazy(() =>
import('@tanstack/react-router-devtools').then((m) => ({
default: m.TanStackRouterDevtoolsInProd,
})),
)
import { NotFound } from '~/components/NotFound'
import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary'
import { SearchProvider, useSearchContext } from '~/contexts/SearchContext'
import { ToastProvider } from '~/components/ToastProvider'
import { LoginModalProvider } from '~/contexts/LoginModalContext'
const LazySearchModal = React.lazy(() =>
import('~/components/SearchModal').then((m) => ({ default: m.SearchModal })),
)
import { Spinner } from '~/components/Spinner'
import { ThemeProvider, useHtmlClass } from '~/components/ThemeProvider'
import { Navbar } from '~/components/Navbar'
import { THEME_COLORS } from '~/utils/utils'
import { useHubSpotChat } from '~/hooks/useHubSpotChat'
declare global {
interface Window {
dataLayer: unknown[] | undefined
gtag: ((...args: unknown[]) => void) | undefined
}
}
export const Route = createRootRouteWithContext<{
queryClient: QueryClient
}>()({
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: 'stylesheet', href: appCss },
{
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')}})()`,
},
],
}),
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 (
<ThemeProvider>
<SearchProvider>
<ShellComponent>{children}</ShellComponent>
</SearchProvider>
</ThemeProvider>
)
},
errorComponent: DefaultCatchBoundary,
notFoundComponent: () => <NotFound />,
})
function ShellComponent({ children }: { children: React.ReactNode }) {
const hasBaseParent = useMatches({
select: (matches) => matches.find((d) => d.staticData?.baseParent),
})
// HubSpot chat loads on configured pages (see useHubSpotChat hook)
useHubSpotChat()
const isLoading = useRouterState({
select: (s) => s.status === 'pending',
})
const [canShowLoading, setShowLoading] = React.useState(false)
React.useEffect(() => {
const timeout = setTimeout(() => {
setShowLoading(true)
}, 2000)
return () => {
clearTimeout(timeout)
}
}, [])
const isRouterPage = useRouterState({
select: (s) => s.resolvedLocation?.pathname.startsWith('/router'),
})
const canonicalPath = useRouterState({
select: (s) => s.resolvedLocation?.pathname || '/',
})
const preferredCanonicalPath = getCanonicalPath(canonicalPath)
const showDevtools = canShowLoading && isRouterPage
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)} />
) : null}
{!shouldIndexPath(canonicalPath) ? (
<meta name="robots" content="noindex, nofollow" />
) : null}
<HeadContent />
{hasBaseParent ? <base target="_parent" /> : null}
</head>
<body className="overflow-x-hidden">
<LoginModalProvider>
<ToastProvider>
<IdleGtmLoader />
{hideNavbar ? children : <Navbar>{children}</Navbar>}
{showDevtools ? (
<LazyRouterDevtools position="bottom-right" />
) : null}
{canShowLoading ? (
<div
className={`fixed top-0 left-0 h-[300px] w-full
transition-all duration-300 pointer-events-none
z-30 dark:h-[200px] dark:bg-white/10! dark:rounded-[100%] ${
isLoading
? 'delay-500 opacity-1 -translate-y-1/2'
: 'delay-0 opacity-0 -translate-y-full'
}`}
style={{
background: `radial-gradient(closest-side, rgba(0,10,40,0.2) 0%, rgba(0,0,0,0) 100%)`,
}}
>
<div
className={`absolute top-1/2 left-1/2 -translate-x-1/2 translate-y-[30px] p-2 bg-white/80 dark:bg-gray-800
rounded-lg shadow-lg`}
>
<Spinner className="text-5xl" />
</div>
</div>
) : null}
<SearchHotkeyController />
</ToastProvider>
</LoginModalProvider>
<Scripts />
</body>
</html>
)
}
function SearchHotkeyController() {
const { isOpen, openSearch } = useSearchContext()
const [hasOpenedSearch, setHasOpenedSearch] = React.useState(false)
React.useEffect(() => {
const handleGlobalKeyDown = (event: KeyboardEvent) => {
if (event.defaultPrevented) return
if (!(event.metaKey || event.ctrlKey)) return
if (event.key.toLowerCase() !== 'k') return
event.preventDefault()
setHasOpenedSearch(true)
openSearch()
}
window.addEventListener('keydown', handleGlobalKeyDown)
return () => {
window.removeEventListener('keydown', handleGlobalKeyDown)
}
}, [openSearch])
React.useEffect(() => {
if (isOpen) {
setHasOpenedSearch(true)
}
}, [isOpen])
if (!hasOpenedSearch) return null
return (
<React.Suspense fallback={null}>
<LazySearchModal />
</React.Suspense>
)
}
function IdleGtmLoader() {
const pagePath = useRouterState({
select: (s) => {
const pathname = s.resolvedLocation?.pathname || '/'
const search = s.resolvedLocation?.searchStr || ''
return `${pathname}${search}`
},
})
React.useEffect(() => {
const gaId = 'G-JMT1Z50SPS'
const existingScript = document.querySelector<HTMLScriptElement>(
`script[src*="googletagmanager.com/gtag/js?id=${gaId}"]`,
)
if (!window.dataLayer) {
window.dataLayer = []
}
if (!window.gtag) {
window.gtag = (...args: unknown[]) => {
window.dataLayer?.push(args)
}
}
window.gtag('js', new Date())
window.gtag('config', gaId, {
send_page_view: false,
})
if (!existingScript) {
const script = document.createElement('script')
script.async = true
script.src = `https://www.googletagmanager.com/gtag/js?id=${gaId}`
document.head.appendChild(script)
}
}, [])
React.useEffect(() => {
if (!window.gtag) {
return
}
window.gtag('event', 'page_view', {
page_title: document.title,
page_path: pagePath,
page_location: window.location.href,
})
}, [pagePath])
return null
}