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

main.tsx

346 lines8.2 KB

1import React from 'react'
2import ReactDOM from 'react-dom/client'
3import {
4 ErrorComponent,
5 Link,
6 Outlet,
7 RouterProvider,
8 createRootRoute,
9 createRoute,
10 createRouteMask,
11 createRouter,
12 useNavigate,
13 useRouterState,
14} from '@tanstack/react-router'
15import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
16import * as Dialog from '@radix-ui/react-dialog'
17import type { ErrorComponentProps } from '@tanstack/react-router'
18import './styles.css'
19​
20type PhotoType = {
21 id: string
22 title: string
23 url: string
24 thumbnailUrl: string
25 albumId: string
27​
28class NotFoundError extends Error {}
29​
30const fetchPhotos = async () => {
31 console.info('Fetching photos...')
32 await new Promise((r) => setTimeout(r, 500))
33 // Generate mock photos using picsum.photos since via.placeholder.com is down
34 return Array.from({ length: 10 }, (_, i) => ({
35 id: String(i + 1),
36 title: `Photo ${i + 1}`,
37 url: `https://picsum.photos/600/400?random=${i + 1}`,
38 thumbnailUrl: `https://picsum.photos/200/200?random=${i + 1}`,
39 albumId: '1',
40 }))
42​
43const fetchPhoto = async (photoId: string) => {
44 console.info(`Fetching photo with id ${photoId}...`)
45 await new Promise((r) => setTimeout(r, 500))
46​
47 // Simulate photo not found for invalid IDs
48 const photoIdNum = parseInt(photoId, 10)
49 if (isNaN(photoIdNum) || photoIdNum < 1 || photoIdNum > 10) {
50 throw new NotFoundError(`Photo with id "${photoId}" not found!`)
51 }
52​
53 // Generate mock photo using picsum.photos
54 return {
55 id: photoId,
56 title: `Photo ${photoId}`,
57 url: `https://picsum.photos/600/400?random=${photoId}`,
58 thumbnailUrl: `https://picsum.photos/200/200?random=${photoId}`,
59 albumId: '1',
60 }
62​
63type PhotoModal = {
64 id: 'photo'
65 photoId: string
67​
68type ModalObject = PhotoModal
69​
70export function Spinner() {
71 return (
72 <div className="animate-spin px-3 text-xl inline-flex items-center justify-center">
73 β₯
74 </div>
75 )
77​
78const rootRoute = createRootRoute({
79 validateSearch: (search) =>
80 search as {
81 modal?: ModalObject
82 },
83 component: RootComponent,
84})
85​
86function RootComponent() {
87 const status = useRouterState({ select: (s) => s.status })
88​
89 return (
90 <>
91 <div className="p-2 flex gap-2 text-lg">
92 <Link
93 to="/"
94 activeProps={{
95 className: 'font-bold',
96 }}
97 activeOptions={{ exact: true }}
98 >
99 Home
100 </Link>{' '}
101 <Link
102 to="/photos"
103 activeProps={{
104 className: 'font-bold',
105 }}
106 >
107 Photos
108 </Link>{' '}
109 {status === 'pending' ? <Spinner /> : null}
110 </div>
111 <hr />
112 <Outlet />
113 {/* Start rendering router matches */}
114 <TanStackRouterDevtools position="bottom-right" />
115 </>
116 )
118​
119function Modal(props: Dialog.DialogProps) {
120 return (
121 <Dialog.Root open {...props}>
122 <Dialog.Portal>
123 <Dialog.Overlay className="fixed inset-0 bg-black/70" />
124 <Dialog.DialogContent className="fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2">
125 {props.children}
126 </Dialog.DialogContent>
127 </Dialog.Portal>
128 </Dialog.Root>
129 )
131​
132const indexRoute = createRoute({
133 getParentRoute: () => rootRoute,
134 path: '/',
135 component: () => {
136 return (
137 <div className="p-2">
138 <h3>Welcome Home!</h3>
139 </div>
140 )
141 },
142})
143const photosLayoutRoute = createRoute({
144 getParentRoute: () => rootRoute,
145 path: 'photos',
146 loader: fetchPhotos,
147 component: PhotosRoute,
148})
149​
150function PhotosRoute() {
151 const photos = photosLayoutRoute.useLoaderData()
152​
153 return (
154 <div className="p-2 space-y-2">
155 <ul className="grid grid-cols-[repeat(auto-fill,minmax(200px,1fr))] gap-2">
156 {[
157 ...photos,
158 { id: 'i-do-not-exist', title: 'Missing Photo Test', url: '' },
159 ].map((photo) => {
160 return (
161 <li key={photo.id} className="">
162 <Link
163 to={photoModalRoute.to}
164 params={{
165 photoId: photo.id,
166 }}
167 // If you want to use a mask, you can do so like this, but
168 // it's generally safer to set up a route mask instead.
169 // mask={{
170 // to: photoRoute.to,
171 // params: {
172 // photoId: photo.id,
173 // },
174 // }}
175 className="whitespace-nowrap border rounded-lg shadow-xs flex items-center hover:shadow-lg text-blue-600 hover:scale-[1.1] overflow-hidden transition-all"
176 >
177 <img src={photo.url} alt={photo.title} className="max-w-full" />
178 </Link>
179 </li>
180 )
181 })}
182 </ul>
183 <Outlet />
184 </div>
185 )
187​
188const photoRoute = createRoute({
189 getParentRoute: () => rootRoute,
190 path: 'photos/$photoId',
191 loader: async ({ params: { photoId } }) => fetchPhoto(photoId),
192 errorComponent: PhotoErrorComponent,
193 component: PhotoComponent,
194})
195​
196function PhotoErrorComponent({ error }: ErrorComponentProps) {
197 return (
198 <div className="p-4">
199 {(() => {
200 if (error instanceof NotFoundError) {
201 return <div>{error.message}</div>
202 }
203 return <ErrorComponent error={error} />
204 })()}
205 </div>
206 )
208​
209function PhotoComponent() {
210 const photo = photoRoute.useLoaderData()
211​
212 return (
213 <div className="p-4">
214 <Photo photo={photo} />
215 </div>
216 )
218​
219const photoModalRoute = createRoute({
220 getParentRoute: () => photosLayoutRoute,
221 path: '$photoId/modal',
222 loader: async ({ params: { photoId } }) => fetchPhoto(photoId),
223 errorComponent: PhotoModalErrorComponent,
224 // pendingComponent: PhotoModalPendingComponent,
225 component: PhotoModalComponent,
226})
227​
228function PhotoModalErrorComponent({ error }: ErrorComponentProps) {
229 const navigate = useNavigate()
230​
231 return (
232 <Modal
233 onOpenChange={(open) => {
234 if (!open) {
235 navigate({
236 to: photosLayoutRoute.to,
237 })
238 }
239 }}
240 >
241 <div className="bg-gray-100 dark:bg-gray-800 p-2 rounded-lg">
242 {(() => {
243 if (error instanceof NotFoundError) {
244 return <div>{error.message}</div>
245 }
246 return <ErrorComponent error={error} />
247 })()}
248 </div>
249 </Modal>
250 )
252​
253function PhotoModalPendingComponent() {
254 const navigate = useNavigate()
255​
256 return (
257 <Modal
258 onOpenChange={(open) => {
259 if (!open) {
260 navigate({
261 to: photosLayoutRoute.to,
262 })
263 }
264 }}
265 >
266 <div className="bg-gray-100 dark:bg-gray-800 p-2 rounded-lg">
267 <Spinner />
268 </div>
269 </Modal>
270 )
272​
273function PhotoModalComponent() {
274 const navigate = useNavigate()
275 const photo = photoModalRoute.useLoaderData()
276​
277 return (
278 <Modal
279 onOpenChange={(open) => {
280 if (!open) {
281 navigate({
282 to: photosLayoutRoute.to,
283 })
284 }
285 }}
286 >
287 <div className="bg-gray-100 dark:bg-gray-800 p-2 rounded-lg">
288 <Link
289 to="."
290 target="_blank"
291 className="text-blue-600 hover:opacity-75 underline"
292 >
293 Open in new tab (to test de-masking)
294 </Link>
295 <Photo photo={photo} />
296 </div>
297 </Modal>
298 )
300​
301function Photo({ photo }: { photo: PhotoType }) {
302 return (
303 <div className="space-y-2">
304 <h4 className="text-xl font-bold underline">{photo.title}</h4>
305 <div className="">
306 <img src={photo.url} alt={photo.title} className="max-w-full" />
307 </div>
308 </div>
309 )
311​
312const routeTree = rootRoute.addChildren([
313 photoRoute,
314 photosLayoutRoute.addChildren([photoModalRoute]),
315 indexRoute,
316])
317​
318const photoModalToPhotoMask = createRouteMask({
319 routeTree,
320 from: '/photos/$photoId/modal',
321 to: '/photos/$photoId',
322 params: true,
323})
324​
325// Set up a Router instance
326const router = createRouter({
327 routeTree,
328 routeMasks: [photoModalToPhotoMask],
329 defaultPreload: 'intent',
330 scrollRestoration: true,
331})
332​
333// Register things for typesafety
334declare module '@tanstack/react-router' {
335 interface Register {
336 router: typeof router
337 }
339​
340const rootElement = document.getElementById('app')!
341​
342if (!rootElement.innerHTML) {
343 const root = ReactDOM.createRoot(rootElement)
344​
345 root.render(<RouterProvider router={router} />)