Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

main.tsx

1,123 lines30.6 KB

1/* eslint-disable @typescript-eslint/no-unnecessary-condition */
2import * as React from 'react'
3import ReactDOM from 'react-dom/client'
4import {
5 ErrorComponent,
6 Link,
7 MatchRoute,
8 Outlet,
9 RouterProvider,
10 createRootRouteWithContext,
11 createRoute,
12 createRouter,
13 lazyRouteComponent,
14 redirect,
15 retainSearchParams,
16 useNavigate,
17 useRouter,
18 useRouterState,
19 useSearch,
20} from '@tanstack/react-router'
21import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
22import {
23 QueryClient,
24 QueryClientProvider,
25 queryOptions,
26 useMutation,
27 useSuspenseQuery,
28} from '@tanstack/react-query'
29import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
30import { z } from 'zod'
31import {
32 fetchInvoiceById,
33 fetchInvoices,
34 fetchUserById,
35 fetchUsers,
36 patchInvoice,
37 postInvoice,
38} from './mockTodos'
39import type { Invoice } from './mockTodos'
40import './styles.css'
41​
42//
43​
44type UsersViewSortBy = 'name' | 'id' | 'email'
45​
46const invoicesQueryOptions = () =>
47 queryOptions({
48 queryKey: ['invoices'],
49 queryFn: () => fetchInvoices(),
50 })
51​
52const invoiceQueryOptions = (invoiceId: number) =>
53 queryOptions({
54 queryKey: ['invoices', invoiceId],
55 queryFn: () => fetchInvoiceById(invoiceId),
56 })
57​
58const usersQueryOptions = ({
59 filterBy,
60 sortBy,
61}: {
62 filterBy?: string
63 sortBy?: UsersViewSortBy
64}) =>
65 queryOptions({
66 queryKey: ['users', { filterBy, sortBy }],
67 queryFn: () =>
68 fetchUsers({
69 filterBy,
70 sortBy,
71 }),
72 })
73​
74const userQueryOptions = (userId: number) =>
75 queryOptions({
76 queryKey: ['users', userId],
77 queryFn: async () => {
78 const user = await fetchUserById(userId)
79 if (!user) {
80 throw new Error('User not found.')
81 }
82 return user
83 },
84 })
85​
86const useCreateInvoiceMutation = () => {
87 return useMutation({
88 mutationKey: ['invoices', 'create'],
89 mutationFn: postInvoice,
90 onSuccess: () => queryClient.invalidateQueries(),
91 })
93​
94const useUpdateInvoiceMutation = (invoiceId: number) => {
95 return useMutation({
96 mutationKey: ['invoices', 'update', invoiceId],
97 mutationFn: patchInvoice,
98 onSuccess: () => queryClient.invalidateQueries(),
99 gcTime: 1000 * 10,
100 })
102​
103function RouterSpinner() {
104 const isLoading = useRouterState({ select: (s) => s.status === 'pending' })
105 return <Spinner show={isLoading} />
107​
108// Routes
109​
110// Build our routes. We could do this in our component, too.
111const rootRoute = createRootRouteWithContext<{
112 auth: Auth
113 queryClient: QueryClient
114}>()({
115 component: RootComponent,
116})
117​
118function RootComponent() {
119 return (
120 <>
121 <div className={`min-h-screen flex flex-col`}>
122 <div className={`flex items-center border-b gap-2`}>
123 <h1 className={`text-3xl p-2`}>Kitchen Sink</h1>
124 {/* Show a global spinner when the router is transitioning */}
125 <div className={`text-3xl`}>
126 <RouterSpinner />
127 </div>
128 </div>
129 <div className={`flex-1 flex`}>
130 <div className={`divide-y w-56`}>
131 {(
132 [
133 ['/', 'Home'],
134 ['/dashboard', 'Dashboard'],
135 ['/expensive', 'Expensive'],
136 ['/route-a', 'Pathless Layout A'],
137 ['/route-b', 'Pathless Layout B'],
138 ['/profile', 'Profile'],
139 ['/login', 'Login'],
140 ] as const
141 ).map(([to, label]) => {
142 return (
143 <div key={to}>
144 <Link
145 to={to}
146 activeOptions={
147 {
148 // If the route points to the root of it's parent,
149 // make sure it's only active if it's exact
150 // exact: to === '.',
151 }
152 }
153 preload="intent"
154 className={`block py-2 px-3 text-blue-700`}
155 // Make "active" links bold
156 activeProps={{ className: `font-bold` }}
157 >
158 {label}
159 </Link>
160 </div>
161 )
162 })}
163 </div>
164 <div className={`flex-1 border-l`}>
165 {/* Render our first route match */}
166 <Outlet />
167 </div>
168 </div>
169 </div>
170 <TanStackRouterDevtools position="bottom-right" />
171 <ReactQueryDevtools buttonPosition="top-right" />
172 </>
173 )
175​
176const indexRoute = createRoute({
177 getParentRoute: () => rootRoute,
178 path: '/',
179 component: IndexComponent,
180})
181​
182function IndexComponent() {
183 return (
184 <div className={`p-2`}>
185 <div className={`text-lg`}>Welcome Home!</div>
186 <hr className={`my-2`} />
187 <Link
188 to={invoiceRoute.to}
189 params={{
190 invoiceId: 3,
191 }}
192 className={`py-1 px-2 text-xs bg-blue-500 text-white rounded-full`}
193 >
194 1 New Invoice
195 </Link>
196 <hr className={`my-2`} />
197 <div className={`max-w-xl`}>
198 As you navigate around take note of the UX. It should feel
199 suspense-like, where routes are only rendered once all of their data and
200 elements are ready.
201 <hr className={`my-2`} />
202 To exaggerate async effects, play with the artificial request delay
203 slider in the bottom-left corner.
204 <hr className={`my-2`} />
205 The last 2 sliders determine if link-hover preloading is enabled (and
206 how long those preloads stick around) and also whether to cache rendered
207 route data (and for how long). Both of these default to 0 (or off).
208 </div>
209 </div>
210 )
212​
213const dashboardLayoutRoute = createRoute({
214 getParentRoute: () => rootRoute,
215 path: 'dashboard',
216 component: DashboardLayoutComponent,
217})
218​
219function DashboardLayoutComponent() {
220 return (
221 <>
222 <div className="flex items-center border-b">
223 <h2 className="text-xl p-2">Dashboard</h2>
224 </div>
225 <div className="flex flex-wrap divide-x">
226 {(
227 [
228 ['/dashboard', 'Summary', true],
229 ['/dashboard/invoices', 'Invoices'],
230 ['/dashboard/users', 'Users'],
231 ] as const
232 ).map(([to, label, exact]) => {
233 return (
234 <Link
235 key={to}
236 to={to}
237 activeOptions={{ exact }}
238 activeProps={{ className: `font-bold` }}
239 className="p-2"
240 >
241 {label}
242 </Link>
243 )
244 })}
245 </div>
246 <hr />
247 <Outlet />
248 </>
249 )
251​
252const dashboardIndexRoute = createRoute({
253 getParentRoute: () => dashboardLayoutRoute,
254 path: '/',
255 loader: (opts) =>
256 opts.context.queryClient.ensureQueryData(invoicesQueryOptions()),
257 component: DashboardIndexComponent,
258})
259​
260function DashboardIndexComponent() {
261 const invoicesQuery = useSuspenseQuery(invoicesQueryOptions())
262 const invoices = invoicesQuery.data
263​
264 return (
265 <div className="p-2">
266 <div className="p-2">
267 Welcome to the dashboard! You have{' '}
268 <strong>{invoices.length} total invoices</strong>.
269 </div>
270 </div>
271 )
273​
274const invoicesLayoutRoute = createRoute({
275 getParentRoute: () => dashboardLayoutRoute,
276 path: 'invoices',
277 loader: (opts) =>
278 opts.context.queryClient.ensureQueryData(invoicesQueryOptions()),
279 component: InvoicesLayoutComponent,
280})
281​
282function InvoicesLayoutComponent() {
283 const invoicesQuery = useSuspenseQuery(invoicesQueryOptions())
284 const invoices = invoicesQuery.data
285 // const updateInvoiceMutation = useUpdateInvoiceMutation()
286 // const createInvoiceMutation = useCreateInvoiceMutation()
287​
288 return (
289 <div className="flex-1 flex">
290 {/* {routerTransitionIsPending ? 'pending' : 'null'} */}
291 <div className="divide-y w-48">
292 {invoices.map((invoice) => {
293 // const updateSubmission = updateInvoiceMutation.submissions.find(
294 // (d) => d.variables?.id === invoice.id,
295 // )
296​
297 // if (updateSubmission) {
298 // invoice = {
299 // ...invoice,
300 // ...updateSubmission.variables,
301 // }
302 // }
303​
304 return (
305 <div key={invoice.id}>
306 <Link
307 to="/dashboard/invoices/$invoiceId"
308 params={{
309 invoiceId: invoice.id,
310 }}
311 preload="intent"
312 className="block py-2 px-3 text-blue-700"
313 activeProps={{ className: `font-bold` }}
314 >
315 <pre className="text-sm">
316 #{invoice.id} - {invoice.title.slice(0, 10)}{' '}
317 {/* {updateSubmission ? (
318 <Spinner />
319 ) : ( */}
320 <MatchRoute
321 to={invoiceRoute.to}
322 params={{
323 invoiceId: invoice.id,
324 }}
325 pending
326 >
327 {(match) => <Spinner show={!!match} wait="delay-50" />}
328 </MatchRoute>
329 {/* )} */}
330 </pre>
331 </Link>
332 </div>
333 )
334 })}
335 {/* {createSubmissions.map((action) => (
336 <div key={action.submittedAt}>
337 <a href="#" className="block py-2 px-3 text-blue-700">
338 <pre className="text-sm">
339 #<Spinner /> - {action.variables.title?.slice(0, 10)}
340 </pre>
341 </a>
342 </div>
343 ))} */}
344 </div>
345 <div className="flex-1 border-l">
346 <Outlet />
347 </div>
348 </div>
349 )
351​
352const invoicesIndexRoute = createRoute({
353 getParentRoute: () => invoicesLayoutRoute,
354 path: '/',
355 component: InvoicesIndexComponent,
356})
357​
358function InvoicesIndexComponent() {
359 const createInvoiceMutation = useCreateInvoiceMutation()
360​
361 return (
362 <>
363 <div className="p-2">
364 <form
365 onSubmit={(event) => {
366 event.preventDefault()
367 event.stopPropagation()
368 const formData = new FormData(event.target as HTMLFormElement)
369 createInvoiceMutation.mutate({
370 title: formData.get('title') as string,
371 body: formData.get('body') as string,
372 })
373 }}
374 className="space-y-2"
375 >
376 <div>Create a new Invoice:</div>
377 <InvoiceFields invoice={{} as Invoice} />
378 <div>
379 <button
380 className="bg-blue-500 rounded-sm p-2 uppercase text-white font-black disabled:opacity-50"
381 disabled={createInvoiceMutation.status === 'pending'}
382 >
383 {createInvoiceMutation.status === 'pending' ? (
384 <>
385 Creating <Spinner />
386 </>
387 ) : (
388 'Create'
389 )}
390 </button>
391 </div>
392 {createInvoiceMutation.status === 'success' ? (
393 <div className="inline-block px-2 py-1 rounded-sm bg-green-500 text-white animate-bounce [animation-iteration-count:2.5] [animation-duration:.3s]">
394 Created!
395 </div>
396 ) : createInvoiceMutation.status === 'error' ? (
397 <div className="inline-block px-2 py-1 rounded-sm bg-red-500 text-white animate-bounce [animation-iteration-count:2.5] [animation-duration:.3s]">
398 Failed to create.
399 </div>
400 ) : null}
401 </form>
402 </div>
403 </>
404 )
406​
407const invoiceRoute = createRoute({
408 getParentRoute: () => invoicesLayoutRoute,
409 path: '$invoiceId',
410 params: {
411 parse: (params) => ({
412 invoiceId: z.number().int().parse(Number(params.invoiceId)),
413 }),
414 stringify: ({ invoiceId }) => ({ invoiceId: `${invoiceId}` }),
415 },
416 validateSearch: (search) =>
417 z
418 .object({
419 showNotes: z.boolean().optional(),
420 notes: z.string().optional(),
421 })
422 .parse(search),
423 loader: (opts) =>
424 opts.context.queryClient.ensureQueryData(
425 invoiceQueryOptions(opts.params.invoiceId),
426 ),
427 component: InvoiceComponent,
428})
429​
430function InvoiceComponent() {
431 const params = invoiceRoute.useParams()
432 const search = invoiceRoute.useSearch()
433 const navigate = useNavigate({ from: invoiceRoute.fullPath })
434 const invoiceQuery = useSuspenseQuery(invoiceQueryOptions(params.invoiceId))
435 const invoice = invoiceQuery.data
436 const updateInvoiceMutation = useUpdateInvoiceMutation(params.invoiceId)
437 const [notes, setNotes] = React.useState(search.notes ?? '')
438​
439 React.useEffect(() => {
440 navigate({
441 search: (old) => ({
442 ...old,
443 notes: notes ? notes : undefined,
444 }),
445 replace: true,
446 params: true,
447 })
448 }, [notes])
449​
450 return (
451 <form
452 key={invoice.id}
453 onSubmit={(event) => {
454 event.preventDefault()
455 event.stopPropagation()
456 const formData = new FormData(event.target as HTMLFormElement)
457 updateInvoiceMutation.mutate({
458 id: invoice.id,
459 title: formData.get('title') as string,
460 body: formData.get('body') as string,
461 })
462 }}
463 className="p-2 space-y-2"
464 >
465 <InvoiceFields
466 invoice={invoice}
467 disabled={updateInvoiceMutation.status === 'pending'}
468 />
469 <div>
470 <Link
471 search={(old) => ({
472 ...old,
473 showNotes: old.showNotes ? undefined : true,
474 })}
475 className="text-blue-700"
476 from={invoiceRoute.fullPath}
477 params={true}
478 >
479 {search.showNotes ? 'Close Notes' : 'Show Notes'}{' '}
480 </Link>
481 {search.showNotes ? (
482 <>
483 <div>
484 <div className="h-2" />
485 <textarea
486 value={notes}
487 onChange={(e) => {
488 setNotes(e.target.value)
489 }}
490 rows={5}
491 className="shadow-sm w-full p-2 rounded-sm"
492 placeholder="Write some notes here..."
493 />
494 <div className="italic text-xs">
495 Notes are stored in the URL. Try copying the URL into a new tab!
496 </div>
497 </div>
498 </>
499 ) : null}
500 </div>
501 <div>
502 <button
503 className="bg-blue-500 rounded-sm p-2 uppercase text-white font-black disabled:opacity-50"
504 disabled={updateInvoiceMutation.status === 'pending'}
505 >
506 Save
507 </button>
508 </div>
509 {updateInvoiceMutation.variables?.id === invoice.id ? (
510 <div key={updateInvoiceMutation.submittedAt}>
511 {updateInvoiceMutation.status === 'success' ? (
512 <div className="inline-block px-2 py-1 rounded-sm bg-green-500 text-white animate-bounce [animation-iteration-count:2.5] [animation-duration:.3s]">
513 Saved!
514 </div>
515 ) : updateInvoiceMutation.status === 'error' ? (
516 <div className="inline-block px-2 py-1 rounded-sm bg-red-500 text-white animate-bounce [animation-iteration-count:2.5] [animation-duration:.3s]">
517 Failed to save.
518 </div>
519 ) : null}
520 </div>
521 ) : null}
522 </form>
523 )
525​
526const usersLayoutRoute = createRoute({
527 getParentRoute: () => dashboardLayoutRoute,
528 path: 'users',
529 validateSearch: z.object({
530 usersView: z
531 .object({
532 sortBy: z.enum(['name', 'id', 'email']).optional(),
533 filterBy: z.string().optional(),
534 })
535 .optional(),
536 }).parse,
537 search: {
538 // Retain the usersView search param while navigating
539 // within or to this route (or it's children!)
540 middlewares: [retainSearchParams(['usersView'])],
541 },
542 loaderDeps: ({ search }) => ({
543 filterBy: search.usersView?.filterBy,
544 sortBy: search.usersView?.sortBy,
545 }),
546 loader: (opts) =>
547 opts.context.queryClient.ensureQueryData(usersQueryOptions(opts.deps)),
548 component: UsersComponent,
549})
550​
551function UsersComponent() {
552 const navigate = useNavigate({ from: usersLayoutRoute.fullPath })
553 const { usersView } = usersLayoutRoute.useSearch()
554 const usersQuery = useSuspenseQuery(
555 usersQueryOptions(usersLayoutRoute.useLoaderDeps()),
556 )
557 const users = usersQuery.data
558 const sortBy = usersView?.sortBy ?? 'name'
559 const filterBy = usersView?.filterBy
560​
561 const [filterDraft, setFilterDraft] = React.useState(filterBy ?? '')
562​
563 React.useEffect(() => {
564 setFilterDraft(filterBy ?? '')
565 }, [filterBy])
566​
567 const sortedUsers = React.useMemo(() => {
568 if (!users) return []
569​
570 return !sortBy
571 ? users
572 : [...users].sort((a, b) => {
573 return a[sortBy] > b[sortBy] ? 1 : -1
574 })
575 }, [users, sortBy])
576​
577 const filteredUsers = React.useMemo(() => {
578 if (!filterBy) return sortedUsers
579​
580 return sortedUsers.filter((user) =>
581 user.name.toLowerCase().includes(filterBy.toLowerCase()),
582 )
583 }, [sortedUsers, filterBy])
584​
585 const setSortBy = (sortBy: UsersViewSortBy) =>
586 navigate({
587 search: (old) => {
588 return {
589 ...old,
590 usersView: {
591 ...(old.usersView ?? {}),
592 sortBy,
593 },
594 }
595 },
596 replace: true,
597 })
598​
599 React.useEffect(() => {
600 navigate({
601 search: (old) => {
602 return {
603 ...old,
604 usersView: {
605 ...old.usersView,
606 filterBy: filterDraft || undefined,
607 },
608 }
609 },
610 replace: true,
611 })
612 }, [filterDraft])
613​
614 return (
615 <div className="flex-1 flex">
616 <div className="divide-y">
617 <div className="py-2 px-3 flex gap-2 items-center bg-gray-100 dark:bg-gray-800">
618 <div>Sort By:</div>
619 <select
620 value={sortBy}
621 onChange={(e) => setSortBy(e.target.value as UsersViewSortBy)}
622 className="flex-1 border p-1 px-2 rounded-sm"
623 >
624 {['name', 'id', 'email'].map((d) => {
625 return <option key={d} value={d} children={d} />
626 })}
627 </select>
628 </div>
629 <div className="py-2 px-3 flex gap-2 items-center bg-gray-100 dark:bg-gray-800">
630 <div>Filter By:</div>
631 <input
632 value={filterDraft}
633 onChange={(e) => setFilterDraft(e.target.value)}
634 placeholder="Search Names..."
635 className="min-w-0 flex-1 border p-1 px-2 rounded-sm"
636 />
637 </div>
638 {filteredUsers.map((user) => {
639 return (
640 <div key={user.id}>
641 <Link
642 to="/dashboard/users/user"
643 search={{
644 userId: user.id,
645 }}
646 className="block py-2 px-3 text-blue-700"
647 activeProps={{ className: `font-bold` }}
648 >
649 <pre className="text-sm">
650 {user.name}{' '}
651 <MatchRoute
652 to={userRoute.to}
653 search={{
654 userId: user.id,
655 }}
656 pending
657 >
658 {(match) => <Spinner show={!!match} wait="delay-50" />}
659 </MatchRoute>
660 </pre>
661 </Link>
662 </div>
663 )
664 })}
665 </div>
666 <div className="flex-initial border-l">
667 <Outlet />
668 </div>
669 </div>
670 )
672​
673const usersIndexRoute = createRoute({
674 getParentRoute: () => usersLayoutRoute,
675 path: '/',
676 component: UsersIndexComponent,
677})
678​
679function UsersIndexComponent() {
680 return (
681 <div className="p-2 space-y-2">
682 <p>
683 Normally, setting default search parameters would either need to be done
684 manually in every link to a page, or as a side-effect (not a great
685 experience).
686 </p>
687 <p>
688 Instead, we can use <strong>search filters</strong> to provide defaults
689 or even persist search params for links to routes (and child routes).
690 </p>
691 <p>
692 A good example of this is the sorting and filtering of the users list.
693 In a traditional router, both would be lost while navigating around
694 individual users or even changing each sort/filter option unless each
695 state was manually passed from the current route into each new link we
696 created (that's a lot of tedious and error-prone work). With TanStack
697 router and search filters, they are persisted with little effort.
698 </p>
699 </div>
700 )
702​
703const userRoute = createRoute({
704 getParentRoute: () => usersLayoutRoute,
705 path: 'user',
706 validateSearch: z.object({
707 userId: z.number(),
708 }),
709 loaderDeps: ({ search }) => ({
710 userId: search.userId,
711 }),
712 loader: (opts) =>
713 opts.context.queryClient.ensureQueryData(
714 userQueryOptions(opts.deps.userId),
715 ),
716 component: UserComponent,
717})
718​
719function UserComponent() {
720 const search = userRoute.useSearch()
721 const userQuery = useSuspenseQuery(userQueryOptions(search.userId))
722 const user = userQuery.data
723​
724 return (
725 <>
726 <h4 className="p-2 font-bold">{user?.name}</h4>
727 <pre className="text-sm whitespace-pre-wrap">
728 {JSON.stringify(user, null, 2)}
729 </pre>
730 </>
731 )
733​
734const expensiveRoute = createRoute({
735 getParentRoute: () => rootRoute,
736 // Your elements can be asynchronous, which means you can code-split!
737 path: 'expensive',
738 component: lazyRouteComponent(() => import('./Expensive')),
739})
740​
741const authPathlessLayoutRoute = createRoute({
742 getParentRoute: () => rootRoute,
743 id: 'auth',
744 // Before loading, authenticate the user via our auth context
745 // This will also happen during prefetching (e.g. hovering over links, etc)
746 beforeLoad: ({ context, location }) => {
747 // If the user is logged out, redirect them to the login page
748 if (context.auth.status === 'loggedOut') {
749 throw redirect({
750 to: loginRoute.to,
751 search: {
752 // Use the current location to power a redirect after login
753 // (Do not use `router.state.resolvedLocation` as it can
754 // potentially lag behind the actual current location)
755 redirect: location.href,
756 },
757 })
758 }
759​
760 // Otherwise, return the user in context
761 return {
762 username: auth.username,
763 }
764 },
765})
766​
767const profileRoute = createRoute({
768 getParentRoute: () => authPathlessLayoutRoute,
769 path: 'profile',
770 component: ProfileComponent,
771})
772​
773function ProfileComponent() {
774 const { username } = profileRoute.useRouteContext()
775​
776 return (
777 <div className="p-2 space-y-2">
778 <div>
779 Username:<strong>{username}</strong>
780 </div>
781 </div>
782 )
784​
785const loginRoute = createRoute({
786 getParentRoute: () => rootRoute,
787 path: 'login',
788 validateSearch: z.object({
789 redirect: z.string().optional(),
790 }),
791}).update({
792 component: LoginComponent,
793})
794​
795function LoginComponent() {
796 const router = useRouter()
797 const { auth, status } = loginRoute.useRouteContext({
798 select: ({ auth }) => ({ auth, status: auth.status }),
799 })
800 const search = useSearch({ from: loginRoute.fullPath })
801 const [username, setUsername] = React.useState('')
802​
803 const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
804 e.preventDefault()
805 auth.login(username)
806 router.invalidate()
807 }
808​
809 // Ah, the subtle nuances of client side auth. πŸ™„
810 React.useLayoutEffect(() => {
811 if (status === 'loggedIn' && search.redirect) {
812 router.history.push(search.redirect)
813 }
814 }, [status, search.redirect])
815​
816 return status === 'loggedIn' ? (
817 <div>
818 Logged in as <strong>{auth.username}</strong>
819 <div className="h-2" />
820 <button
821 onClick={() => auth.logout()}
822 className="text-sm bg-blue-500 text-white border inline-block py-1 px-2 rounded-sm"
823 >
824 Log out
825 </button>
826 <div className="h-2" />
827 </div>
828 ) : (
829 <div className="p-2">
830 <div>You must log in!</div>
831 <div className="h-2" />
832 <form onSubmit={onSubmit} className="flex gap-2">
833 <input
834 value={username}
835 onChange={(e) => setUsername(e.target.value)}
836 placeholder="Username"
837 className="border p-1 px-2 rounded-sm"
838 />
839 <button
840 onClick={() => auth.logout()}
841 className="text-sm bg-blue-500 text-white border inline-block py-1 px-2 rounded-sm"
842 >
843 Login
844 </button>
845 </form>
846 </div>
847 )
849​
850const pathlessLayoutRoute = createRoute({
851 getParentRoute: () => rootRoute,
852 id: 'pathlessLayout',
853 component: PathlessLayoutComponent,
854})
855​
856function PathlessLayoutComponent() {
857 return (
858 <div>
859 <div>Pathless Layout</div>
860 <hr />
861 <Outlet />
862 </div>
863 )
865​
866const pathlessLayoutARoute = createRoute({
867 getParentRoute: () => pathlessLayoutRoute,
868 path: 'route-a',
869 component: PathlessLayoutAComponent,
870})
871​
872function PathlessLayoutAComponent() {
873 return (
874 <div>
875 <div>I'm A</div>
876 </div>
877 )
879​
880const pathlessLayoutBRoute = createRoute({
881 getParentRoute: () => pathlessLayoutRoute,
882 path: 'route-b',
883 component: PathlessLayoutBComponent,
884})
885​
886function PathlessLayoutBComponent() {
887 return (
888 <div>
889 <div>i"m B</div>
890 </div>
891 )
893​
894const routeTree = rootRoute.addChildren([
895 indexRoute,
896 dashboardLayoutRoute.addChildren([
897 dashboardIndexRoute,
898 invoicesLayoutRoute.addChildren([invoicesIndexRoute, invoiceRoute]),
899 usersLayoutRoute.addChildren([usersIndexRoute, userRoute]),
900 ]),
901 expensiveRoute,
902 authPathlessLayoutRoute.addChildren([profileRoute]),
903 loginRoute,
904 pathlessLayoutRoute.addChildren([pathlessLayoutARoute, pathlessLayoutBRoute]),
905])
906​
907const queryClient = new QueryClient()
908​
909const router = createRouter({
910 routeTree,
911 defaultPendingComponent: () => (
912 <div className={`p-2 text-2xl`}>
913 <Spinner />
914 </div>
915 ),
916 defaultErrorComponent: ({ error }) => <ErrorComponent error={error} />,
917 context: {
918 auth: undefined!, // We'll inject this when we render
919 queryClient,
920 },
921 defaultPreload: 'intent',
922 // Since we're using React Query, we don't want loader calls to ever be stale
923 // This will ensure that the loader is always called when the route is preloaded or visited
924 defaultPreloadStaleTime: 0,
925 scrollRestoration: true,
926})
927​
928declare module '@tanstack/react-router' {
929 interface Register {
930 router: typeof router
931 }
933​
934const auth: Auth = {
935 status: 'loggedOut',
936 username: undefined,
937 login: (username: string) => {
938 auth.status = 'loggedIn'
939 auth.username = username
940 },
941 logout: () => {
942 auth.status = 'loggedOut'
943 auth.username = undefined
944 },
946​
947function App() {
948 // This stuff is just to tweak our sandbox setup in real-time
949 const [loaderDelay, setLoaderDelay] = useSessionStorage('loaderDelay', 500)
950 const [pendingMs, setPendingMs] = useSessionStorage('pendingMs', 1000)
951 const [pendingMinMs, setPendingMinMs] = useSessionStorage('pendingMinMs', 500)
952​
953 return (
954 <>
955 <div className="text-xs fixed w-52 shadow-md shadow-black/20 rounded-sm bottom-2 left-2 bg-white dark:bg-gray-800 bg-opacity-75 border-b flex flex-col gap-1 flex-wrap items-left divide-y">
956 <div className="p-2 space-y-2">
957 <div className="flex gap-2">
958 <button
959 className="bg-blue-500 text-white rounded-sm p-1 px-2"
960 onClick={() => {
961 setLoaderDelay(150)
962 }}
963 >
964 Fast
965 </button>
966 <button
967 className="bg-blue-500 text-white rounded-sm p-1 px-2"
968 onClick={() => {
969 setLoaderDelay(500)
970 }}
971 >
972 Fast 3G
973 </button>
974 <button
975 className="bg-blue-500 text-white rounded-sm p-1 px-2"
976 onClick={() => {
977 setLoaderDelay(2000)
978 }}
979 >
980 Slow 3G
981 </button>
982 </div>
983 <div>
984 <div>Loader Delay: {loaderDelay}ms</div>
985 <input
986 type="range"
987 min="0"
988 max="5000"
989 step="100"
990 value={loaderDelay}
991 onChange={(e) => setLoaderDelay(e.target.valueAsNumber)}
992 className="w-full"
993 />
994 </div>
995 </div>
996 <div className="p-2 space-y-2">
997 <div className="flex gap-2">
998 <button
999 className="bg-blue-500 text-white rounded-sm p-1 px-2"
1000 onClick={() => {
1001 setPendingMs(1000)
1002 setPendingMinMs(500)
1003 }}
1005 Reset to Default
1006 </button>
1007 </div>
1008 <div>
1009 <div>defaultPendingMs: {pendingMs}ms</div>
1010 <input
1011 type="range"
1012 min="0"
1013 max="5000"
1014 step="100"
1015 value={pendingMs}
1016 onChange={(e) => setPendingMs(e.target.valueAsNumber)}
1017 className="w-full"
1018 />
1019 </div>
1020 <div>
1021 <div>defaultPendingMinMs: {pendingMinMs}ms</div>
1022 <input
1023 type="range"
1024 min="0"
1025 max="5000"
1026 step="100"
1027 value={pendingMinMs}
1028 onChange={(e) => setPendingMinMs(e.target.valueAsNumber)}
1029 className="w-full"
1030 />
1031 </div>
1032 </div>
1033 </div>
1034 <QueryClientProvider client={queryClient}>
1035 <RouterProvider
1036 router={router}
1037 defaultPreload="intent"
1038 defaultPendingMs={pendingMs}
1039 defaultPendingMinMs={pendingMinMs}
1040 context={{
1041 auth,
1042 }}
1043 />
1044 </QueryClientProvider>
1045 </>
1048​
1049function InvoiceFields({
1050 invoice,
1051 disabled,
1052}: {
1053 invoice: Invoice
1054 disabled?: boolean
1055}) {
1056 return (
1057 <div className="space-y-2">
1058 <h2 className="font-bold text-lg">
1059 <input
1060 name="title"
1061 defaultValue={invoice.title}
1062 placeholder="Invoice Title"
1063 className="border border-opacity-50 rounded-sm p-2 w-full"
1064 disabled={disabled}
1065 />
1066 </h2>
1067 <div>
1068 <textarea
1069 name="body"
1070 defaultValue={invoice.body}
1071 rows={6}
1072 placeholder="Invoice Body..."
1073 className="border border-opacity-50 p-2 rounded-sm w-full"
1074 disabled={disabled}
1075 />
1076 </div>
1077 </div>
1080​
1081type Auth = {
1082 login: (username: string) => void
1083 logout: () => void
1084 status: 'loggedOut' | 'loggedIn'
1085 username?: string
1087​
1088function Spinner({ show, wait }: { show?: boolean; wait?: `delay-${number}` }) {
1089 return (
1090 <div
1091 className={`inline-block animate-spin px-3 transition ${
1092 (show ?? true)
1093 ? `opacity-100 duration-500 ${wait ?? 'delay-300'}`
1094 : 'duration-500 opacity-0 delay-0'
1095 }`}
1097 β₯
1098 </div>
1101​
1102function useSessionStorage<T>(key: string, initialValue: T) {
1103 const state = React.useState<T>(() => {
1104 const stored = sessionStorage.getItem(key)
1105 return stored ? JSON.parse(stored) : initialValue
1106 })
1107​
1108 React.useEffect(() => {
1109 sessionStorage.setItem(key, JSON.stringify(state[0]))
1110 }, [state[0]])
1111​
1112 return state
1114​
1115const rootElement = document.getElementById('app')!
1116if (!rootElement.innerHTML) {
1117 const root = ReactDOM.createRoot(rootElement)
1118 root.render(
1119 <React.StrictMode>
1120 <App />
1121 </React.StrictMode>,