Open History to see the last commit
1import {
2 Link,
3 Outlet,
4 createRootRouteWithContext,
5 createRoute,
6 createRouter,
7 linkOptions,
8 retainSearchParams,
9 stripSearchParams,
10 useLocation,
11} from '@tanstack/react-router'
12import {
13 LINK_COUNT,
14 LOCALES,
15 encodedValue,
16 optionalCategory,
17 sourceFilter,
18 sourceSearch,
19 splatValue,
20} from '../cases'
21import type { RouterHistory } from '@tanstack/history'
22import type { SearchSchemaInput } from '@tanstack/react-router'
23import type { Filter, LinkCaseId, LinkSearch } from '../cases'
24β
25interface StateUpdates {
26 calls: number
27 verifiedCalls: number
28 input: number
29 output: number
30 offset: number
31}
32β
33interface WorkloadContext {
34 caseId: LinkCaseId
35 stateUpdates: StateUpdates
36}
37β
38function isFilter(value: unknown): value is Filter {
39 return (
40 typeof value === 'object' &&
41 value !== null &&
42 'tag' in value &&
43 typeof value.tag === 'string' &&
44 'flags' in value &&
45 typeof value.flags === 'object' &&
46 value.flags !== null &&
47 'open' in value.flags &&
48 typeof value.flags.open === 'boolean' &&
49 'tags' in value &&
50 Array.isArray(value.tags) &&
51 value.tags.every((tag: unknown) => typeof tag === 'string')
52 )
53}
54β
55const rootRoute = createRootRouteWithContext<WorkloadContext>()({
56 validateSearch: (
57 search: Record<string, unknown> & SearchSchemaInput,
58 ): LinkSearch => ({
59 page: typeof search.page === 'number' ? search.page : undefined,
60 tenant: typeof search.tenant === 'string' ? search.tenant : undefined,
61 filter: isFilter(search.filter) ? search.filter : undefined,
62 }),
63 component: RootLayout,
64})
65β
66const itemsRoute = createRoute({
67 getParentRoute: () => rootRoute,
68 path: 'items/$itemId',
69})
70const detailsRoute = createRoute({
71 getParentRoute: () => itemsRoute,
72 path: 'details',
73})
74const teamRoute = createRoute({
75 getParentRoute: () => rootRoute,
76 path: 'teams/$teamId',
77})
78const teamItemRoute = createRoute({
79 getParentRoute: () => teamRoute,
80 path: '$itemId',
81})
82const teamDetailsRoute = createRoute({
83 getParentRoute: () => teamItemRoute,
84 path: 'details',
85})
86const filteredRoute = createRoute({
87 getParentRoute: () => rootRoute,
88 path: 'filtered/$itemId',
89 search: {
90 middlewares: [
91 retainSearchParams<LinkSearch>(['tenant']),
92 stripSearchParams<LinkSearch>({ page: 1 }),
93 ({ search, next }) => {
94 const result = next(search)
95 return {
96 ...result,
97 filter: result.filter
98 ? { ...result.filter, tag: result.filter.tag.trim().toUpperCase() }
99 : undefined,
100 }
101 },
102 ],
103 },
104})
105const numericRoute = createRoute({
106 getParentRoute: () => rootRoute,
107 path: 'numbers/$number',
108 params: {
109 parse: ({ number }) => {
110 const value = Number(number)
111 if (!Number.isFinite(value)) {
112 throw new Error(`Invalid number: ${number}`)
113 }
114 return { number: value }
115 },
116 stringify: ({ number }) => ({ number: String(number) }),
117 },
118})
119const optionalRoute = createRoute({
120 getParentRoute: () => rootRoute,
121 path: 'optional/{-$category}/$itemId',
122})
123const splatRoute = createRoute({
124 getParentRoute: () => rootRoute,
125 path: 'files/$',
126})
127const encodedRoute = createRoute({
128 getParentRoute: () => rootRoute,
129 path: 'encoded/$value',
130})
131const publicRoute = createRoute({
132 getParentRoute: () => rootRoute,
133 path: 'public/$itemId',
134})
135β
136const routeTree = rootRoute.addChildren([
137 itemsRoute.addChildren([detailsRoute]),
138 teamRoute.addChildren([teamItemRoute.addChildren([teamDetailsRoute])]),
139 filteredRoute,
140 numericRoute,
141 optionalRoute,
142 splatRoute,
143 encodedRoute,
144 publicRoute,
145])
146β
147const localeRewrite = {
148 input: ({ url }: { url: URL }) => {
149 const match = /^\/(en|fr|de|es)(\/.*)$/.exec(url.pathname)
150 if (match) {
151 url.pathname = match[2]!
152 url.searchParams.set('tenant', match[1]!)
153 }
154 return url
155 },
156 output: ({ url }: { url: URL }) => {
157 const locale = url.searchParams.get('tenant')
158 if (locale) {
159 url.searchParams.delete('tenant')
160 url.pathname = `/${locale}${url.pathname}`
161 }
162 return url
163 },
164}
165β
166export function createLinkRouter(
167 caseId: LinkCaseId,
168 history: RouterHistory,
169 isServer: boolean,
170) {
171 const context: WorkloadContext = {
172 caseId,
173 stateUpdates: {
174 calls: 0,
175 verifiedCalls: 0,
176 input: 0,
177 output: 0,
178 offset: 0,
179 },
180 }
181 return createRouter({
182 routeTree,
183 history,
184 isServer,
185 context,
186 scrollRestoration: false,
187 defaultPreload: false,
188 trailingSlash: 'never',
189 pathParamsAllowedCharacters:
190 caseId === 'encoding' ? ['@', ':', '+'] : undefined,
191 ...(caseId === 'rewrites'
192 ? { basepath: '/app', rewrite: localeRewrite }
193 : {}),
194 })
195}
196β
197export type LinkRouter = ReturnType<typeof createLinkRouter>
198β
199declare module '@tanstack/react-router' {
200 interface Register {
201 router: LinkRouter
202 }
203}
204β
205declare module '@tanstack/history' {
206 interface HistoryState {
207 linkPerfState?: number
208 }
209}
210β
211// Call alongside DOM assertions, outside the timed loop, after each sample.
212export function assertStateUpdates(router: LinkRouter): void {
213 const { caseId, stateUpdates } = router.options.context
214 if (caseId !== 'location-updaters') {
215 return
216 }
217 const input = router.state.location.state.linkPerfState ?? 0
218 if (
219 stateUpdates.calls - stateUpdates.verifiedCalls < LINK_COUNT ||
220 stateUpdates.input !== input ||
221 stateUpdates.output !== input + stateUpdates.offset ||
222 stateUpdates.offset < 1 ||
223 stateUpdates.offset > 40
224 ) {
225 throw new Error(
226 'Link history-state updaters did not run with current state',
227 )
228 }
229 stateUpdates.verifiedCalls = stateUpdates.calls
230}
231β
232function sourceOptions(caseId: LinkCaseId, stateIndex: number) {
233 const itemId = `item-${stateIndex}`
234 const common = {
235 search: sourceSearch(caseId, stateIndex),
236 hash: caseId === 'location-updaters' ? `source-${stateIndex}` : '',
237 state: { linkPerfState: stateIndex + 10 },
238 }
239 switch (caseId) {
240 case 'relative':
241 return linkOptions({
242 ...common,
243 to: '/teams/$teamId/$itemId',
244 params: { teamId: `team-${stateIndex}`, itemId },
245 })
246 case 'numeric-params':
247 return linkOptions({
248 ...common,
249 to: '/numbers/$number',
250 params: { number: stateIndex },
251 })
252 case 'optional-params':
253 return linkOptions({
254 ...common,
255 to: '/optional/{-$category}/$itemId',
256 params: { category: optionalCategory(stateIndex), itemId },
257 })
258 case 'splats':
259 return linkOptions({
260 ...common,
261 to: '/files/$',
262 params: { _splat: `source/state-${stateIndex}` },
263 })
264 case 'encoding':
265 return linkOptions({
266 ...common,
267 to: '/encoded/$value',
268 params: { value: `source-${stateIndex}` },
269 })
270 case 'active':
271 return linkOptions({
272 ...common,
273 to: '/items/$itemId/details',
274 params: { itemId },
275 })
276 default:
277 return linkOptions({
278 ...common,
279 to: '/items/$itemId',
280 params: { itemId },
281 })
282 }
283}
284β
285const indexes = Array.from({ length: LINK_COUNT }, (_, index) => index)
286const controls = [0, 1, 2, 3] as const
287β
288function SourcePath() {
289 const pathname = useLocation({ select: (location) => location.pathname })
290 return <span data-testid="source-path">{pathname}</span>
291}
292β
293function RootLayout() {
294 const context = rootRoute.useRouteContext()
295 return (
296 <>
297 <nav>
298 {controls.map((stateIndex) => (
299 <Link
300 key={stateIndex}
301 {...sourceOptions(context.caseId, stateIndex)}
302 replace
303 preload={false}
304 resetScroll={false}
305 hashScrollIntoView={false}
306 data-testid={`go-state-${stateIndex}`}
307 >
308 State {stateIndex}
309 </Link>
310 ))}
311 </nav>
312 <SourcePath />
313 <section aria-label="Measured Links">
314 {indexes.map((index) => measuredLink(context, index))}
315 </section>
316 <Outlet />
317 </>
318 )
319}
320β
321function measuredLink(
322 { caseId, stateUpdates }: WorkloadContext,
323 index: number,
324) {
325 const common = {
326 key: index,
327 'data-perf-link': index,
328 preload: false,
329 children: `Link ${index}`,
330 } as const
331 const itemId = `item-${index % 40}`
332 switch (caseId) {
333 case 'shared-params':
334 case 'unique-params':
335 return (
336 <Link
337 {...common}
338 to="/items/$itemId"
339 params={{
340 itemId: caseId === 'unique-params' ? `item-${index}` : itemId,
341 }}
342 />
343 )
344 case 'param-updaters':
345 return (
346 <Link
347 {...common}
348 from="/items/$itemId"
349 to="."
350 params={(previous) => ({
351 itemId: `${previous.itemId}-related-${index % 40}`,
352 })}
353 />
354 )
355 case 'location-updaters':
356 return (
357 <Link
358 {...common}
359 from="/items/$itemId"
360 to="."
361 params
362 search={(previous) => ({
363 ...previous,
364 page: (previous.page ?? 1) + 1 + (index % 5),
365 })}
366 hash={(previous) => `${previous}-link-${index % 5}`}
367 state={(previous) => {
368 const input = previous.linkPerfState ?? 0
369 const offset = (index % 40) + 1
370 const output = input + offset
371 stateUpdates.calls++
372 stateUpdates.input = input
373 stateUpdates.output = output
374 stateUpdates.offset = offset
375 return { ...previous, linkPerfState: output }
376 }}
377 />
378 )
379 case 'relative':
380 return (
381 <Link
382 {...common}
383 from="/teams/$teamId/$itemId"
384 to={index % 2 === 0 ? '..' : './details'}
385 params
386 search
387 />
388 )
389 case 'middleware':
390 return (
391 <Link
392 {...common}
393 to="/filtered/$itemId"
394 params={{ itemId }}
395 search={{
396 page: index % 2 === 0 ? 1 : 2,
397 filter: {
398 ...sourceFilter(index % 4),
399 tag: ` label-${index % 40} `,
400 },
401 }}
402 />
403 )
404 case 'numeric-params':
405 return (
406 <Link
407 {...common}
408 from="/numbers/$number"
409 to="."
410 params={(previous) => ({ number: previous.number + (index % 40) })}
411 />
412 )
413 case 'optional-params':
414 return (
415 <Link
416 {...common}
417 from="/optional/{-$category}/$itemId"
418 to="."
419 params={
420 index % 3 === 0
421 ? { itemId, category: 'fixed' }
422 : index % 3 === 1
423 ? { itemId }
424 : { itemId, category: undefined }
425 }
426 />
427 )
428 case 'splats':
429 return (
430 <Link
431 {...common}
432 to="/files/$"
433 params={{ _splat: splatValue(index) }}
434 />
435 )
436 case 'encoding':
437 return (
438 <Link
439 {...common}
440 to="/encoded/$value"
441 params={{ value: encodedValue(index) }}
442 />
443 )
444 case 'masks':
445 return (
446 <Link
447 {...common}
448 to="/items/$itemId"
449 params={{ itemId }}
450 search={{ page: 2 }}
451 mask={{
452 to: '/public/$itemId',
453 params: { itemId: `display-${index % 40}` },
454 search: { tenant: `mask-${index % 4}` },
455 }}
456 />
457 )
458 case 'rewrites':
459 return (
460 <Link
461 {...common}
462 to="/items/$itemId"
463 params={{ itemId }}
464 search={{ tenant: LOCALES[index % 4], page: (index % 3) + 1 }}
465 />
466 )
467 case 'active': {
468 const item = Math.floor(index / 5)
469 const variant = index % 5
470 return (
471 <Link
472 {...common}
473 to={variant < 2 ? '/items/$itemId' : '/items/$itemId/details'}
474 params={{ itemId: `item-${item}` }}
475 search={
476 variant < 3
477 ? { filter: sourceFilter(item % 4) }
478 : {
479 ...sourceSearch('active', item % 4),
480 ...(variant === 4 ? { filter: undefined } : {}),
481 }
482 }
483 activeOptions={{
484 exact: variant === 1 || variant === 2 || variant === 3,
485 includeSearch: variant !== 2,
486 explicitUndefined: variant === 4,
487 }}
488 className="perf-link"
489 style={{ color: 'black', opacity: 0.8 }}
490 activeProps={() => ({
491 className: 'perf-active',
492 title: 'active',
493 style: { color: 'green' },
494 })}
495 inactiveProps={() => ({
496 className: 'perf-inactive',
497 title: 'inactive',
498 style: { color: 'gray' },
499 })}
500 >
501 {({ isActive }) => `${index}:${isActive ? 'active' : 'inactive'}`}
502 </Link>
503 )
504 }
505 }
506}