Unverified Commit 2a61253f authored by Shu Ding's avatar Shu Ding Committed by GitHub

Fix misordered CSS resources (#48244)

### What?

This PR fixes misordered CSS `<link>` tags. CSS imports in inner layers
(e.g. a page) should always take precedence over outer layers (e.g. root
layout), but currently it's reversed.

### Why?

In layouts we usually define more general styles like globals, resets,
and layout specific things. And in inner layers and pages, things need
to be more detailed and override upper layers if there're any conflicts.

Previously we defined the component segment as

```tsx
<>
  <Component {...props} />
  {assets}
</>
```

which is necessary because of `findDOMNode` - if we put `assets` before
the component, we can't find the correct scrolling DOM and position for
that layer.

However, with `assets` being the last Float will receive the reversed
order of resources.

### How?

I changed the `createComponentTree` function to return a `Component` and
`assets` pair, so in the Layout Router they're no longer passed to the
scroll wrapper altogether but separately.

Closes NEXT-983
Fixes #47585, fixes #46347.

fix NEXT-656

---------
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 3ac76585
...@@ -453,6 +453,7 @@ export default function OuterLayoutRouter({ ...@@ -453,6 +453,7 @@ export default function OuterLayoutRouter({
notFound, notFound,
notFoundStyles, notFoundStyles,
asNotFound, asNotFound,
styles,
}: { }: {
parallelRouterKey: string parallelRouterKey: string
segmentPath: FlightSegmentPath segmentPath: FlightSegmentPath
...@@ -467,6 +468,7 @@ export default function OuterLayoutRouter({ ...@@ -467,6 +468,7 @@ export default function OuterLayoutRouter({
notFound: React.ReactNode | undefined notFound: React.ReactNode | undefined
notFoundStyles: React.ReactNode | undefined notFoundStyles: React.ReactNode | undefined
asNotFound?: boolean asNotFound?: boolean
styles?: React.ReactNode
}) { }) {
const context = useContext(LayoutRouterContext) const context = useContext(LayoutRouterContext)
if (!context) { if (!context) {
...@@ -501,6 +503,7 @@ export default function OuterLayoutRouter({ ...@@ -501,6 +503,7 @@ export default function OuterLayoutRouter({
return ( return (
<> <>
{styles}
{preservedSegments.map((preservedSegment) => { {preservedSegments.map((preservedSegment) => {
const isChildPropSegment = matchSegment( const isChildPropSegment = matchSegment(
preservedSegment, preservedSegment,
......
...@@ -468,7 +468,7 @@ export async function renderToHTMLOrFlight( ...@@ -468,7 +468,7 @@ export async function renderToHTMLOrFlight(
return [Comp, styles] return [Comp, styles]
} }
const createStaticAssets = async ({ const getLayerAssets = ({
layoutOrPagePath, layoutOrPagePath,
injectedCSS: injectedCSSWithCurrentLayout, injectedCSS: injectedCSSWithCurrentLayout,
injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout, injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout,
...@@ -476,7 +476,10 @@ export async function renderToHTMLOrFlight( ...@@ -476,7 +476,10 @@ export async function renderToHTMLOrFlight(
layoutOrPagePath: string | undefined layoutOrPagePath: string | undefined
injectedCSS: Set<string> injectedCSS: Set<string>
injectedFontPreloadTags: Set<string> injectedFontPreloadTags: Set<string>
}) => { }): {
styles: React.ReactNode
preloads: React.ReactNode
} => {
const stylesheets: string[] = layoutOrPagePath const stylesheets: string[] = layoutOrPagePath
? getCssInlinedLinkTags( ? getCssInlinedLinkTags(
clientReferenceManifest, clientReferenceManifest,
...@@ -498,9 +501,10 @@ export async function renderToHTMLOrFlight( ...@@ -498,9 +501,10 @@ export async function renderToHTMLOrFlight(
) )
: [] : []
return ( const preloads = (
<> <>
{preloadedFontFiles?.length === 0 ? ( {preloadedFontFiles?.length === 0 ? (
<>
<link <link
data-next-font={ data-next-font={
nextFontManifest?.appUsingSizeAdjust ? 'size-adjust' : '' nextFontManifest?.appUsingSizeAdjust ? 'size-adjust' : ''
...@@ -509,6 +513,7 @@ export async function renderToHTMLOrFlight( ...@@ -509,6 +513,7 @@ export async function renderToHTMLOrFlight(
href="/" href="/"
crossOrigin="anonymous" crossOrigin="anonymous"
/> />
</>
) : null} ) : null}
{preloadedFontFiles {preloadedFontFiles
? preloadedFontFiles.map((fontFile) => { ? preloadedFontFiles.map((fontFile) => {
...@@ -528,7 +533,10 @@ export async function renderToHTMLOrFlight( ...@@ -528,7 +533,10 @@ export async function renderToHTMLOrFlight(
) )
}) })
: null} : null}
{stylesheets </>
)
const styles = stylesheets
? stylesheets.map((href, index) => ( ? stylesheets.map((href, index) => (
<link <link
rel="stylesheet" rel="stylesheet"
...@@ -546,9 +554,32 @@ export async function renderToHTMLOrFlight( ...@@ -546,9 +554,32 @@ export async function renderToHTMLOrFlight(
key={index} key={index}
/> />
)) ))
: null} : null
</>
) return {
styles,
preloads,
}
}
const parseLoaderTree = (tree: LoaderTree) => {
const [segment, parallelRoutes, components] = tree
const { layout } = components
let { page } = components
// a __DEFAULT__ segment means that this route didn't match any of the
// segments in the route, so we should use the default page
page = segment === '__DEFAULT__' ? components.defaultPage : page
const layoutOrPagePath = layout?.[1] || page?.[1]
return {
page,
segment,
components,
layoutOrPagePath,
parallelRoutes,
}
} }
/** /**
...@@ -572,8 +603,13 @@ export async function renderToHTMLOrFlight( ...@@ -572,8 +603,13 @@ export async function renderToHTMLOrFlight(
injectedCSS: Set<string> injectedCSS: Set<string>
injectedFontPreloadTags: Set<string> injectedFontPreloadTags: Set<string>
asNotFound?: boolean asNotFound?: boolean
}): Promise<{ Component: React.ComponentType }> => { }): Promise<{
const [segment, parallelRoutes, components] = tree Component: React.ComponentType
styles: React.ReactNode
}> => {
const { page, layoutOrPagePath, segment, components, parallelRoutes } =
parseLoaderTree(tree)
const { const {
layout, layout,
template, template,
...@@ -581,20 +617,13 @@ export async function renderToHTMLOrFlight( ...@@ -581,20 +617,13 @@ export async function renderToHTMLOrFlight(
loading, loading,
'not-found': notFound, 'not-found': notFound,
} = components } = components
let { page } = components
// a __DEFAULT__ segment means that this route didn't match any of the
// segments in the route, so we should use the default page
page = segment === '__DEFAULT__' ? components.defaultPage : page
const layoutOrPagePath = layout?.[1] || page?.[1]
const injectedCSSWithCurrentLayout = new Set(injectedCSS) const injectedCSSWithCurrentLayout = new Set(injectedCSS)
const injectedFontPreloadTagsWithCurrentLayout = new Set( const injectedFontPreloadTagsWithCurrentLayout = new Set(
injectedFontPreloadTags injectedFontPreloadTags
) )
const assets = createStaticAssets({ const { styles, preloads } = getLayerAssets({
layoutOrPagePath, layoutOrPagePath,
injectedCSS: injectedCSSWithCurrentLayout, injectedCSS: injectedCSSWithCurrentLayout,
injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout, injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout,
...@@ -825,7 +854,8 @@ export async function renderToHTMLOrFlight( ...@@ -825,7 +854,8 @@ export async function renderToHTMLOrFlight(
} }
// Create the child component // Create the child component
const { Component: ChildComponent } = await createComponentTree({ const { Component: ChildComponent, styles: childStyles } =
await createComponentTree({
createSegmentPath: (child) => { createSegmentPath: (child) => {
return createSegmentPath([...currentSegmentPath, ...child]) return createSegmentPath([...currentSegmentPath, ...child])
}, },
...@@ -833,7 +863,8 @@ export async function renderToHTMLOrFlight( ...@@ -833,7 +863,8 @@ export async function renderToHTMLOrFlight(
parentParams: currentParams, parentParams: currentParams,
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove, rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
injectedCSS: injectedCSSWithCurrentLayout, injectedCSS: injectedCSSWithCurrentLayout,
injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout, injectedFontPreloadTags:
injectedFontPreloadTagsWithCurrentLayout,
asNotFound, asNotFound,
}) })
...@@ -871,6 +902,7 @@ export async function renderToHTMLOrFlight( ...@@ -871,6 +902,7 @@ export async function renderToHTMLOrFlight(
notFoundStyles={notFoundStyles} notFoundStyles={notFoundStyles}
asNotFound={asNotFound} asNotFound={asNotFound}
childProp={childProp} childProp={childProp}
styles={childStyles}
/>, />,
] ]
} }
...@@ -890,6 +922,7 @@ export async function renderToHTMLOrFlight( ...@@ -890,6 +922,7 @@ export async function renderToHTMLOrFlight(
if (!Component) { if (!Component) {
return { return {
Component: () => <>{parallelRouteComponents.children}</>, Component: () => <>{parallelRouteComponents.children}</>,
styles,
} }
} }
...@@ -940,7 +973,7 @@ export async function renderToHTMLOrFlight( ...@@ -940,7 +973,7 @@ export async function renderToHTMLOrFlight(
Component: () => { Component: () => {
return ( return (
<> <>
{/* <Component /> needs to be the first element because we use `findDOMONode` in layout router to locate it. */} {/* <Component /> needs to be the first element because we use `findDOMNode` in layout router to locate it. */}
{isPage && isClientComponent && isStaticGeneration ? ( {isPage && isClientComponent && isStaticGeneration ? (
<StaticGenerationSearchParamsBailoutProvider <StaticGenerationSearchParamsBailoutProvider
propsForComponent={props} propsForComponent={props}
...@@ -949,10 +982,11 @@ export async function renderToHTMLOrFlight( ...@@ -949,10 +982,11 @@ export async function renderToHTMLOrFlight(
) : ( ) : (
<Component {...props} /> <Component {...props} />
)} )}
{assets} {preloads}
</> </>
) )
}, },
styles,
} }
} }
...@@ -1038,6 +1072,7 @@ export async function renderToHTMLOrFlight( ...@@ -1038,6 +1072,7 @@ export async function renderToHTMLOrFlight(
canSegmentBeOverridden(actualSegment, flightRouterState[0]) canSegmentBeOverridden(actualSegment, flightRouterState[0])
? flightRouterState[0] ? flightRouterState[0]
: null : null
return [ return [
[ [
overriddenSegment ?? actualSegment, overriddenSegment ?? actualSegment,
...@@ -1056,16 +1091,14 @@ export async function renderToHTMLOrFlight( ...@@ -1056,16 +1091,14 @@ export async function renderToHTMLOrFlight(
const { Component } = await createComponentTree( const { Component } = await createComponentTree(
// This ensures flightRouterPath is valid and filters down the tree // This ensures flightRouterPath is valid and filters down the tree
{ {
createSegmentPath: (child) => { createSegmentPath,
return createSegmentPath(child)
},
loaderTree: loaderTreeToFilter, loaderTree: loaderTreeToFilter,
parentParams: currentParams, parentParams: currentParams,
firstItem: isFirst, firstItem: isFirst,
injectedCSS, injectedCSS,
injectedFontPreloadTags, injectedFontPreloadTags,
// This is intentionally not "rootLayoutIncludedAtThisLevelOrAbove" as createComponentTree starts at the current level and does a check for "rootLayoutAtThisLevel" too. // This is intentionally not "rootLayoutIncludedAtThisLevelOrAbove" as createComponentTree starts at the current level and does a check for "rootLayoutAtThisLevel" too.
rootLayoutIncluded: rootLayoutIncluded, rootLayoutIncluded,
asNotFound, asNotFound,
} }
) )
...@@ -1074,7 +1107,23 @@ export async function renderToHTMLOrFlight( ...@@ -1074,7 +1107,23 @@ export async function renderToHTMLOrFlight(
}), }),
isPrefetch && !Boolean(components.loading) isPrefetch && !Boolean(components.loading)
? null ? null
: rscPayloadHead, : (() => {
const { layoutOrPagePath } =
parseLoaderTree(loaderTreeToFilter)
const { styles } = getLayerAssets({
layoutOrPagePath,
injectedCSS: new Set(injectedCSS),
injectedFontPreloadTags: new Set(injectedFontPreloadTags),
})
return (
<>
{styles}
{rscPayloadHead}
</>
)
})(),
], ],
] ]
} }
...@@ -1271,7 +1320,7 @@ export async function renderToHTMLOrFlight( ...@@ -1271,7 +1320,7 @@ export async function renderToHTMLOrFlight(
const injectedCSS = new Set<string>() const injectedCSS = new Set<string>()
const injectedFontPreloadTags = new Set<string>() const injectedFontPreloadTags = new Set<string>()
const { Component: ComponentTree } = await createComponentTree({ const { Component: ComponentTree, styles } = await createComponentTree({
createSegmentPath: (child) => child, createSegmentPath: (child) => child,
loaderTree, loaderTree,
parentParams: {}, parentParams: {},
...@@ -1299,12 +1348,6 @@ export async function renderToHTMLOrFlight( ...@@ -1299,12 +1348,6 @@ export async function renderToHTMLOrFlight(
? [DefaultNotFound] ? [DefaultNotFound]
: [] : []
const assets = createStaticAssets({
layoutOrPagePath: layout?.[1],
injectedCSS,
injectedFontPreloadTags,
})
const initialTree = createFlightRouterStateFromLoaderTree( const initialTree = createFlightRouterStateFromLoaderTree(
loaderTree, loaderTree,
getDynamicParamFromSegment, getDynamicParamFromSegment,
...@@ -1313,6 +1356,7 @@ export async function renderToHTMLOrFlight( ...@@ -1313,6 +1356,7 @@ export async function renderToHTMLOrFlight(
return ( return (
<> <>
{styles}
<AppRouter <AppRouter
assetPrefix={assetPrefix} assetPrefix={assetPrefix}
initialCanonicalUrl={initialCanonicalUrl} initialCanonicalUrl={initialCanonicalUrl}
...@@ -1331,13 +1375,10 @@ export async function renderToHTMLOrFlight( ...@@ -1331,13 +1375,10 @@ export async function renderToHTMLOrFlight(
globalErrorComponent={GlobalError} globalErrorComponent={GlobalError}
notFound={ notFound={
NotFound && RootLayout ? ( NotFound && RootLayout ? (
<>
{assets}
<RootLayout params={{}}> <RootLayout params={{}}>
{notFoundStyles} {notFoundStyles}
<NotFound /> <NotFound />
</RootLayout> </RootLayout>
</>
) : undefined ) : undefined
} }
asNotFound={props.asNotFound} asNotFound={props.asNotFound}
......
@layer default;
@layer default {
h1 {
color: black;
}
}
@layer default {
input[type='text'] {
padding: 0.5rem;
}
h1 {
color: red;
}
}
'use client'
import './input.css'
export default function InputText() {
return <input />
}
import './index.css'
export default function Layout({ children }) {
return <div>{children}</div>
}
import InputText from './input'
export default function Home() {
return (
<div>
<h1>Hello</h1>
<InputText />
</div>
)
}
...@@ -239,6 +239,17 @@ createNextDescribe( ...@@ -239,6 +239,17 @@ createNextDescribe(
}) })
}) })
describe('css ordering', () => {
it('should have inner layers take precedence over outer layers', async () => {
const browser = await next.browser('/ordering')
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('h1')).color`
)
).toBe('rgb(255, 0, 0)')
})
})
if (isDev) { if (isDev) {
describe('multiple entries', () => { describe('multiple entries', () => {
it('should only inject the same style once if used by different layers', async () => { it('should only inject the same style once if used by different layers', async () => {
......
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