Unverified Commit a840dbf8 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add Suspense boundary to demo (#37393)

parent ccd3df2f
...@@ -14,14 +14,16 @@ function pathToUrlPath(pathname: string) { ...@@ -14,14 +14,16 @@ function pathToUrlPath(pathname: string) {
return urlPath return urlPath
} }
async function resolveLayoutPathsByPage({ async function resolvePathsByPage({
name,
pagePath, pagePath,
resolve, resolve,
}: { }: {
name: 'layout' | 'loading'
pagePath: string pagePath: string
resolve: (pathname: string) => Promise<string | undefined> resolve: (pathname: string) => Promise<string | undefined>
}) { }) {
const layoutPaths = new Map<string, string | undefined>() const paths = new Map<string, string | undefined>()
const parts = pagePath.split('/') const parts = pagePath.split('/')
const isNewRootLayout = const isNewRootLayout =
parts[1]?.length > 2 && parts[1]?.startsWith('(') && parts[1]?.endsWith(')') parts[1]?.length > 2 && parts[1]?.startsWith('(') && parts[1]?.endsWith(')')
...@@ -32,26 +34,30 @@ async function resolveLayoutPathsByPage({ ...@@ -32,26 +34,30 @@ async function resolveLayoutPathsByPage({
if (!pathWithoutSlashLayout) { if (!pathWithoutSlashLayout) {
continue continue
} }
const layoutPath = `${pathWithoutSlashLayout}/layout` const layoutPath = `${pathWithoutSlashLayout}/${name}`
let resolvedLayoutPath = await resolve(layoutPath) let resolvedLayoutPath = await resolve(layoutPath)
let urlPath = pathToUrlPath(pathWithoutSlashLayout) let urlPath = pathToUrlPath(pathWithoutSlashLayout)
// if we are in a new root app/(root) and a custom root layout was // if we are in a new root app/(root) and a custom root layout was
// not provided or a root layout app/layout is not present, we use // not provided or a root layout app/layout is not present, we use
// a default root layout to provide the html/body tags // a default root layout to provide the html/body tags
const isCustomRootLayout = isNewRootLayout && i === 2 const isCustomRootLayout = name === 'layout' && isNewRootLayout && i === 2
if ((isCustomRootLayout || i === 1) && !resolvedLayoutPath) { if (
name === 'layout' &&
(isCustomRootLayout || i === 1) &&
!resolvedLayoutPath
) {
resolvedLayoutPath = await resolve('next/dist/lib/app-layout') resolvedLayoutPath = await resolve('next/dist/lib/app-layout')
} }
layoutPaths.set(urlPath, resolvedLayoutPath) paths.set(urlPath, resolvedLayoutPath)
// if we're in a new root layout don't add the top-level app/layout // if we're in a new root layout don't add the top-level app/layout
if (isCustomRootLayout) { if (isCustomRootLayout) {
break break
} }
} }
return layoutPaths return paths
} }
const nextAppLoader: webpack.LoaderDefinitionFunction<{ const nextAppLoader: webpack.LoaderDefinitionFunction<{
...@@ -75,7 +81,39 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{ ...@@ -75,7 +81,39 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{
} }
const resolve = this.getResolve(resolveOptions) const resolve = this.getResolve(resolveOptions)
const layoutPaths = await resolveLayoutPathsByPage({ const loadingPaths = await resolvePathsByPage({
name: 'loading',
pagePath: pagePath,
resolve: async (pathname) => {
try {
return await resolve(this.rootContext, pathname)
} catch (err: any) {
if (err.message.includes("Can't resolve")) {
return undefined
}
throw err
}
},
})
const loadingComponentsCode = []
for (const [loadingPath, resolvedLoadingPath] of loadingPaths) {
if (resolvedLoadingPath) {
this.addDependency(resolvedLoadingPath)
// use require so that we can bust the require cache
const codeLine = `'${loadingPath}': () => require('${resolvedLoadingPath}')`
loadingComponentsCode.push(codeLine)
} else {
for (const ext of extensions) {
this.addMissingDependency(
path.join(appDir, loadingPath, `layout${ext}`)
)
}
}
}
const layoutPaths = await resolvePathsByPage({
name: 'layout',
pagePath: pagePath, pagePath: pagePath,
resolve: async (pathname) => { resolve: async (pathname) => {
try { try {
...@@ -117,6 +155,10 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{ ...@@ -117,6 +155,10 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{
${componentsCode.join(',\n')} ${componentsCode.join(',\n')}
}; };
export const loadingComponents = {
${loadingComponentsCode.join(',\n')}
};
export const AppRouter = require('next/dist/client/components/app-router.client.js').default export const AppRouter = require('next/dist/client/components/app-router.client.js').default
export const LayoutRouter = require('next/dist/client/components/layout-router.client.js').default export const LayoutRouter = require('next/dist/client/components/layout-router.client.js').default
......
...@@ -36,6 +36,10 @@ export type RenderOptsPartial = { ...@@ -36,6 +36,10 @@ export type RenderOptsPartial = {
export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial
function interopDefault(mod: any) {
return mod.default || mod
}
const rscCache = new Map() const rscCache = new Map()
// Shadowing check does not work with TypeScript enums // Shadowing check does not work with TypeScript enums
...@@ -236,7 +240,7 @@ export async function renderToHTML( ...@@ -236,7 +240,7 @@ export async function renderToHTML(
.sort() .sort()
.map((path) => { .map((path) => {
const mod = ComponentMod.components[path]() const mod = ComponentMod.components[path]()
mod.Component = mod.default || mod mod.Component = interopDefault(mod)
mod.path = path mod.path = path
return mod return mod
}) })
...@@ -307,6 +311,9 @@ export async function renderToHTML( ...@@ -307,6 +311,9 @@ export async function renderToHTML(
} }
const LayoutRouter = ComponentMod.LayoutRouter const LayoutRouter = ComponentMod.LayoutRouter
const getLoadingMod = ComponentMod.loadingComponents[layout.path]
const Loading = getLoadingMod ? interopDefault(getLoadingMod()) : null
// eslint-disable-next-line no-loop-func // eslint-disable-next-line no-loop-func
const lastComponent = WrappedComponent const lastComponent = WrappedComponent
WrappedComponent = (props: any) => { WrappedComponent = (props: any) => {
...@@ -333,16 +340,24 @@ export async function renderToHTML( ...@@ -333,16 +340,24 @@ export async function renderToHTML(
{}, {},
null null
) )
// TODO: add tests for loading.js
const chilrenWithLoading = Loading ? (
<React.Suspense fallback={<Loading />}>{children}</React.Suspense>
) : (
children
)
// Pages don't need to be wrapped in a router // Pages don't need to be wrapped in a router
return React.createElement( return React.createElement(
layout.Component, layout.Component,
props, props,
layout.path.endsWith('/page') ? ( layout.path.endsWith('/page') ? (
children chilrenWithLoading
) : ( ) : (
// TODO: only provide the part of the url that is relevant to the layout (see layout-router.client.tsx) // TODO: only provide the part of the url that is relevant to the layout (see layout-router.client.tsx)
<LayoutRouter initialUrl={pathname} layoutPath={layout.path}> <LayoutRouter initialUrl={pathname} layoutPath={layout.path}>
{children} {chilrenWithLoading}
</LayoutRouter> </LayoutRouter>
) )
) )
......
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