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