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(
basePath: config.basePath,
assetPrefix: config.assetPrefix,
nextConfigOutput: config.output,
nextConfigExperimentalUseEarlyImport:
config.experimental.useEarlyImport,
nextConfigExperimentalUseEarlyImport: config.experimental
.useEarlyImport
? true
: undefined,
preferredRegion: staticInfo.preferredRegion,
middlewareConfig: encodeToBase64(staticInfo.middleware || {}),
})
......
......@@ -612,6 +612,17 @@ export const css = curry(async function css(
// If this warning were to trigger, it'd be unactionable by the user,
// but likely not valid -- so we disable it.
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 = {
assetPrefix: string
rootDir?: string
tsconfigPath?: string
isDev?: boolean
isDev?: true
basePath: string
nextConfigOutput?: NextConfig['output']
nextConfigExperimentalUseEarlyImport?: boolean
nextConfigExperimentalUseEarlyImport?: true
middlewareConfig: string
}
type AppLoader = webpack.LoaderDefinitionFunction<AppLoaderOptions>
......@@ -175,7 +175,7 @@ async function createTreeCodeFromPath(
metadataResolver,
pageExtensions,
basePath,
collectedAsyncImports,
collectedDeclarations,
}: {
page: string
resolveDir: DirResolver
......@@ -187,7 +187,7 @@ async function createTreeCodeFromPath(
loaderContext: webpack.LoaderContext<AppLoaderOptions>
pageExtensions: PageExtensions
basePath: string
collectedAsyncImports: string[]
collectedDeclarations: [string, string][]
}
): Promise<{
treeCode: string
......@@ -242,7 +242,7 @@ async function createTreeCodeFromPath(
async function createSubtreePropsFromSegmentPath(
segments: string[],
nestedCollectedAsyncImports: string[]
nestedCollectedDeclarations: [string, string][]
): Promise<{
treeCode: string
}> {
......@@ -291,18 +291,18 @@ async function createTreeCodeFromPath(
const resolvedPagePath = await resolver(matchedPagePath)
if (resolvedPagePath) {
pages.push(resolvedPagePath)
nestedCollectedAsyncImports.push(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.
props[normalizeParallelKey(parallelKey)] =
`['${PAGE_SEGMENT_KEY}', {}, {
page: [() => import(/* webpackMode: "eager" */ ${JSON.stringify(
resolvedPagePath
)}), ${JSON.stringify(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.
props[normalizeParallelKey(parallelKey)] =
`['${PAGE_SEGMENT_KEY}', {}, {
page: [${varName}, ${JSON.stringify(resolvedPagePath)}],
${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.
......@@ -330,12 +330,6 @@ async function createTreeCodeFromPath(
subSegmentPath.push(normalizedParallelSegment)
}
const { treeCode: pageSubtreeCode } =
await createSubtreePropsFromSegmentPath(
subSegmentPath,
nestedCollectedAsyncImports
)
const parallelSegmentPath = subSegmentPath.join('/')
// 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(
const definedFilePaths = filePaths.filter(
([, filePath]) => filePath !== undefined
)
) as [ValueOf<typeof FILE_TYPES>, string][]
// Add default not found error as root not found if not present
const hasNotFoundFile = definedFilePaths.some(
......@@ -411,20 +405,20 @@ async function createTreeCodeFromPath(
: parallelSegmentKey
const normalizedParallelKey = normalizeParallelKey(parallelKey)
let subtreeCode = pageSubtreeCode
let subtreeCode
// If it's root not found page, set not-found boundary as children page
if (isNotFoundRoute && normalizedParallelKey === 'children') {
const notFoundPath =
definedFilePaths.find(([type]) => type === 'not-found')?.[1] ??
defaultNotFoundPath
nestedCollectedAsyncImports.push(notFoundPath)
const varName = `notFound${nestedCollectedDeclarations.length}`
nestedCollectedDeclarations.push([varName, notFoundPath])
subtreeCode = `{
children: [${JSON.stringify(UNDERSCORE_NOT_FOUND_ROUTE)}, {
children: ['${PAGE_SEGMENT_KEY}', {}, {
page: [
() => import(/* webpackMode: "eager" */ ${JSON.stringify(
notFoundPath
)}),
${varName},
${JSON.stringify(notFoundPath)}
]
}]
......@@ -435,15 +429,24 @@ async function createTreeCodeFromPath(
const componentsCode = `{
${definedFilePaths
.map(([file, filePath]) => {
if (filePath) nestedCollectedAsyncImports.push(filePath)
return `'${file}': [() => import(/* webpackMode: "eager" */ ${JSON.stringify(
filePath
)}), ${JSON.stringify(filePath)}],`
const varName = `component${nestedCollectedDeclarations.length}`
nestedCollectedDeclarations.push([varName, filePath])
return `'${file}': [${varName}, ${JSON.stringify(filePath)}],`
})
.join('\n')}
${createMetadataExportsCode(metadata)}
}`
if (!subtreeCode) {
const { treeCode: pageSubtreeCode } =
await createSubtreePropsFromSegmentPath(
subSegmentPath,
nestedCollectedDeclarations
)
subtreeCode = pageSubtreeCode
}
props[normalizedParallelKey] = `[
'${parallelSegmentKey}',
${subtreeCode},
......@@ -467,14 +470,13 @@ async function createTreeCodeFromPath(
`${appDirPrefix}${segmentPath}${actualSegment}/default`
)) ?? PARALLEL_ROUTE_DEFAULT_PATH
nestedCollectedAsyncImports.push(defaultPath)
const varName = `default${nestedCollectedDeclarations.length}`
nestedCollectedDeclarations.push([varName, defaultPath])
props[normalizeParallelKey(adjacentParallelSegment)] = `[
'${DEFAULT_SEGMENT_KEY}',
{},
{
defaultPage: [() => import(/* webpackMode: "eager" */ ${JSON.stringify(
defaultPath
)}), ${JSON.stringify(defaultPath)}],
defaultPage: [${varName}, ${JSON.stringify(defaultPath)}],
}
]`
}
......@@ -490,7 +492,7 @@ async function createTreeCodeFromPath(
const { treeCode } = await createSubtreePropsFromSegmentPath(
[],
collectedAsyncImports
collectedDeclarations
)
return {
......@@ -529,7 +531,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
} = loaderOptions
const buildInfo = getModuleBuildInfo((this as any)._module)
const collectedAsyncImports: string[] = []
const collectedDeclarations: [string, string][] = []
const page = name.replace(/^app/, '')
const middlewareConfig: MiddlewareConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString()
......@@ -707,7 +709,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
loaderContext: this,
pageExtensions,
basePath,
collectedAsyncImports,
collectedDeclarations,
})
if (!treeCodeResult.rootLayout) {
......@@ -756,7 +758,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
loaderContext: this,
pageExtensions,
basePath,
collectedAsyncImports,
collectedDeclarations,
})
}
}
......@@ -781,18 +783,23 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
}
)
// Evaluated the imported modules early in the generated code
const earlyEvaluateCode =
const header =
nextConfigExperimentalUseEarlyImport &&
process.env.NODE_ENV === 'production'
? collectedAsyncImports
.map((modulePath) => {
return `import ${JSON.stringify(modulePath)};`
? // Evaluate the imported modules early in the generated code
collectedDeclarations
.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
......@@ -709,6 +709,7 @@ function Router({
appRouterState={useUnwrapState(reducerState)}
sync={sync}
/>
<RuntimeStyles />
<PathParamsContext.Provider value={pathParams}>
<PathnameContext.Provider value={pathname}>
<SearchParamsContext.Provider value={searchParams}>
......@@ -739,3 +740,48 @@ export default function AppRouter(
</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 {
interface RequestInit {
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 @@
"flakey": [],
"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": {
"passed": [
"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