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