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