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

app.tsx

367 lines9.3 KB

1import { For, createRenderEffect } from 'solid-js'
2import { render } from 'solid-js/web'
3import {
4 Link,
5 Outlet,
6 RouterProvider,
7 createMemoryHistory,
8 createRootRoute,
9 createRoute,
10 createRouter,
11 useParams,
12 useSearch,
13} from '@tanstack/solid-router'
14​
15function runPerfSelectorComputation(seed: number) {
16 let value = Math.trunc(seed) | 0
17​
18 for (let index = 0; index < 40; index++) {
19 value = (value * 1664525 + 1013904223 + index) >>> 0
20 }
21​
22 return value
24​
25function normalizePage(value: unknown) {
26 const page = Number(value)
27 return Number.isFinite(page) && page > 0 ? Math.trunc(page) : 1
29​
30function normalizeFilter(value: unknown) {
31 return typeof value === 'string' && value.length > 0 ? value : 'all'
33​
34const noop = () => {}
35const rootSelectors = Array.from({ length: 10 }, (_, index) => index)
36const routeSelectors = Array.from({ length: 6 }, (_, index) => index)
37const linkGroups = Array.from({ length: 4 }, (_, index) => index)
38​
39function PerfValue(props: { value: () => number }) {
40 createRenderEffect(() => {
41 void props.value()
42 })
43​
44 return null
46​
47function RootParamsSubscriber() {
48 const params = useParams({
49 strict: false,
50 select: (params) => runPerfSelectorComputation(Number(params.id ?? 0)),
51 })
52​
53 return <PerfValue value={() => runPerfSelectorComputation(params())} />
55​
56function RootSearchSubscriber() {
57 const search = useSearch({
58 strict: false,
59 select: (search) => runPerfSelectorComputation(Number(search.page ?? 0)),
60 })
61​
62 return <PerfValue value={() => runPerfSelectorComputation(search())} />
64​
65function LinkPanel() {
66 return (
67 <>
68 <For each={linkGroups}>
69 {(groupIndex) => {
70 const itemsId = groupIndex === 0 ? 1 : groupIndex + 2
71 const ctxId = groupIndex + 1
72​
73 return (
74 <div>
75 <Link
76 data-testid={groupIndex === 0 ? 'go-items-1' : undefined}
77 to="/items/$id"
78 params={{ id: itemsId }}
79 replace
80 activeOptions={{ exact: true }}
81 activeProps={{ class: 'active-link' }}
82 inactiveProps={{ class: 'inactive-link' }}
83 >
84 {`Items ${itemsId}`}
85 </Link>
86 <Link
87 data-testid={groupIndex === 0 ? 'go-items-2' : undefined}
88 to="/items/$id"
89 params={{ id: 2 }}
90 replace
91 activeOptions={{ includeSearch: false }}
92 >
93 {`Items 2 alt ${groupIndex}`}
94 </Link>
95 <Link
96 data-testid={groupIndex === 0 ? 'go-search' : undefined}
97 to="/search"
98 search={{ page: 1, filter: 'all', junk: `group-${groupIndex}` }}
99 replace
100 activeOptions={{ includeSearch: true }}
101 activeProps={{ class: 'active-link' }}
102 inactiveProps={{ class: 'inactive-link' }}
103 >
104 {`Search ${groupIndex}`}
105 </Link>
106 <Link
107 data-testid={groupIndex === 0 ? 'go-ctx' : undefined}
108 to="/ctx/$id"
109 params={{ id: ctxId }}
110 search={true}
111 replace
112 activeOptions={{ includeSearch: false }}
113 >
114 {`Context ${ctxId}`}
115 </Link>
116 <Link
117 from={searchRoute.fullPath}
118 to="/search"
119 search={(prev: { page: number; filter: string }) => ({
120 page: prev.page + groupIndex + 1,
121 filter: prev.filter,
122 junk: `updater-${groupIndex}`,
123 })}
124 activeOptions={{ includeSearch: true }}
125 >
126 {({ isActive }) =>
127 isActive
128 ? `Search updater active ${groupIndex}`
129 : `Search updater inactive ${groupIndex}`
130 }
131 </Link>
132 </div>
133 )
134 }}
135 </For>
136 </>
137 )
139​
140function Root() {
141 return (
142 <>
143 <For each={rootSelectors}>{() => <RootParamsSubscriber />}</For>
144 <For each={rootSelectors}>{() => <RootSearchSubscriber />}</For>
145 <LinkPanel />
146 <Outlet />
147 </>
148 )
150​
151const rootRoute = createRootRoute({
152 component: Root,
153})
154​
155const itemsRoute = createRoute({
156 getParentRoute: () => rootRoute,
157 path: '/items/$id',
158 params: {
159 parse: (params) => ({
160 ...params,
161 id: normalizePage(params.id),
162 }),
163 stringify: (params) => ({
164 ...params,
165 id: `${params.id}`,
166 }),
167 },
168 onEnter: noop,
169 onStay: noop,
170 onLeave: noop,
171 component: ItemsPage,
172})
173​
174const itemDetailsRoute = createRoute({
175 getParentRoute: () => itemsRoute,
176 path: 'details',
177 component: ItemDetailsPage,
178})
179​
180const searchRoute = createRoute({
181 getParentRoute: () => rootRoute,
182 path: '/search',
183 validateSearch: (search: Record<string, unknown>) => ({
184 page: normalizePage(search.page),
185 filter: normalizeFilter(search.filter),
186 }),
187 search: {
188 middlewares: [
189 ({ search, next }) => {
190 const result = next(search)
191 return {
192 page: result.page,
193 filter: result.filter,
194 }
195 },
196 ],
197 },
198 loaderDeps: ({ search }) => ({
199 page: search.page,
200 filter: search.filter,
201 }),
202 loader: ({ deps }) => ({
203 seed: deps.page * 31 + deps.filter.length,
204 checksum: deps.page * 17 + deps.filter.length,
205 }),
206 staleTime: 60_000,
207 gcTime: 60_000,
208 component: SearchPage,
209})
210​
211const contextRoute = createRoute({
212 getParentRoute: () => rootRoute,
213 path: '/ctx/$id',
214 beforeLoad: ({ params }) => ({
215 sectionSeed: Number(params.id) * 13 + 1,
216 }),
217 component: ContextPage,
218})
219​
220function ItemParamsSubscriber() {
221 const params = itemsRoute.useParams({
222 select: (params) => runPerfSelectorComputation(params.id),
223 })
224​
225 return <PerfValue value={() => runPerfSelectorComputation(params())} />
227​
228function SearchStateSubscriber() {
229 const search = searchRoute.useSearch({
230 select: (search) =>
231 runPerfSelectorComputation(search.page + search.filter.length),
232 })
233​
234 return <PerfValue value={() => runPerfSelectorComputation(search())} />
236​
237function SearchLoaderDepsSubscriber() {
238 const loaderDeps = searchRoute.useLoaderDeps({
239 select: (loaderDeps) =>
240 runPerfSelectorComputation(loaderDeps.page + loaderDeps.filter.length),
241 })
242​
243 return <PerfValue value={() => runPerfSelectorComputation(loaderDeps())} />
245​
246function SearchLoaderDataSubscriber() {
247 const loaderData = searchRoute.useLoaderData({
248 select: (loaderData) =>
249 runPerfSelectorComputation(loaderData.seed + loaderData.checksum),
250 })
251​
252 return <PerfValue value={() => runPerfSelectorComputation(loaderData())} />
254​
255function ContextParamsSubscriber() {
256 const params = contextRoute.useParams({
257 select: (params) => runPerfSelectorComputation(Number(params.id)),
258 })
259​
260 return <PerfValue value={() => runPerfSelectorComputation(params())} />
262​
263function ContextRouteSubscriber() {
264 const context = contextRoute.useRouteContext({
265 select: (context) => runPerfSelectorComputation(context.sectionSeed),
266 })
267​
268 return <PerfValue value={() => runPerfSelectorComputation(context())} />
270​
271function ItemsPage() {
272 return (
273 <>
274 <For each={routeSelectors}>{() => <ItemParamsSubscriber />}</For>
275 <Link
276 data-testid="items-details"
277 from={itemsRoute.fullPath}
278 to="./details"
279 replace
280 >
281 Details
282 </Link>
283 <Link
284 from={itemsRoute.fullPath}
285 to="."
286 search={true}
287 activeOptions={{ includeSearch: true }}
288 >
289 Preserve search on item
290 </Link>
291 <Outlet />
292 </>
293 )
295​
296function ItemDetailsPage() {
297 return (
298 <>
299 <For each={routeSelectors}>{() => <ItemParamsSubscriber />}</For>
300 <Link
301 data-testid="items-parent"
302 from={itemDetailsRoute.fullPath}
303 to=".."
304 replace
305 activeOptions={{ exact: true }}
306 >
307 Back to item
308 </Link>
309 </>
310 )
312​
313function SearchPage() {
314 return (
315 <>
316 <For each={routeSelectors}>{() => <SearchStateSubscriber />}</For>
317 <For each={routeSelectors}>{() => <SearchLoaderDepsSubscriber />}</For>
318 <For each={routeSelectors}>{() => <SearchLoaderDataSubscriber />}</For>
319 <Link
320 data-testid="search-next-page"
321 from={searchRoute.fullPath}
322 to="."
323 replace
324 search={(prev: { page: number; filter: string }) => ({
325 page: prev.page + 1,
326 filter: prev.filter,
327 junk: 'local-updater',
328 })}
329 activeOptions={{ includeSearch: true }}
330 activeProps={{ class: 'active-link' }}
331 inactiveProps={{ class: 'inactive-link' }}
332 >
333 Next page
334 </Link>
335 </>
336 )
338​
339function ContextPage() {
340 return (
341 <>
342 <For each={routeSelectors}>{() => <ContextParamsSubscriber />}</For>
343 <For each={routeSelectors}>{() => <ContextRouteSubscriber />}</For>
344 </>
345 )
347​
348export function mountTestApp(container: Element) {
349 const router = createRouter({
350 history: createMemoryHistory({
351 initialEntries: ['/items/0'],
352 }),
353 scrollRestoration: true,
354 routeTree: rootRoute.addChildren([
355 itemsRoute.addChildren([itemDetailsRoute]),
356 searchRoute,
357 contextRoute,
358 ]),
359 })
360​
361 const unmount = render(() => <RouterProvider router={router} />, container)
362​
363 return {
364 router,
365 unmount,
366 }