Unverified Commit 77e6b033 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

fix css order for some edge cases in App Dir (#66500)

### What?

* order of CSS between layout and page
* order of CSS between page and next/dynamic

### Why?

### How?

* overrides webpack CSS chunk loading to use react CSS loading to allow
them to share the order
parent ceef7194
...@@ -654,8 +654,10 @@ export async function createEntrypoints( ...@@ -654,8 +654,10 @@ export async function createEntrypoints(
basePath: config.basePath, basePath: config.basePath,
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
nextConfigOutput: config.output, nextConfigOutput: config.output,
nextConfigExperimentalUseEarlyImport: nextConfigExperimentalUseEarlyImport: config.experimental
config.experimental.useEarlyImport, .useEarlyImport
? true
: undefined,
preferredRegion: staticInfo.preferredRegion, preferredRegion: staticInfo.preferredRegion,
middlewareConfig: encodeToBase64(staticInfo.middleware || {}), middlewareConfig: encodeToBase64(staticInfo.middleware || {}),
}) })
......
...@@ -612,6 +612,17 @@ export const css = curry(async function css( ...@@ -612,6 +612,17 @@ export const css = curry(async function css(
// If this warning were to trigger, it'd be unactionable by the user, // If this warning were to trigger, it'd be unactionable by the user,
// but likely not valid -- so we disable it. // but likely not valid -- so we disable it.
ignoreOrder: true, ignoreOrder: true,
insert: function (linkTag: HTMLLinkElement) {
if (typeof _N_E_STYLE_LOAD === 'function') {
const { href, onload, onerror } = linkTag
_N_E_STYLE_LOAD(new URL(href).pathname).then(
() => onload?.call(linkTag, { type: 'load' } as Event),
() => onerror?.call(linkTag, {} as Event)
)
} else {
document.head.appendChild(linkTag)
}
},
}) })
) )
) )
......
...@@ -47,10 +47,10 @@ export type AppLoaderOptions = { ...@@ -47,10 +47,10 @@ export type AppLoaderOptions = {
assetPrefix: string assetPrefix: string
rootDir?: string rootDir?: string
tsconfigPath?: string tsconfigPath?: string
isDev?: boolean isDev?: true
basePath: string basePath: string
nextConfigOutput?: NextConfig['output'] nextConfigOutput?: NextConfig['output']
nextConfigExperimentalUseEarlyImport?: boolean nextConfigExperimentalUseEarlyImport?: true
middlewareConfig: string middlewareConfig: string
} }
type AppLoader = webpack.LoaderDefinitionFunction<AppLoaderOptions> type AppLoader = webpack.LoaderDefinitionFunction<AppLoaderOptions>
...@@ -175,7 +175,7 @@ async function createTreeCodeFromPath( ...@@ -175,7 +175,7 @@ async function createTreeCodeFromPath(
metadataResolver, metadataResolver,
pageExtensions, pageExtensions,
basePath, basePath,
collectedAsyncImports, collectedDeclarations,
}: { }: {
page: string page: string
resolveDir: DirResolver resolveDir: DirResolver
...@@ -187,7 +187,7 @@ async function createTreeCodeFromPath( ...@@ -187,7 +187,7 @@ async function createTreeCodeFromPath(
loaderContext: webpack.LoaderContext<AppLoaderOptions> loaderContext: webpack.LoaderContext<AppLoaderOptions>
pageExtensions: PageExtensions pageExtensions: PageExtensions
basePath: string basePath: string
collectedAsyncImports: string[] collectedDeclarations: [string, string][]
} }
): Promise<{ ): Promise<{
treeCode: string treeCode: string
...@@ -242,7 +242,7 @@ async function createTreeCodeFromPath( ...@@ -242,7 +242,7 @@ async function createTreeCodeFromPath(
async function createSubtreePropsFromSegmentPath( async function createSubtreePropsFromSegmentPath(
segments: string[], segments: string[],
nestedCollectedAsyncImports: string[] nestedCollectedDeclarations: [string, string][]
): Promise<{ ): Promise<{
treeCode: string treeCode: string
}> { }> {
...@@ -291,18 +291,18 @@ async function createTreeCodeFromPath( ...@@ -291,18 +291,18 @@ async function createTreeCodeFromPath(
const resolvedPagePath = await resolver(matchedPagePath) const resolvedPagePath = await resolver(matchedPagePath)
if (resolvedPagePath) { if (resolvedPagePath) {
pages.push(resolvedPagePath) pages.push(resolvedPagePath)
nestedCollectedAsyncImports.push(resolvedPagePath)
} const varName = `page${nestedCollectedDeclarations.length}`
nestedCollectedDeclarations.push([varName, resolvedPagePath])
// Use '' for segment as it's the page. There can't be a segment called '' so this is the safest way to add it. // Use '' for segment as it's the page. There can't be a segment called '' so this is the safest way to add it.
props[normalizeParallelKey(parallelKey)] = props[normalizeParallelKey(parallelKey)] =
`['${PAGE_SEGMENT_KEY}', {}, { `['${PAGE_SEGMENT_KEY}', {}, {
page: [() => import(/* webpackMode: "eager" */ ${JSON.stringify( page: [${varName}, ${JSON.stringify(resolvedPagePath)}],
resolvedPagePath
)}), ${JSON.stringify(resolvedPagePath)}],
${createMetadataExportsCode(metadata)} ${createMetadataExportsCode(metadata)}
}]` }]`
if (resolvedPagePath) continue continue
}
} }
// if the parallelSegment was not matched to the __PAGE__ slot, then it's a parallel route at this level. // if the parallelSegment was not matched to the __PAGE__ slot, then it's a parallel route at this level.
...@@ -330,12 +330,6 @@ async function createTreeCodeFromPath( ...@@ -330,12 +330,6 @@ async function createTreeCodeFromPath(
subSegmentPath.push(normalizedParallelSegment) subSegmentPath.push(normalizedParallelSegment)
} }
const { treeCode: pageSubtreeCode } =
await createSubtreePropsFromSegmentPath(
subSegmentPath,
nestedCollectedAsyncImports
)
const parallelSegmentPath = subSegmentPath.join('/') const parallelSegmentPath = subSegmentPath.join('/')
// Fill in the loader tree for all of the special files types (layout, default, etc) at this level // Fill in the loader tree for all of the special files types (layout, default, etc) at this level
...@@ -358,7 +352,7 @@ async function createTreeCodeFromPath( ...@@ -358,7 +352,7 @@ async function createTreeCodeFromPath(
const definedFilePaths = filePaths.filter( const definedFilePaths = filePaths.filter(
([, filePath]) => filePath !== undefined ([, filePath]) => filePath !== undefined
) ) as [ValueOf<typeof FILE_TYPES>, string][]
// Add default not found error as root not found if not present // Add default not found error as root not found if not present
const hasNotFoundFile = definedFilePaths.some( const hasNotFoundFile = definedFilePaths.some(
...@@ -411,20 +405,20 @@ async function createTreeCodeFromPath( ...@@ -411,20 +405,20 @@ async function createTreeCodeFromPath(
: parallelSegmentKey : parallelSegmentKey
const normalizedParallelKey = normalizeParallelKey(parallelKey) const normalizedParallelKey = normalizeParallelKey(parallelKey)
let subtreeCode = pageSubtreeCode let subtreeCode
// If it's root not found page, set not-found boundary as children page // If it's root not found page, set not-found boundary as children page
if (isNotFoundRoute && normalizedParallelKey === 'children') { if (isNotFoundRoute && normalizedParallelKey === 'children') {
const notFoundPath = const notFoundPath =
definedFilePaths.find(([type]) => type === 'not-found')?.[1] ?? definedFilePaths.find(([type]) => type === 'not-found')?.[1] ??
defaultNotFoundPath defaultNotFoundPath
nestedCollectedAsyncImports.push(notFoundPath)
const varName = `notFound${nestedCollectedDeclarations.length}`
nestedCollectedDeclarations.push([varName, notFoundPath])
subtreeCode = `{ subtreeCode = `{
children: [${JSON.stringify(UNDERSCORE_NOT_FOUND_ROUTE)}, { children: [${JSON.stringify(UNDERSCORE_NOT_FOUND_ROUTE)}, {
children: ['${PAGE_SEGMENT_KEY}', {}, { children: ['${PAGE_SEGMENT_KEY}', {}, {
page: [ page: [
() => import(/* webpackMode: "eager" */ ${JSON.stringify( ${varName},
notFoundPath
)}),
${JSON.stringify(notFoundPath)} ${JSON.stringify(notFoundPath)}
] ]
}] }]
...@@ -435,15 +429,24 @@ async function createTreeCodeFromPath( ...@@ -435,15 +429,24 @@ async function createTreeCodeFromPath(
const componentsCode = `{ const componentsCode = `{
${definedFilePaths ${definedFilePaths
.map(([file, filePath]) => { .map(([file, filePath]) => {
if (filePath) nestedCollectedAsyncImports.push(filePath) const varName = `component${nestedCollectedDeclarations.length}`
return `'${file}': [() => import(/* webpackMode: "eager" */ ${JSON.stringify( nestedCollectedDeclarations.push([varName, filePath])
filePath return `'${file}': [${varName}, ${JSON.stringify(filePath)}],`
)}), ${JSON.stringify(filePath)}],`
}) })
.join('\n')} .join('\n')}
${createMetadataExportsCode(metadata)} ${createMetadataExportsCode(metadata)}
}` }`
if (!subtreeCode) {
const { treeCode: pageSubtreeCode } =
await createSubtreePropsFromSegmentPath(
subSegmentPath,
nestedCollectedDeclarations
)
subtreeCode = pageSubtreeCode
}
props[normalizedParallelKey] = `[ props[normalizedParallelKey] = `[
'${parallelSegmentKey}', '${parallelSegmentKey}',
${subtreeCode}, ${subtreeCode},
...@@ -467,14 +470,13 @@ async function createTreeCodeFromPath( ...@@ -467,14 +470,13 @@ async function createTreeCodeFromPath(
`${appDirPrefix}${segmentPath}${actualSegment}/default` `${appDirPrefix}${segmentPath}${actualSegment}/default`
)) ?? PARALLEL_ROUTE_DEFAULT_PATH )) ?? PARALLEL_ROUTE_DEFAULT_PATH
nestedCollectedAsyncImports.push(defaultPath) const varName = `default${nestedCollectedDeclarations.length}`
nestedCollectedDeclarations.push([varName, defaultPath])
props[normalizeParallelKey(adjacentParallelSegment)] = `[ props[normalizeParallelKey(adjacentParallelSegment)] = `[
'${DEFAULT_SEGMENT_KEY}', '${DEFAULT_SEGMENT_KEY}',
{}, {},
{ {
defaultPage: [() => import(/* webpackMode: "eager" */ ${JSON.stringify( defaultPage: [${varName}, ${JSON.stringify(defaultPath)}],
defaultPath
)}), ${JSON.stringify(defaultPath)}],
} }
]` ]`
} }
...@@ -490,7 +492,7 @@ async function createTreeCodeFromPath( ...@@ -490,7 +492,7 @@ async function createTreeCodeFromPath(
const { treeCode } = await createSubtreePropsFromSegmentPath( const { treeCode } = await createSubtreePropsFromSegmentPath(
[], [],
collectedAsyncImports collectedDeclarations
) )
return { return {
...@@ -529,7 +531,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -529,7 +531,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
} = loaderOptions } = loaderOptions
const buildInfo = getModuleBuildInfo((this as any)._module) const buildInfo = getModuleBuildInfo((this as any)._module)
const collectedAsyncImports: string[] = [] const collectedDeclarations: [string, string][] = []
const page = name.replace(/^app/, '') const page = name.replace(/^app/, '')
const middlewareConfig: MiddlewareConfig = JSON.parse( const middlewareConfig: MiddlewareConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString() Buffer.from(middlewareConfigBase64, 'base64').toString()
...@@ -707,7 +709,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -707,7 +709,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
loaderContext: this, loaderContext: this,
pageExtensions, pageExtensions,
basePath, basePath,
collectedAsyncImports, collectedDeclarations,
}) })
if (!treeCodeResult.rootLayout) { if (!treeCodeResult.rootLayout) {
...@@ -756,7 +758,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -756,7 +758,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
loaderContext: this, loaderContext: this,
pageExtensions, pageExtensions,
basePath, basePath,
collectedAsyncImports, collectedDeclarations,
}) })
} }
} }
...@@ -781,18 +783,23 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -781,18 +783,23 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
} }
) )
// Evaluated the imported modules early in the generated code const header =
const earlyEvaluateCode =
nextConfigExperimentalUseEarlyImport && nextConfigExperimentalUseEarlyImport &&
process.env.NODE_ENV === 'production' process.env.NODE_ENV === 'production'
? collectedAsyncImports ? // Evaluate the imported modules early in the generated code
.map((modulePath) => { collectedDeclarations
return `import ${JSON.stringify(modulePath)};` .map(([varName, modulePath]) => {
return `import * as ${varName}_ from ${JSON.stringify(modulePath)};\nconst ${varName} = () => ${varName}_;\n`
})
.join('')
: // Lazily evaluate the imported modules in the generated code
collectedDeclarations
.map(([varName, modulePath]) => {
return `const ${varName} = () => import(/* webpackMode: "eager" */ ${JSON.stringify(modulePath)});\n`
}) })
.join('\n') .join('')
: ''
return earlyEvaluateCode + code return header + code
} }
export default nextAppLoader export default nextAppLoader
...@@ -709,6 +709,7 @@ function Router({ ...@@ -709,6 +709,7 @@ function Router({
appRouterState={useUnwrapState(reducerState)} appRouterState={useUnwrapState(reducerState)}
sync={sync} sync={sync}
/> />
<RuntimeStyles />
<PathParamsContext.Provider value={pathParams}> <PathParamsContext.Provider value={pathParams}>
<PathnameContext.Provider value={pathname}> <PathnameContext.Provider value={pathname}>
<SearchParamsContext.Provider value={searchParams}> <SearchParamsContext.Provider value={searchParams}>
...@@ -739,3 +740,48 @@ export default function AppRouter( ...@@ -739,3 +740,48 @@ export default function AppRouter(
</ErrorBoundary> </ErrorBoundary>
) )
} }
const runtimeStyles = new Set<string>()
let runtimeStyleChanged = new Set<() => void>()
globalThis._N_E_STYLE_LOAD = function (href: string) {
let len = runtimeStyles.size
runtimeStyles.add(href)
if (runtimeStyles.size !== len) {
runtimeStyleChanged.forEach((cb) => cb())
}
// TODO figure out how to get a promise here
// But maybe it's not necessary as react would block rendering until it's loaded
return Promise.resolve()
}
function RuntimeStyles() {
const [, forceUpdate] = React.useState(0)
const renderedStylesSize = runtimeStyles.size
useEffect(() => {
const changed = () => forceUpdate((c) => c + 1)
runtimeStyleChanged.add(changed)
if (renderedStylesSize !== runtimeStyles.size) {
changed()
}
return () => {
runtimeStyleChanged.delete(changed)
}
}, [renderedStylesSize, forceUpdate])
const dplId = process.env.NEXT_DEPLOYMENT_ID
? `?dpl=${process.env.NEXT_DEPLOYMENT_ID}`
: ''
return [...runtimeStyles].map((href, i) => (
<link
key={i}
rel="stylesheet"
href={`${href}${dplId}`}
// @ts-ignore
precedence="next"
// TODO figure out crossOrigin and nonce
// crossOrigin={TODO}
// nonce={TODO}
/>
))
}
...@@ -58,3 +58,5 @@ interface NextFetchRequestConfig { ...@@ -58,3 +58,5 @@ interface NextFetchRequestConfig {
interface RequestInit { interface RequestInit {
next?: NextFetchRequestConfig | undefined next?: NextFetchRequestConfig | undefined
} }
declare var _N_E_STYLE_LOAD: (href: string) => Promise<void>
import { ReactNode } from 'react'
import './global3.css'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
import './global.css'
import base from './base.module.css'
import styles from './component.module.css'
export default function Component() {
return (
<p id="component" className={`global-class ${base.class} ${styles.class}`}>
Hello Component
</p>
)
}
.global-class {
background: darkred;
color: darkred;
}
body {
background: red;
}
body {
background: white;
color: black;
}
'use client'
import dynamic from 'next/dynamic'
const Component = dynamic(() => import('./component'))
export default async function Inner() {
return <Component />
}
This source diff could not be displayed because it is too large. You can view the blob instead.
'use client'
import base from './base.module.css'
import styles from './inner2.module.css'
export default async function Inner2() {
if (typeof window === 'undefined') {
throw new Error('Expected error to opt out of server rendering')
}
return (
<p id="inner2" className={`global-class ${base.class} ${styles.class}`}>
Hello Inner 2
</p>
)
}
import React, { ReactNode } from 'react'
import './global.css'
import server from './server.module.css'
import Inner from './inner'
export default function Layout({ children }: { children: ReactNode }) {
return (
<>
<p id="server" className={`global-class ${server.class}`}>
Hello Server
</p>
<Inner />
{children}
</>
)
}
import React from 'react'
import './global2.css'
import Inner2 from './inner2'
import { cookies } from 'next/headers'
export default function Page() {
cookies()
return (
<>
<p id="global">Hello Global</p>
<Inner2 />
</>
)
}
.class {
background: green;
color: black;
}
import { nextTestSetup } from 'e2e-utils'
describe('next-dynamic-css', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
it('should have correct order of styles between global and css modules', async () => {
const browser = await next.browser('/page')
expect(await browser.waitForElementByCss('#server').text()).toBe(
'Hello Server'
)
expect(
await browser.elementByCss('#server').getComputedCss('background-color')
).toBe('rgb(0, 128, 0)')
expect(await browser.elementByCss('#server').getComputedCss('color')).toBe(
'rgb(0, 0, 0)'
)
})
if (isNextDev) {
// TODO Fix order of styling in development
it.todo(
'should have correct order of styles on client component that is sharing styles with next/dynamic (TODO)'
)
} else {
it('should have correct order of styles on client component that is sharing styles with next/dynamic', async () => {
const browser = await next.browser('/page')
expect(await browser.waitForElementByCss('#inner2').text()).toBe(
'Hello Inner 2'
)
expect(
await browser.elementByCss('#inner2').getComputedCss('background-color')
).toBe('rgb(0, 128, 0)')
expect(
await browser.elementByCss('#inner2').getComputedCss('color')
).toBe('rgb(0, 0, 0)')
})
}
it('should have correct order of styles on next/dymamic loaded component', async () => {
const browser = await next.browser('/page')
expect(await browser.waitForElementByCss('#component').text()).toBe(
'Hello Component'
)
expect(
await browser
.elementByCss('#component')
.getComputedCss('background-color')
).toBe('rgb(0, 128, 0)')
expect(
await browser.elementByCss('#component').getComputedCss('color')
).toBe('rgb(0, 0, 0)')
})
it('should have correct order of global styles between layout and pages', async () => {
const browser = await next.browser('/page')
expect(await browser.waitForElementByCss('#global').text()).toBe(
'Hello Global'
)
expect(
await browser.elementByCss('#global').getComputedCss('background-color')
).toBe('rgba(0, 0, 0, 0)')
expect(await browser.elementByCss('#global').getComputedCss('color')).toBe(
'rgb(0, 0, 0)'
)
expect(
await browser.elementByCss('body').getComputedCss('background-color')
).toBe('rgb(255, 255, 255)')
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
...@@ -2122,6 +2122,19 @@ ...@@ -2122,6 +2122,19 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/e2e/app-dir/next-dynamic-css/next-dynamic-css.test.ts": {
"passed": [
"next-dynamic-css app dir should have correct order of styles between global and css modules",
"next-dynamic-css should have correct order of global styles between layout and pages",
"next-dynamic-css should have correct order of styles on next/dymamic loaded component"
],
"failed": [
"next-dynamic-css should have correct order of styles on client component that is sharing styles with next/dynamic"
],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/e2e/app-dir/next-font/next-font.test.ts": { "test/e2e/app-dir/next-font/next-font.test.ts": {
"passed": [ "passed": [
"app dir - next/font app dir - next-font computed styles should have correct styles at /", "app dir - next/font app dir - next-font computed styles should have correct styles at /",
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