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

process-route-tree.ts

241 lines6.8 KB

1import invariant from 'tiny-invariant'
2import {
3 SEGMENT_TYPE_OPTIONAL_PARAM,
4 SEGMENT_TYPE_PARAM,
5 SEGMENT_TYPE_PATHNAME,
6 parsePathname,
7 trimPathLeft,
8 trimPathRight,
9} from './path'
10import type { Segment } from './path'
11import type { RouteLike } from './route'
12​
13const SLASH_SCORE = 0.75
14const STATIC_SEGMENT_SCORE = 1
15const REQUIRED_PARAM_BASE_SCORE = 0.5
16const OPTIONAL_PARAM_BASE_SCORE = 0.4
17const WILDCARD_PARAM_BASE_SCORE = 0.25
18const STATIC_AFTER_DYNAMIC_BONUS_SCORE = 0.2
19const BOTH_PRESENCE_BASE_SCORE = 0.05
20const PREFIX_PRESENCE_BASE_SCORE = 0.02
21const SUFFIX_PRESENCE_BASE_SCORE = 0.01
22const PREFIX_LENGTH_SCORE_MULTIPLIER = 0.0002
23const SUFFIX_LENGTH_SCORE_MULTIPLIER = 0.0001
24​
25function handleParam(segment: Segment, baseScore: number) {
26 if (segment.prefixSegment && segment.suffixSegment) {
27 return (
28 baseScore +
29 BOTH_PRESENCE_BASE_SCORE +
30 PREFIX_LENGTH_SCORE_MULTIPLIER * segment.prefixSegment.length +
31 SUFFIX_LENGTH_SCORE_MULTIPLIER * segment.suffixSegment.length
32 )
33 }
34​
35 if (segment.prefixSegment) {
36 return (
37 baseScore +
38 PREFIX_PRESENCE_BASE_SCORE +
39 PREFIX_LENGTH_SCORE_MULTIPLIER * segment.prefixSegment.length
40 )
41 }
42​
43 if (segment.suffixSegment) {
44 return (
45 baseScore +
46 SUFFIX_PRESENCE_BASE_SCORE +
47 SUFFIX_LENGTH_SCORE_MULTIPLIER * segment.suffixSegment.length
48 )
49 }
50​
51 return baseScore
53​
54function sortRoutes<TRouteLike extends RouteLike>(
55 routes: ReadonlyArray<TRouteLike>,
56): Array<TRouteLike> {
57 const scoredRoutes: Array<{
58 child: TRouteLike
59 trimmed: string
60 parsed: ReadonlyArray<Segment>
61 index: number
62 scores: Array<number>
63 hasStaticAfter: boolean
64 optionalParamCount: number
65 }> = []
66​
67 routes.forEach((d, i) => {
68 if (d.isRoot || !d.path) {
69 return
70 }
71​
72 const trimmed = trimPathLeft(d.fullPath)
73 let parsed = parsePathname(trimmed)
74​
75 // Removes the leading slash if it is not the only remaining segment
76 let skip = 0
77 while (parsed.length > skip + 1 && parsed[skip]?.value === '/') {
78 skip++
79 }
80 if (skip > 0) parsed = parsed.slice(skip)
81​
82 let optionalParamCount = 0
83 let hasStaticAfter = false
84 const scores = parsed.map((segment, index) => {
85 if (segment.value === '/') {
86 return SLASH_SCORE
87 }
88​
89 if (segment.type === SEGMENT_TYPE_PATHNAME) {
90 return STATIC_SEGMENT_SCORE
91 }
92​
93 let baseScore: number | undefined = undefined
94 if (segment.type === SEGMENT_TYPE_PARAM) {
95 baseScore = REQUIRED_PARAM_BASE_SCORE
96 } else if (segment.type === SEGMENT_TYPE_OPTIONAL_PARAM) {
97 baseScore = OPTIONAL_PARAM_BASE_SCORE
98 optionalParamCount++
99 } else {
100 baseScore = WILDCARD_PARAM_BASE_SCORE
101 }
102​
103 // if there is any static segment (that is not an index) after a required / optional param,
104 // we will boost this param so it ranks higher than a required/optional param without a static segment after it
105 // JUST FOR SORTING, NOT FOR MATCHING
106 for (let i = index + 1; i < parsed.length; i++) {
107 const nextSegment = parsed[i]!
108 if (
109 nextSegment.type === SEGMENT_TYPE_PATHNAME &&
110 nextSegment.value !== '/'
111 ) {
112 hasStaticAfter = true
113 return handleParam(
114 segment,
115 baseScore + STATIC_AFTER_DYNAMIC_BONUS_SCORE,
116 )
117 }
118 }
119​
120 return handleParam(segment, baseScore)
121 })
122​
123 scoredRoutes.push({
124 child: d,
125 trimmed,
126 parsed,
127 index: i,
128 scores,
129 optionalParamCount,
130 hasStaticAfter,
131 })
132 })
133​
134 const flatRoutes = scoredRoutes
135 .sort((a, b) => {
136 const minLength = Math.min(a.scores.length, b.scores.length)
137​
138 // Sort by segment-by-segment score comparison ONLY for the common prefix
139 for (let i = 0; i < minLength; i++) {
140 if (a.scores[i] !== b.scores[i]) {
141 return b.scores[i]! - a.scores[i]!
142 }
143 }
144​
145 // If all common segments have equal scores, then consider length and specificity
146 if (a.scores.length !== b.scores.length) {
147 // If different number of optional parameters, fewer optional parameters wins (more specific)
148 // only if both or none of the routes has static segments after the params
149 if (a.optionalParamCount !== b.optionalParamCount) {
150 if (a.hasStaticAfter === b.hasStaticAfter) {
151 return a.optionalParamCount - b.optionalParamCount
152 } else if (a.hasStaticAfter && !b.hasStaticAfter) {
153 return -1
154 } else if (!a.hasStaticAfter && b.hasStaticAfter) {
155 return 1
156 }
157 }
158​
159 // If same number of optional parameters, longer path wins (for static segments)
160 return b.scores.length - a.scores.length
161 }
162​
163 // Sort by min available parsed value for alphabetical ordering
164 for (let i = 0; i < minLength; i++) {
165 if (a.parsed[i]!.value !== b.parsed[i]!.value) {
166 return a.parsed[i]!.value > b.parsed[i]!.value ? 1 : -1
167 }
168 }
169​
170 // Sort by original index
171 return a.index - b.index
172 })
173 .map((d, i) => {
174 d.child.rank = i
175 return d.child
176 })
177​
178 return flatRoutes
180​
181export type ProcessRouteTreeResult<TRouteLike extends RouteLike> = {
182 routesById: Record<string, TRouteLike>
183 routesByPath: Record<string, TRouteLike>
184 flatRoutes: Array<TRouteLike>
186​
187/**
188 * Build lookup maps and a specificity-sorted flat list from a route tree.
189 * Returns `routesById`, `routesByPath`, and `flatRoutes`.
190 */
191/**
192 * Build lookup maps and a specificity-sorted flat list from a route tree.
193 * Returns `routesById`, `routesByPath`, and `flatRoutes`.
194 */
195export function processRouteTree<TRouteLike extends RouteLike>({
196 routeTree,
197 initRoute,
198}: {
199 routeTree: TRouteLike
200 initRoute?: (route: TRouteLike, index: number) => void
201}): ProcessRouteTreeResult<TRouteLike> {
202 const routesById = {} as Record<string, TRouteLike>
203 const routesByPath = {} as Record<string, TRouteLike>
204​
205 const recurseRoutes = (childRoutes: Array<TRouteLike>) => {
206 childRoutes.forEach((childRoute, i) => {
207 initRoute?.(childRoute, i)
208​
209 const existingRoute = routesById[childRoute.id]
210​
211 invariant(
212 !existingRoute,
213 `Duplicate routes found with id: ${String(childRoute.id)}`,
214 )
215​
216 routesById[childRoute.id] = childRoute
217​
218 if (!childRoute.isRoot && childRoute.path) {
219 const trimmedFullPath = trimPathRight(childRoute.fullPath)
220 if (
221 !routesByPath[trimmedFullPath] ||
222 childRoute.fullPath.endsWith('/')
223 ) {
224 routesByPath[trimmedFullPath] = childRoute
225 }
226 }
227​
228 const children = childRoute.children as Array<TRouteLike>
229​
230 if (children?.length) {
231 recurseRoutes(children)
232 }
233 })
234 }
235​
236 recurseRoutes([routeTree])
237​
238 const flatRoutes = sortRoutes(Object.values(routesById))
239​
240 return { routesById, routesByPath, flatRoutes }