Unverified Commit 0299f14a authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add param names into the tree (#38415)

- Remove cache value that was incorrectly nested deeper
- Remove extra useEffect (already applied during hydration based on the `useReducer` input)
- Add dynamic parameter name into the tree

Follow-up to #37551, cleans up some code and prepares for catch-all and optional catch-all routes.
parent 34117946
...@@ -161,13 +161,6 @@ export default function AppRouter({ ...@@ -161,13 +161,6 @@ export default function AppRouter({
}, []) }, [])
useEffect(() => { useEffect(() => {
console.log(
'UPDATE URL',
pushRef.pendingPush ? 'push' : 'replace',
pushRef.mpaNavigation ? 'MPA' : '',
tree
)
if (pushRef.mpaNavigation) { if (pushRef.mpaNavigation) {
window.location.href = canonicalUrl window.location.href = canonicalUrl
return return
...@@ -213,10 +206,6 @@ export default function AppRouter({ ...@@ -213,10 +206,6 @@ export default function AppRouter({
} }
}, [onPopState]) }, [onPopState])
React.useEffect(() => {
window.history.replaceState({ tree: initialTree }, '')
}, [initialTree])
return ( return (
<PathnameContext.Provider value={pathname}> <PathnameContext.Provider value={pathname}>
<QueryContext.Provider value={query}> <QueryContext.Provider value={query}>
......
...@@ -11,11 +11,12 @@ import { ...@@ -11,11 +11,12 @@ import {
FullAppTreeContext, FullAppTreeContext,
} from '../../shared/lib/app-router-context' } from '../../shared/lib/app-router-context'
import { fetchServerResponse } from './app-router.client' import { fetchServerResponse } from './app-router.client'
import { matchSegment } from './match-segments'
let infinitePromise: Promise<void> | Error let infinitePromise: Promise<void> | Error
function equalArray(a: any[], b: any[]) { function equalArray(a: any[], b: any[]) {
return a.length === b.length && a.every((val, i) => val === b[i]) return a.length === b.length && a.every((val, i) => matchSegment(val, b[i]))
} }
function pathMatches( function pathMatches(
...@@ -29,11 +30,12 @@ function pathMatches( ...@@ -29,11 +30,12 @@ function pathMatches(
function createInfinitePromise() { function createInfinitePromise() {
if (!infinitePromise) { if (!infinitePromise) {
infinitePromise = new Promise((resolve) => { infinitePromise = new Promise((/* resolve */) => {
setTimeout(() => { // Note: this is used to debug when the rendering is never updated.
infinitePromise = new Error('Infinite promise') // setTimeout(() => {
resolve() // infinitePromise = new Error('Infinite promise')
}, 20000) // resolve()
// }, 5000)
}) })
} }
...@@ -68,7 +70,7 @@ export function InnerLayoutRouter({ ...@@ -68,7 +70,7 @@ export function InnerLayoutRouter({
childNodes.set(path, { childNodes.set(path, {
data: null, data: null,
subTreeData: childProp.current, subTreeData: childProp.current,
parallelRoutes: new Map([[parallelRouterKey, new Map()]]), parallelRoutes: new Map(),
}) })
childProp.current = null childProp.current = null
// In the above case childNode was set on childNodes, so we have to get it from the cacheNodes again. // In the above case childNode was set on childNodes, so we have to get it from the cacheNodes again.
...@@ -128,7 +130,7 @@ export function InnerLayoutRouter({ ...@@ -128,7 +130,7 @@ export function InnerLayoutRouter({
childNodes.set(path, { childNodes.set(path, {
data, data,
subTreeData: null, subTreeData: null,
parallelRoutes: new Map([[parallelRouterKey, new Map()]]), parallelRoutes: new Map(),
}) })
// In the above case childNode was set on childNodes, so we have to get it from the cacheNodes again. // In the above case childNode was set on childNodes, so we have to get it from the cacheNodes again.
childNode = childNodes.get(path) childNode = childNodes.get(path)
...@@ -243,7 +245,13 @@ export default function OuterLayoutRouter({ ...@@ -243,7 +245,13 @@ export default function OuterLayoutRouter({
// This relates to the segments in the current router // This relates to the segments in the current router
// tree[1].children[0] refers to tree.children.segment in the data format // tree[1].children[0] refers to tree.children.segment in the data format
const currentChildSegment = tree[1][parallelRouterKey][0] ?? childProp.segment const treeSegment = tree[1][parallelRouterKey][0]
const childPropSegment = Array.isArray(childProp.segment)
? childProp.segment[1]
: childProp.segment
const currentChildSegment =
(Array.isArray(treeSegment) ? treeSegment[1] : treeSegment) ??
childPropSegment
const preservedSegments: string[] = [currentChildSegment] const preservedSegments: string[] = [currentChildSegment]
return ( return (
...@@ -257,7 +265,7 @@ export default function OuterLayoutRouter({ ...@@ -257,7 +265,7 @@ export default function OuterLayoutRouter({
tree={tree} tree={tree}
childNodes={childNodesForParallelRouter!} childNodes={childNodesForParallelRouter!}
childProp={ childProp={
childProp.segment === preservedSegment ? childProp : null childPropSegment === preservedSegment ? childProp : null
} }
segmentPath={segmentPath} segmentPath={segmentPath}
path={preservedSegment} path={preservedSegment}
......
import { Segment } from '../../server/app-render'
export const matchSegment = (
existingSegment: Segment,
segment: Segment
): boolean => {
// Common case: segment is just a string
if (typeof existingSegment === 'string' && typeof segment === 'string') {
return existingSegment === segment
}
// Dynamic parameter case: segment is an array with param/value. Both param and value are compared.
if (Array.isArray(existingSegment) && Array.isArray(segment)) {
return (
existingSegment[0] === segment[0] && existingSegment[1] === segment[1]
)
}
return false
}
...@@ -4,6 +4,7 @@ import type { ...@@ -4,6 +4,7 @@ import type {
FlightData, FlightData,
FlightDataPath, FlightDataPath,
} from '../../server/app-render' } from '../../server/app-render'
import { matchSegment } from './match-segments'
import { fetchServerResponse } from './app-router.client' import { fetchServerResponse } from './app-router.client'
const fillCacheWithNewSubTreeData = ( const fillCacheWithNewSubTreeData = (
...@@ -15,6 +16,8 @@ const fillCacheWithNewSubTreeData = ( ...@@ -15,6 +16,8 @@ const fillCacheWithNewSubTreeData = (
const isLastEntry = flightDataPath.length <= 4 const isLastEntry = flightDataPath.length <= 4
const [parallelRouteKey, segment] = flightDataPath const [parallelRouteKey, segment] = flightDataPath
const segmentForCache = Array.isArray(segment) ? segment[1] : segment
const existingChildSegmentMap = const existingChildSegmentMap =
existingCache.parallelRoutes.get(parallelRouteKey) existingCache.parallelRoutes.get(parallelRouteKey)
...@@ -30,8 +33,8 @@ const fillCacheWithNewSubTreeData = ( ...@@ -30,8 +33,8 @@ const fillCacheWithNewSubTreeData = (
newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap) newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap)
} }
const existingChildCacheNode = existingChildSegmentMap.get(segment) const existingChildCacheNode = existingChildSegmentMap.get(segmentForCache)
let childCacheNode = childSegmentMap.get(segment) let childCacheNode = childSegmentMap.get(segmentForCache)
// In case of last segment start off the fetch at this level and don't copy further down. // In case of last segment start off the fetch at this level and don't copy further down.
if (isLastEntry) { if (isLastEntry) {
...@@ -40,7 +43,7 @@ const fillCacheWithNewSubTreeData = ( ...@@ -40,7 +43,7 @@ const fillCacheWithNewSubTreeData = (
!childCacheNode.data || !childCacheNode.data ||
childCacheNode === existingChildCacheNode childCacheNode === existingChildCacheNode
) { ) {
childSegmentMap.set(segment, { childSegmentMap.set(segmentForCache, {
data: null, data: null,
subTreeData: flightDataPath[3], subTreeData: flightDataPath[3],
parallelRoutes: new Map(), parallelRoutes: new Map(),
...@@ -61,7 +64,7 @@ const fillCacheWithNewSubTreeData = ( ...@@ -61,7 +64,7 @@ const fillCacheWithNewSubTreeData = (
subTreeData: childCacheNode.subTreeData, subTreeData: childCacheNode.subTreeData,
parallelRoutes: new Map(childCacheNode.parallelRoutes), parallelRoutes: new Map(childCacheNode.parallelRoutes),
} }
childSegmentMap.set(segment, childCacheNode) childSegmentMap.set(segmentForCache, childCacheNode)
} }
fillCacheWithNewSubTreeData( fillCacheWithNewSubTreeData(
...@@ -164,7 +167,7 @@ const createOptimisticTree = ( ...@@ -164,7 +167,7 @@ const createOptimisticTree = (
!flightRouterState || segment !== flightRouterState[0] !flightRouterState || segment !== flightRouterState[0]
let parallelRoutes: FlightRouterState[1] = {} let parallelRoutes: FlightRouterState[1] = {}
if (existingSegment === segment) { if (existingSegment !== null && matchSegment(existingSegment, segment)) {
parallelRoutes = existingParallelRoutes parallelRoutes = existingParallelRoutes
} }
...@@ -210,7 +213,7 @@ const walkTreeWithFlightDataPath = ( ...@@ -210,7 +213,7 @@ const walkTreeWithFlightDataPath = (
// Tree path returned from the server should always match up with the current tree in the browser // Tree path returned from the server should always match up with the current tree in the browser
// TODO: verify // TODO: verify
if (segment !== currentSegment) { if (!matchSegment(currentSegment, segment)) {
throw new Error('SEGMENT MISMATCH') throw new Error('SEGMENT MISMATCH')
} }
...@@ -316,6 +319,18 @@ export function reducer( ...@@ -316,6 +319,18 @@ export function reducer(
// The with optimistic tree case only happens when the layouts have a loading state (loading.js) // The with optimistic tree case only happens when the layouts have a loading state (loading.js)
// The without optimistic tree case happens when there is no loading state, in that case we suspend in this reducer // The without optimistic tree case happens when there is no loading state, in that case we suspend in this reducer
if (cacheType === 'hard') { if (cacheType === 'hard') {
if (
mutable.patchedTree &&
JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree)
) {
return {
canonicalUrl: href,
pushRef: { pendingPush, mpaNavigation: false },
cache: cache,
tree: mutable.patchedTree,
}
}
// TODO: flag on the tree of which part of the tree for if there is a loading boundary // TODO: flag on the tree of which part of the tree for if there is a loading boundary
const isOptimistic = false const isOptimistic = false
...@@ -336,10 +351,14 @@ export function reducer( ...@@ -336,10 +351,14 @@ export function reducer(
cache, cache,
state.cache, state.cache,
segments.slice(1), segments.slice(1),
() => fetchServerResponse(url, optimisticTree) () => {
return fetchServerResponse(url, optimisticTree)
}
) )
if (!res?.bailOptimistic) { if (!res?.bailOptimistic) {
mutable.previousTree = state.tree
mutable.patchedTree = optimisticTree
return { return {
canonicalUrl: href, canonicalUrl: href,
pushRef: { pendingPush, mpaNavigation: false }, pushRef: { pendingPush, mpaNavigation: false },
...@@ -349,18 +368,6 @@ export function reducer( ...@@ -349,18 +368,6 @@ export function reducer(
} }
} }
if (
mutable.patchedTree &&
JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree)
) {
return {
canonicalUrl: href,
pushRef: { pendingPush, mpaNavigation: false },
cache: cache,
tree: mutable.patchedTree,
}
}
if (!cache.data) { if (!cache.data) {
cache.data = fetchServerResponse(url, state.tree) cache.data = fetchServerResponse(url, state.tree)
} }
...@@ -436,7 +443,12 @@ export function reducer( ...@@ -436,7 +443,12 @@ export function reducer(
const treePath = flightDataPath.slice(0, -3) const treePath = flightDataPath.slice(0, -3)
const [treePatch] = flightDataPath.slice(-2) const [treePatch] = flightDataPath.slice(-2)
const newTree = walkTreeWithFlightDataPath(treePath, state.tree, treePatch) const newTree = walkTreeWithFlightDataPath(
// TODO: remove ''
['', ...treePath],
state.tree,
treePatch
)
fillCacheWithNewSubTreeData(cache, state.cache, flightDataPath) fillCacheWithNewSubTreeData(cache, state.cache, flightDataPath)
......
...@@ -22,6 +22,7 @@ import { tryGetPreviewData } from './api-utils/node' ...@@ -22,6 +22,7 @@ import { tryGetPreviewData } from './api-utils/node'
import { htmlEscapeJsonString } from './htmlescape' import { htmlEscapeJsonString } from './htmlescape'
import { stripInternalQueries } from './utils' import { stripInternalQueries } from './utils'
import { NextApiRequestCookies } from './api-utils' import { NextApiRequestCookies } from './api-utils'
import { matchSegment } from '../client/components/match-segments'
const ReactDOMServer = process.env.__NEXT_REACT_ROOT const ReactDOMServer = process.env.__NEXT_REACT_ROOT
? require('react-dom/server.browser') ? require('react-dom/server.browser')
...@@ -245,6 +246,8 @@ function createServerComponentRenderer( ...@@ -245,6 +246,8 @@ function createServerComponentRenderer(
return ServerComponentWrapper return ServerComponentWrapper
} }
export type Segment = string | [param: string, value: string]
type LoaderTree = [ type LoaderTree = [
segment: string, segment: string,
parallelRoutes: { [parallelRouterKey: string]: LoaderTree }, parallelRoutes: { [parallelRouterKey: string]: LoaderTree },
...@@ -256,7 +259,7 @@ type LoaderTree = [ ...@@ -256,7 +259,7 @@ type LoaderTree = [
] ]
export type FlightRouterState = [ export type FlightRouterState = [
segment: string, segment: Segment,
parallelRoutes: { [parallelRouterKey: string]: FlightRouterState }, parallelRoutes: { [parallelRouterKey: string]: FlightRouterState },
url?: string, url?: string,
refresh?: 'refetch' refresh?: 'refetch'
...@@ -266,11 +269,11 @@ export type FlightSegmentPath = ...@@ -266,11 +269,11 @@ export type FlightSegmentPath =
| any[] | any[]
// Looks somewhat like this // Looks somewhat like this
| [ | [
segment: string, segment: Segment,
parallelRouterKey: string, parallelRouterKey: string,
segment: string, segment: Segment,
parallelRouterKey: string, parallelRouterKey: string,
segment: string, segment: Segment,
parallelRouterKey: string parallelRouterKey: string
] ]
...@@ -278,18 +281,21 @@ export type FlightDataPath = ...@@ -278,18 +281,21 @@ export type FlightDataPath =
| any[] | any[]
// Looks somewhat like this // Looks somewhat like this
| [ | [
segment: string, segment: Segment,
parallelRoute: string, parallelRoute: string,
segment: string, segment: Segment,
parallelRoute: string, parallelRoute: string,
segment: string, segment: Segment,
parallelRoute: string, parallelRoute: string,
tree: FlightRouterState, tree: FlightRouterState,
subTreeData: React.ReactNode subTreeData: React.ReactNode
] ]
export type FlightData = Array<FlightDataPath> | string export type FlightData = Array<FlightDataPath> | string
export type ChildProp = { current: React.ReactNode; segment: string } export type ChildProp = {
current: React.ReactNode
segment: Segment
}
export async function renderToHTML( export async function renderToHTML(
req: IncomingMessage, req: IncomingMessage,
...@@ -395,7 +401,7 @@ export async function renderToHTML( ...@@ -395,7 +401,7 @@ export async function renderToHTML(
const dynamicParam = getDynamicParamFromSegment(segment) const dynamicParam = getDynamicParamFromSegment(segment)
const segmentTree: FlightRouterState = [ const segmentTree: FlightRouterState = [
dynamicParam ? dynamicParam.value : segment, dynamicParam ? [dynamicParam.param, dynamicParam.value] : segment,
{}, {},
] ]
...@@ -459,7 +465,9 @@ export async function renderToHTML( ...@@ -459,7 +465,9 @@ export async function renderToHTML(
} }
: parentParams : parentParams
const actualSegment = segmentParam ? segmentParam.value : segment const actualSegment = segmentParam
? [segmentParam.param, segmentParam.value]
: segment
// This happens outside of rendering in order to eagerly kick off data fetching for layouts / the page further down // This happens outside of rendering in order to eagerly kick off data fetching for layouts / the page further down
const parallelRouteComponents = Object.keys(parallelRoutes).reduce( const parallelRouteComponents = Object.keys(parallelRoutes).reduce(
...@@ -482,7 +490,7 @@ export async function renderToHTML( ...@@ -482,7 +490,7 @@ export async function renderToHTML(
const childProp: ChildProp = { const childProp: ChildProp = {
current: <ChildComponent />, current: <ChildComponent />,
segment: childSegmentParam segment: childSegmentParam
? childSegmentParam.value ? [childSegmentParam.param, childSegmentParam.value]
: parallelRoutes[currentValue][0], : parallelRoutes[currentValue][0],
} }
...@@ -621,7 +629,9 @@ export async function renderToHTML( ...@@ -621,7 +629,9 @@ export async function renderToHTML(
const parallelRoutesKeys = Object.keys(parallelRoutes) const parallelRoutesKeys = Object.keys(parallelRoutes)
const segmentParam = getDynamicParamFromSegment(segment) const segmentParam = getDynamicParamFromSegment(segment)
const actualSegment = segmentParam ? segmentParam.value : segment const actualSegment: Segment = segmentParam
? [segmentParam.param, segmentParam.value]
: segment
const currentParams = segmentParam const currentParams = segmentParam
? { ? {
...@@ -632,7 +642,7 @@ export async function renderToHTML( ...@@ -632,7 +642,7 @@ export async function renderToHTML(
const renderComponentsOnThisLevel = const renderComponentsOnThisLevel =
!flightRouterState || !flightRouterState ||
actualSegment !== flightRouterState[0] || !matchSegment(actualSegment, flightRouterState[0]) ||
// Last item in the tree // Last item in the tree
parallelRoutesKeys.length === 0 || parallelRoutesKeys.length === 0 ||
// Explicit refresh // Explicit refresh
......
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