Commit e783e3be authored by Jimmy Lai's avatar Jimmy Lai

fix: propagate dynamic segments across parallel route slots (#62656)

parent 98aaf5c6
...@@ -1096,6 +1096,7 @@ async fn directory_tree_to_loader_tree( ...@@ -1096,6 +1096,7 @@ async fn directory_tree_to_loader_tree(
for_app_path, for_app_path,
AppDirModules::default(), AppDirModules::default(),
Some(&plain_tree.url_tree), Some(&plain_tree.url_tree),
false,
) )
.await?; .await?;
...@@ -1176,10 +1177,20 @@ async fn directory_tree_to_loader_tree_internal( ...@@ -1176,10 +1177,20 @@ async fn directory_tree_to_loader_tree_internal(
for_app_path: AppPath, for_app_path: AppPath,
mut parent_modules: AppDirModules, mut parent_modules: AppDirModules,
url_tree: Option<&UrlSegmentTree>, url_tree: Option<&UrlSegmentTree>,
// When true, Dynamic segments in app_path are treated as matching any Static
// segment in for_app_path. Used for parallel route slots so that e.g.
// @parallel/test/[param] can match the static path /test/static.
match_dynamic: bool,
) -> Result<Option<AppPageLoaderTree>> { ) -> Result<Option<AppPageLoaderTree>> {
let app_path = AppPath::from(app_page.clone()); let app_path = AppPath::from(app_page.clone());
if !for_app_path.contains(&app_path) { let is_contained = if match_dynamic {
for_app_path.contains_dynamic(&app_path)
} else {
for_app_path.contains(&app_path)
};
if !is_contained {
return Ok(None); return Ok(None);
} }
...@@ -1267,9 +1278,11 @@ async fn directory_tree_to_loader_tree_internal( ...@@ -1267,9 +1278,11 @@ async fn directory_tree_to_loader_tree_internal(
tree.segment = rcstr!("(__SLOT__)"); tree.segment = rcstr!("(__SLOT__)");
} }
if let Some(page) = (app_path == for_app_path || app_path.is_catchall()) if let Some(page) = (app_path == for_app_path
.then_some(modules.page) || app_path.is_catchall()
.flatten() || (match_dynamic && app_path.matches_dynamic(&for_app_path)))
.then_some(modules.page)
.flatten()
{ {
tree.parallel_routes.insert( tree.parallel_routes.insert(
rcstr!("children"), rcstr!("children"),
...@@ -1311,6 +1324,11 @@ async fn directory_tree_to_loader_tree_internal( ...@@ -1311,6 +1324,11 @@ async fn directory_tree_to_loader_tree_internal(
url_tree.and_then(|t| t.get_child(&directory_name)) url_tree.and_then(|t| t.get_child(&directory_name))
}; };
// For parallel route slots, use dynamic matching so that a slot with
// e.g. @parallel/test/[param] can match the static path /test/static.
// The match_dynamic flag propagates down the entire parallel subtree.
let child_match_dynamic = match_dynamic || parallel_route_key.is_some();
let subtree = Box::pin(directory_tree_to_loader_tree_internal( let subtree = Box::pin(directory_tree_to_loader_tree_internal(
app_dir.clone(), app_dir.clone(),
global_metadata, global_metadata,
...@@ -1320,6 +1338,7 @@ async fn directory_tree_to_loader_tree_internal( ...@@ -1320,6 +1338,7 @@ async fn directory_tree_to_loader_tree_internal(
for_app_path.clone(), for_app_path.clone(),
parent_modules.clone(), parent_modules.clone(),
child_url_tree, child_url_tree,
child_match_dynamic,
)) ))
.await?; .await?;
......
...@@ -448,7 +448,44 @@ impl AppPath { ...@@ -448,7 +448,44 @@ impl AppPath {
) )
} }
/// Returns true if `self` has at least one Dynamic segment and each segment
/// in `self` either equals the corresponding segment in `other` or is a
/// Dynamic segment (which matches any single segment). Both paths must have
/// the same length. This is used to allow parallel routes with dynamic
/// segments to match static paths from other slots.
pub fn matches_dynamic(&self, other: &AppPath) -> bool {
if self.0.len() != other.0.len() {
return false;
}
let mut has_dynamic = false;
for (self_seg, other_seg) in self.0.iter().zip(other.0.iter()) {
if self_seg == other_seg {
continue;
}
if matches!(self_seg, PathSegment::Dynamic(_)) {
has_dynamic = true;
continue;
}
return false;
}
has_dynamic
}
pub fn contains(&self, other: &AppPath) -> bool { pub fn contains(&self, other: &AppPath) -> bool {
self.contains_impl(other, false)
}
/// Like `contains` but also treats Dynamic segments in `other` as matching
/// any single Static segment in `self`. Used when checking if a parallel
/// route with a dynamic segment could serve a static path.
pub fn contains_dynamic(&self, other: &AppPath) -> bool {
self.contains_impl(other, true)
}
fn contains_impl(&self, other: &AppPath, match_dynamic: bool) -> bool {
// TODO: handle OptionalCatchAll properly. // TODO: handle OptionalCatchAll properly.
for (i, segment) in other.0.iter().enumerate() { for (i, segment) in other.0.iter().enumerate() {
let Some(self_segment) = self.0.get(i) else { let Some(self_segment) = self.0.get(i) else {
...@@ -467,6 +504,13 @@ impl AppPath { ...@@ -467,6 +504,13 @@ impl AppPath {
return true; return true;
} }
// A Dynamic segment matches any single Static segment.
// This allows parallel routes with dynamic segments (e.g. @parallel/test/[param])
// to match static paths (e.g. /test/static) in other slots.
if match_dynamic && matches!(segment, PathSegment::Dynamic(_)) {
continue;
}
return false; return false;
} }
......
...@@ -6,6 +6,10 @@ import { AppPathnameNormalizer } from '../server/normalizers/built/app/app-pathn ...@@ -6,6 +6,10 @@ import { AppPathnameNormalizer } from '../server/normalizers/built/app/app-pathn
* It will traverse the appPaths, looking for catch-all routes and try to find parallel routes that could match * It will traverse the appPaths, looking for catch-all routes and try to find parallel routes that could match
* the catch-all. If it finds a match, it will add the catch-all to the parallel route's list of possible routes. * the catch-all. If it finds a match, it will add the catch-all to the parallel route's list of possible routes.
* *
* It also handles single dynamic segment routes (`[param]`) in parallel slots. When a static path like
* `/test/static` exists and a parallel slot has a dynamic route like `/@parallel/test/[param]` but no
* `/@parallel/test/static`, the dynamic route is added as a fallback for that slot.
*
* @param appPaths The appPaths to transform * @param appPaths The appPaths to transform
*/ */
export function normalizeCatchAllRoutes( export function normalizeCatchAllRoutes(
...@@ -59,6 +63,108 @@ export function normalizeCatchAllRoutes( ...@@ -59,6 +63,108 @@ export function normalizeCatchAllRoutes(
} }
} }
} }
// Propagate single dynamic segment routes from parallel slots.
// When a static path like `/test/static` exists and a parallel slot has
// `/@parallel/test/[param]` but no `/@parallel/test/static`, add the
// dynamic route as a fallback for that slot.
normalizeDynamicRoutes(appPaths, filteredAppPaths, normalizer)
}
/**
* Propagates single dynamic segment parallel routes to static paths that
* could be matched by them.
*
* For example, if `@parallel/test/[testParam]/page` exists but there is no
* `@parallel/test/static/page`, and `/test/static` is a valid app path,
* then `@parallel/test/[testParam]/page` will be added to the `/test/static`
* entry so that the parallel slot resolves to the dynamic page instead of
* falling back to `default.tsx`.
*/
function normalizeDynamicRoutes(
appPaths: Record<string, string[]>,
filteredAppPaths: string[],
normalizer: AppPathnameNormalizer
): void {
// Collect all dynamic routes that belong to a parallel slot (contain @).
const dynamicParallelRoutes = [
...new Set(
Object.values(appPaths)
.flat()
.filter(
(route) =>
route.includes('@') &&
hasDynamicSegment(route) &&
!isCatchAllRoute(route)
)
// Prefer more specific (deeper) routes first.
.sort((a, b) => b.split('/').length - a.split('/').length)
),
]
if (dynamicParallelRoutes.length === 0) return
for (const appPath of filteredAppPaths) {
// Skip default route entries, which are fallback routes and should not
// receive dynamic route propagation.
if (appPath.endsWith('/default')) continue
for (const dynamicRoute of dynamicParallelRoutes) {
const normalizedDynamic = normalizer.normalize(dynamicRoute)
// Check if this dynamic route could match the appPath.
// A dynamic route like `/test/[param]` can match `/test/static` if:
// 1. They have the same number of segments.
// 2. All non-dynamic segments in the dynamic route match the appPath.
// 3. Dynamic segments in the dynamic route only match static (non-dynamic)
// segments in the appPath.
if (
dynamicRouteMatchesPath(normalizedDynamic, appPath) &&
// Don't add if the slot already has a matching entry for this path.
!appPaths[appPath].some((path) => hasMatchedSlots(path, dynamicRoute))
) {
appPaths[appPath].push(dynamicRoute)
}
}
}
}
/**
* Checks if a normalized dynamic route pattern could match a given path.
* For example, `/test/[param]` matches `/test/static` because they have the same
* number of segments and the non-dynamic segments match.
*
* Dynamic segments in the dynamic route must correspond to static (non-dynamic)
* segments in the target path. This prevents matching patterns like
* `/nested/[foo]/[bar]/[baz]` against `/nested/[foo]/[bar]/[qux]` where both
* sides have dynamic segments at the same position.
*/
function dynamicRouteMatchesPath(
dynamicRoute: string,
targetPath: string
): boolean {
const dynamicSegments = dynamicRoute.split('/').filter(Boolean)
const targetSegments = targetPath.split('/').filter(Boolean)
if (dynamicSegments.length !== targetSegments.length) return false
// At least one position must have a dynamic-to-static match
let hasDynamicToStaticMatch = false
for (let i = 0; i < dynamicSegments.length; i++) {
if (isDynamicSegment(dynamicSegments[i])) {
// Only count as a match if the corresponding target segment is static.
// If the target also has a dynamic segment at this position, skip it
// (both sides are dynamic, so this isn't a meaningful match).
if (!isDynamicSegment(targetSegments[i])) {
hasDynamicToStaticMatch = true
}
continue
}
if (dynamicSegments[i] !== targetSegments[i]) return false
}
return hasDynamicToStaticMatch
} }
function hasMatchedSlots(path1: string, path2: string): boolean { function hasMatchedSlots(path1: string, path2: string): boolean {
...@@ -99,3 +205,13 @@ function isOptionalCatchAll(pathname: string): boolean { ...@@ -99,3 +205,13 @@ function isOptionalCatchAll(pathname: string): boolean {
function isCatchAll(pathname: string): boolean { function isCatchAll(pathname: string): boolean {
return pathname.includes('[...') return pathname.includes('[...')
} }
function isDynamicSegment(segment: string): boolean {
return (
segment.startsWith('[') && segment.endsWith(']') && !segment.includes('...')
)
}
function hasDynamicSegment(pathname: string): boolean {
return pathname.split('/').some(isDynamicSegment)
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment