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

cases.ts

360 lines10.4 KB

1export const LINK_CASES = [
2 {
3 id: 'shared-params',
4 label: 'Shared string params',
5 description: '200 persistent Links reuse 40 string parameter values.',
6 },
7 {
8 id: 'unique-params',
9 label: 'Unique string params',
10 description: '200 distinct parameter values exceed the 128-result cache.',
11 },
12 {
13 id: 'param-updaters',
14 label: 'Parameter updaters',
15 description: 'Parameter functions derive destinations from current params.',
16 },
17 {
18 id: 'location-updaters',
19 label: 'Search, hash and state updaters',
20 description:
21 'Functions derive search, hash and history state from the source.',
22 },
23 {
24 id: 'relative',
25 label: 'Relative targets',
26 description: 'Parent and child targets inherit current params and search.',
27 },
28 {
29 id: 'middleware',
30 label: 'Search middleware chain',
31 description:
32 'Retain a tenant, strip a default page and normalize a filter.',
33 },
34 {
35 id: 'numeric-params',
36 label: 'Numeric params',
37 description: 'Parse numbers, update them numerically and stringify them.',
38 },
39 {
40 id: 'optional-params',
41 label: 'Optional segments',
42 description: 'Set, inherit and explicitly clear an optional path segment.',
43 },
44 {
45 id: 'splats',
46 label: 'Splat params',
47 description: 'Empty, multi-segment and encoded splat values.',
48 },
49 {
50 id: 'encoding',
51 label: 'Allowed path characters',
52 description: 'Preserve allowed @, : and + while encoding other characters.',
53 },
54 {
55 id: 'masks',
56 label: 'Explicit route masks',
57 description:
58 'Build a different public path and search for each destination.',
59 },
60 {
61 id: 'rewrites',
62 label: 'Basepath and rewrites',
63 description: 'Compose /app with input/output locale path rewrites.',
64 },
65 {
66 id: 'active',
67 label: 'Active props and structured search',
68 description:
69 'Exact, fuzzy and search matching with props and render children.',
70 },
71] as const
72​
73export type LinkCaseId = (typeof LINK_CASES)[number]['id']
74​
75export const LINK_COUNT = 200
76export const NAVIGATION_STATES = [1, 2, 3, 0] as const
77export const LOCALES = ['en', 'fr', 'de', 'es'] as const
78​
79export interface Filter {
80 tag: string
81 flags: { open: boolean }
82 tags: Array<string>
84​
85export interface LinkSearch {
86 page?: number
87 tenant?: string
88 filter?: Filter
90​
91export function sourceFilter(index: number): Filter {
92 return {
93 tag: `group-${index}`,
94 flags: { open: index % 2 === 0 },
95 tags: ['links', `state-${index}`],
96 }
98​
99export function sourceSearch(
100 caseId: LinkCaseId,
101 stateIndex: number,
102): Partial<LinkSearch> {
103 switch (caseId) {
104 case 'location-updaters':
105 case 'relative':
106 case 'middleware':
107 case 'active':
108 return {
109 page: stateIndex + 1,
110 tenant: `tenant-${stateIndex}`,
111 filter: sourceFilter(stateIndex),
112 }
113 case 'rewrites':
114 return { tenant: LOCALES[stateIndex] }
115 default:
116 return {}
117 }
119​
120export function optionalCategory(stateIndex: number) {
121 return stateIndex % 2 === 0 ? `category-${stateIndex}` : undefined
123​
124export function splatValue(index: number) {
125 switch (index % 4) {
126 case 0:
127 return ''
128 case 1:
129 return `folder/sub/file-${index % 40}`
130 case 2:
131 return 'a b/100%/caf\u00e9?#'
132 default:
133 return 'literal%2F/\u{1f680}'
134 }
136​
137export function encodedValue(index: number) {
138 return `user-${index % 40}@mail.test:tag+value /?#% caf\u00e9`
140​
141function url(pathname: string, search: Partial<LinkSearch> = {}, hash = '') {
142 const result = new URL(pathname, 'http://localhost')
143 for (const [key, value] of Object.entries<LinkSearch[keyof LinkSearch]>(
144 search,
145 )) {
146 if (value !== undefined) {
147 result.searchParams.set(
148 key,
149 typeof value === 'object' ? JSON.stringify(value) : String(value),
150 )
151 }
152 }
153 result.hash = hash
154 return result.pathname + result.search + result.hash
156​
157function sourcePath(caseId: LinkCaseId, stateIndex: number) {
158 switch (caseId) {
159 case 'relative':
160 return `/teams/team-${stateIndex}/item-${stateIndex}`
161 case 'numeric-params':
162 return `/numbers/${stateIndex}`
163 case 'optional-params': {
164 const category = optionalCategory(stateIndex)
165 return `/optional/${category ? `${category}/` : ''}item-${stateIndex}`
166 }
167 case 'splats':
168 return `/files/source/state-${stateIndex}`
169 case 'encoding':
170 return `/encoded/source-${stateIndex}`
171 case 'active':
172 return `/items/item-${stateIndex}/details`
173 default:
174 return `/items/item-${stateIndex}`
175 }
177​
178export function getSourceUrl(caseId: LinkCaseId, stateIndex: number): string {
179 if (!Number.isInteger(stateIndex) || stateIndex < 0 || stateIndex > 3) {
180 throw new Error(`Invalid Link performance state: ${stateIndex}`)
181 }
182 const pathname = sourcePath(caseId, stateIndex)
183 if (caseId === 'rewrites') {
184 return `/app/${LOCALES[stateIndex]}${pathname}`
185 }
186 return url(
187 pathname,
188 sourceSearch(caseId, stateIndex),
189 caseId === 'location-updaters' ? `source-${stateIndex}` : '',
190 )
192​
193// These expectations use fixture values and platform encoding, not router APIs.
194function expectedHref(caseId: LinkCaseId, stateIndex: number, index: number) {
195 const itemId = `item-${index % 40}`
196 switch (caseId) {
197 case 'shared-params':
198 return `/items/${itemId}`
199 case 'unique-params':
200 return `/items/item-${index}`
201 case 'param-updaters':
202 return `/items/item-${stateIndex}-related-${index % 40}`
203 case 'location-updaters':
204 return url(
205 `/items/item-${stateIndex}`,
206 {
207 ...sourceSearch(caseId, stateIndex),
208 page: stateIndex + 2 + (index % 5),
209 },
210 `source-${stateIndex}-link-${index % 5}`,
211 )
212 case 'relative':
213 return url(
214 index % 2 === 0
215 ? `/teams/team-${stateIndex}`
216 : `/teams/team-${stateIndex}/item-${stateIndex}/details`,
217 sourceSearch(caseId, stateIndex),
218 )
219 case 'middleware':
220 return url(`/filtered/${itemId}`, {
221 tenant: `tenant-${stateIndex}`,
222 page: index % 2 === 0 ? undefined : 2,
223 filter: { ...sourceFilter(index % 4), tag: `LABEL-${index % 40}` },
224 })
225 case 'numeric-params':
226 return `/numbers/${stateIndex + (index % 40)}`
227 case 'optional-params': {
228 const category =
229 index % 3 === 0
230 ? 'fixed'
231 : index % 3 === 1
232 ? optionalCategory(stateIndex)
233 : undefined
234 return `/optional/${category ? `${category}/` : ''}${itemId}`
235 }
236 case 'splats': {
237 const value = splatValue(index)
238 return `/files${value ? `/${value.split('/').map(encodeURIComponent).join('/')}` : ''}`
239 }
240 case 'encoding': {
241 const value = encodeURIComponent(encodedValue(index))
242 .replaceAll('%40', '@')
243 .replaceAll('%3A', ':')
244 .replaceAll('%2B', '+')
245 return `/encoded/${value}`
246 }
247 case 'masks':
248 return url(`/public/display-${index % 40}`, {
249 tenant: `mask-${index % 4}`,
250 })
251 case 'rewrites':
252 return url(`/app/${LOCALES[index % 4]}/items/${itemId}`, {
253 page: (index % 3) + 1,
254 })
255 case 'active': {
256 const item = Math.floor(index / 5)
257 const variant = index % 5
258 const search =
259 variant < 3
260 ? { filter: sourceFilter(item % 4) }
261 : {
262 ...sourceSearch('active', item % 4),
263 ...(variant === 4 ? { filter: undefined } : {}),
264 }
265 return url(`/items/item-${item}${variant < 2 ? '' : '/details'}`, search)
266 }
267 }
269​
270function assertUrl(
271 actualHref: string | null,
272 expectedHref: string,
273 label: string,
274) {
275 if (actualHref === null) {
276 throw new Error(`${label}: missing href`)
277 }
278 const actual = new URL(actualHref, 'http://localhost')
279 const expected = new URL(expectedHref, 'http://localhost')
280 // Query ordering and the platform's '+' versus '%20' are immaterial here.
281 const query = (value: URL) =>
282 JSON.stringify([...value.searchParams.entries()].sort())
283 if (
284 actual.origin !== expected.origin ||
285 actual.pathname !== expected.pathname ||
286 actual.hash !== expected.hash ||
287 query(actual) !== query(expected)
288 ) {
289 throw new Error(
290 `${label}: expected ${expectedHref}, received ${actualHref}`,
291 )
292 }
294​
295export function assertScenario(
296 caseId: LinkCaseId,
297 stateIndex: number,
298 root: ParentNode,
299): void {
300 const source = root.querySelector('[data-testid="source-path"]')
301 if (source?.textContent !== sourcePath(caseId, stateIndex)) {
302 throw new Error(
303 `${caseId}/${stateIndex}: unexpected source path ${source?.textContent}`,
304 )
305 }
306 const links = root.querySelectorAll<HTMLAnchorElement>('a[data-perf-link]')
307 if (links.length !== LINK_COUNT) {
308 throw new Error(
309 `${caseId}: expected ${LINK_COUNT} Links, got ${links.length}`,
310 )
311 }
312 for (const [index, link] of links.entries()) {
313 const label = `${caseId}/${stateIndex}/link-${index}`
314 if (link.getAttribute('data-perf-link') !== String(index)) {
315 throw new Error(`${label}: unexpected Link order`)
316 }
317 assertUrl(
318 link.getAttribute('href'),
319 expectedHref(caseId, stateIndex, index),
320 label,
321 )
322 let active: boolean | undefined
323 if (caseId === 'shared-params') {
324 active = index % 40 === stateIndex
325 } else if (caseId === 'unique-params') {
326 active = index === stateIndex
327 } else if (caseId === 'active') {
328 active =
329 Math.floor(index / 5) === stateIndex && [0, 2, 3].includes(index % 5)
330 if (
331 link.textContent !== `${index}:${active ? 'active' : 'inactive'}` ||
332 link.getAttribute('title') !== (active ? 'active' : 'inactive') ||
333 !link.classList.contains(active ? 'perf-active' : 'perf-inactive') ||
334 link.style.color !== (active ? 'green' : 'gray') ||
335 link.style.opacity !== '0.8'
336 ) {
337 throw new Error(
338 `${label}: active props or render children are incorrect`,
339 )
340 }
341 }
342 if (
343 active !== undefined &&
344 (link.getAttribute('data-status') === 'active') !== active
345 ) {
346 throw new Error(`${label}: expected active=${active}`)
347 }
348 }
349 for (let state = 0; state < 4; state++) {
350 const control = root.querySelector(`[data-testid="go-state-${state}"]`)
351 if (!control || control.hasAttribute('data-perf-link')) {
352 throw new Error(`${caseId}: missing or measured control Link ${state}`)
353 }
354 assertUrl(
355 control.getAttribute('href'),
356 getSourceUrl(caseId, state),
357 `${caseId}/control-${state}`,
358 )
359 }