Commit beb2ec17 authored by Jimmy Lai's avatar Jimmy Lai

refactor: move collectedInlineCss to AppRenderContext

Eliminates prop drilling of collectedInlineCss by adding it to ctx
(AppRenderContext). The CSS collector is now initialized once in the
ctx object and accessed via ctx.collectedInlineCss throughout the
render pipeline.

Changes:
- Add collectedInlineCss field to AppRenderContext type
- Initialize collectedInlineCss in ctx creation (single location)
- Remove separate variable declarations from renderToStream/prerenderToStream
- Remove collectedInlineCss parameter from getRSCPayload, createComponentTree,
  getLayerAssets, renderCssResource, and createComponentStylesAndScripts
- Update ~30 call sites to use ctx.collectedInlineCss
Co-Authored-By: 's avatarClaude Opus 4.5 <noreply@anthropic.com>
parent 228f69ba
......@@ -264,6 +264,12 @@ export type AppRenderContext = {
* work unit store.
*/
implicitTags: ImplicitTags
/**
* Collected inline CSS to be injected via ServerInsertedHTML.
* This avoids duplicating CSS in both the HTML (as <style> tags)
* and the RSC payload (serialized in <script> tags).
*/
collectedInlineCss: CollectedInlineCss
}
interface ParseRequestHeadersOptions {
......@@ -1425,8 +1431,7 @@ function getRenderedSearch(query: NextParsedUrlQuery): string {
async function getRSCPayload(
tree: LoaderTree,
ctx: AppRenderContext,
is404: boolean,
collectedInlineCss?: CollectedInlineCss
is404: boolean
): Promise<InitialRSCPayload & { P: ReactNode }> {
const injectedCSS = new Set<string>()
const injectedJS = new Set<string>()
......@@ -1485,7 +1490,6 @@ async function getRSCPayload(
preloadCallbacks,
authInterrupts: ctx.renderOpts.experimental.authInterrupts,
MetadataOutlet,
collectedInlineCss,
})
// When the `vary` response header is present with `Next-URL`, that means there's a chance
......@@ -2059,6 +2063,14 @@ async function renderToHTMLOrFlightImpl(
res,
sharedContext,
implicitTags,
// Collector for inline CSS to be injected via ServerInsertedHTML.
// This prevents CSS from being duplicated in both HTML (as <style> tags)
// and RSC payload (serialized in <script> tags).
collectedInlineCss: {
styles: [],
rootLayoutCSSPaths: new Set(),
inlineCssMode: renderOpts.experimental.inlineCss,
},
}
getTracer().setRootSpanAttribute('next.route', pagePath)
......@@ -2530,15 +2542,6 @@ async function renderToStream(
createServerInsertedHTML()
const getServerInsertedMetadata = createServerInsertedMetadata(nonce)
// Collector for inline CSS to be injected via ServerInsertedHTML.
// This prevents CSS from being duplicated in both HTML (as <style> tags)
// and RSC payload (serialized in <script> tags).
const collectedInlineCss: CollectedInlineCss = {
styles: [],
rootLayoutCSSPaths: new Set(),
inlineCssMode: experimental.inlineCss,
}
const tracingMetadata = getTracedMetadata(
getTracer().getTracePropagationData(),
experimental.clientTraceMetadata
......@@ -2681,8 +2684,7 @@ async function renderToStream(
getRSCPayload,
tree,
ctx,
res.statusCode === 404,
collectedInlineCss
res.statusCode === 404
)
if (isBypassingCachesInDev(renderOpts, requestStore)) {
......@@ -2792,8 +2794,7 @@ async function renderToStream(
getRSCPayload,
tree,
ctx,
res.statusCode === 404,
collectedInlineCss
res.statusCode === 404
)
const debugChannel = setReactDebugChannel && createDebugChannel()
......@@ -2885,7 +2886,7 @@ async function renderToStream(
serverCapturedErrors: allCapturedErrors,
basePath,
tracingMetadata: tracingMetadata,
collectedInlineCss,
collectedInlineCss: ctx.collectedInlineCss,
})
return await continueDynamicHTMLResume(htmlStream, {
// If the prelude is empty (i.e. is no static shell), we should wait for initial HTML to be rendered
......@@ -2949,7 +2950,7 @@ async function renderToStream(
serverCapturedErrors: allCapturedErrors,
basePath,
tracingMetadata: tracingMetadata,
collectedInlineCss,
collectedInlineCss: ctx.collectedInlineCss,
})
/**
* Rules of Static & Dynamic HTML:
......@@ -3157,7 +3158,7 @@ async function renderToStream(
serverCapturedErrors: [],
basePath,
tracingMetadata: tracingMetadata,
collectedInlineCss,
collectedInlineCss: ctx.collectedInlineCss,
}),
getServerInsertedMetadata,
validateRootLayout: dev,
......@@ -4148,15 +4149,6 @@ async function prerenderToStream(
createServerInsertedHTML()
const getServerInsertedMetadata = createServerInsertedMetadata(nonce)
// Collector for inline CSS to be injected via ServerInsertedHTML.
// This prevents CSS from being duplicated in both HTML (as <style> tags)
// and RSC payload (serialized in <script> tags).
const collectedInlineCss: CollectedInlineCss = {
styles: [],
rootLayoutCSSPaths: new Set(),
inlineCssMode: experimental.inlineCss,
}
const tracingMetadata = getTracedMetadata(
getTracer().getTracePropagationData(),
experimental.clientTraceMetadata
......@@ -4343,8 +4335,7 @@ async function prerenderToStream(
getRSCPayload,
tree,
ctx,
res.statusCode === 404,
collectedInlineCss
res.statusCode === 404
)
const initialServerPrerenderStore: PrerenderStore = (prerenderStore = {
......@@ -4618,8 +4609,7 @@ async function prerenderToStream(
getRSCPayload,
tree,
ctx,
res.statusCode === 404,
collectedInlineCss
res.statusCode === 404
)
const serverDynamicTracking = createDynamicTrackingState(
......@@ -4826,7 +4816,7 @@ async function prerenderToStream(
serverCapturedErrors: allCapturedErrors,
basePath,
tracingMetadata: tracingMetadata,
collectedInlineCss,
collectedInlineCss: ctx.collectedInlineCss,
})
const flightData = await streamToBuffer(reactServerResult.asStream())
......@@ -5027,8 +5017,7 @@ async function prerenderToStream(
getRSCPayload,
tree,
ctx,
res.statusCode === 404,
collectedInlineCss
res.statusCode === 404
)
const reactServerResult = (reactServerPrerenderResult =
await createReactServerPrerenderResultFromRender(
......@@ -5092,7 +5081,7 @@ async function prerenderToStream(
serverCapturedErrors: allCapturedErrors,
basePath,
tracingMetadata: tracingMetadata,
collectedInlineCss,
collectedInlineCss: ctx.collectedInlineCss,
})
// After awaiting here we've waited for the entire RSC render to complete. Crucially this means
......@@ -5275,8 +5264,7 @@ async function prerenderToStream(
getRSCPayload,
tree,
ctx,
res.statusCode === 404,
collectedInlineCss
res.statusCode === 404
)
const reactServerResult = (reactServerPrerenderResult =
......@@ -5333,7 +5321,7 @@ async function prerenderToStream(
serverCapturedErrors: allCapturedErrors,
basePath,
tracingMetadata: tracingMetadata,
collectedInlineCss,
collectedInlineCss: ctx.collectedInlineCss,
})
return {
digestErrorsMap: reactServerErrorsByDigest,
......@@ -5533,7 +5521,7 @@ async function prerenderToStream(
serverCapturedErrors: [],
basePath,
tracingMetadata: tracingMetadata,
collectedInlineCss,
collectedInlineCss: ctx.collectedInlineCss,
}),
getServerInsertedMetadata,
validateRootLayout: dev,
......
......@@ -4,7 +4,6 @@ import type { AppRenderContext } from './app-render'
import { getAssetQueryString } from './get-asset-query-string'
import { encodeURIPath } from '../../shared/lib/encode-uri-path'
import { renderCssResource } from './render-css-resource'
import type { CollectedInlineCss } from './types'
export async function createComponentStylesAndScripts({
filePath,
......@@ -12,14 +11,12 @@ export async function createComponentStylesAndScripts({
injectedCSS,
injectedJS,
ctx,
collectedInlineCss,
}: {
filePath: string
getComponent: () => any
injectedCSS: Set<string>
injectedJS: Set<string>
ctx: AppRenderContext
collectedInlineCss?: CollectedInlineCss
}): Promise<[React.ComponentType<any>, React.ReactNode, React.ReactNode]> {
const {
componentMod: { createElement },
......@@ -30,12 +27,7 @@ export async function createComponentStylesAndScripts({
injectedJS
)
const styles = renderCssResource(
entryCssFiles,
ctx,
undefined,
collectedInlineCss
)
const styles = renderCssResource(entryCssFiles, ctx)
const scripts = jsHrefs
? jsHrefs.map((href, index) =>
......
......@@ -3,7 +3,7 @@ import type {
CacheNodeSeedData,
LoadingModuleData,
} from '../../shared/lib/app-router-types'
import type { PreloadCallbacks, CollectedInlineCss } from './types'
import type { PreloadCallbacks } from './types'
import {
isClientReference,
isUseCacheFunction,
......@@ -52,7 +52,6 @@ export function createComponentTree(props: {
preloadCallbacks: PreloadCallbacks
authInterrupts: boolean
MetadataOutlet: ComponentType
collectedInlineCss?: CollectedInlineCss
}): Promise<CacheNodeSeedData> {
return getTracer().trace(
NextNodeServerSpan.createComponentTree,
......@@ -88,7 +87,6 @@ async function createComponentTreeInternal(
preloadCallbacks,
authInterrupts,
MetadataOutlet,
collectedInlineCss,
}: {
loaderTree: LoaderTree
parentParams: Params
......@@ -101,7 +99,6 @@ async function createComponentTreeInternal(
preloadCallbacks: PreloadCallbacks
authInterrupts: boolean
MetadataOutlet: ComponentType | null
collectedInlineCss?: CollectedInlineCss
},
isRoot: boolean
): Promise<CacheNodeSeedData> {
......@@ -162,7 +159,6 @@ async function createComponentTreeInternal(
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout,
collectedInlineCss,
isRootLayout: rootLayoutAtThisLevel,
})
......@@ -173,7 +169,6 @@ async function createComponentTreeInternal(
getComponent: template[0],
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
collectedInlineCss,
})
: [Fragment]
......@@ -184,7 +179,6 @@ async function createComponentTreeInternal(
getComponent: error[0],
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
collectedInlineCss,
})
: []
......@@ -195,7 +189,6 @@ async function createComponentTreeInternal(
getComponent: loading[0],
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
collectedInlineCss,
})
: []
......@@ -225,7 +218,6 @@ async function createComponentTreeInternal(
getComponent: notFound[0],
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
collectedInlineCss,
})
: []
......@@ -243,7 +235,6 @@ async function createComponentTreeInternal(
getComponent: forbidden[0],
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
collectedInlineCss,
})
: []
......@@ -255,7 +246,6 @@ async function createComponentTreeInternal(
getComponent: unauthorized[0],
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
collectedInlineCss,
})
: []
......@@ -549,7 +539,6 @@ async function createComponentTreeInternal(
// `StreamingMetadataOutlet` is used to conditionally throw. In the case of parallel routes we will have more than one page
// but we only want to throw on the first one.
MetadataOutlet: isChildrenRouteKey ? MetadataOutlet : null,
collectedInlineCss,
},
false
)
......
......@@ -3,7 +3,7 @@ import { getPreloadableFonts } from './get-preloadable-fonts'
import type { AppRenderContext } from './app-render'
import { getAssetQueryString } from './get-asset-query-string'
import { encodeURIPath } from '../../shared/lib/encode-uri-path'
import type { PreloadCallbacks, CollectedInlineCss } from './types'
import type { PreloadCallbacks } from './types'
import { renderCssResource } from './render-css-resource'
export function getLayerAssets({
......@@ -13,7 +13,6 @@ export function getLayerAssets({
injectedJS: injectedJSWithCurrentLayout,
injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout,
preloadCallbacks,
collectedInlineCss,
isRootLayout,
}: {
layoutOrPagePath: string | undefined
......@@ -22,7 +21,6 @@ export function getLayerAssets({
injectedFontPreloadTags: Set<string>
ctx: AppRenderContext
preloadCallbacks: PreloadCallbacks
collectedInlineCss?: CollectedInlineCss
isRootLayout?: boolean
}): React.ReactNode {
const {
......@@ -39,9 +37,9 @@ export function getLayerAssets({
// Track root layout CSS paths for inlineCss: 'shared' mode
// Root layout CSS is guaranteed to be shared across all pages
if (isRootLayout && collectedInlineCss && styleTags.length > 0) {
if (isRootLayout && styleTags.length > 0) {
for (const css of styleTags) {
collectedInlineCss.rootLayoutCSSPaths.add(css.path)
ctx.collectedInlineCss.rootLayoutCSSPaths.add(css.path)
}
}
......@@ -86,12 +84,7 @@ export function getLayerAssets({
}
}
const styles = renderCssResource(
styleTags,
ctx,
preloadCallbacks,
collectedInlineCss
)
const styles = renderCssResource(styleTags, ctx, preloadCallbacks)
const scripts = scriptTags
? scriptTags.map((href, index) => {
......
......@@ -2,7 +2,7 @@ import type { CssResource } from '../../build/webpack/plugins/flight-manifest-pl
import { encodeURIPath } from '../../shared/lib/encode-uri-path'
import type { AppRenderContext } from './app-render'
import { getAssetQueryString } from './get-asset-query-string'
import type { PreloadCallbacks, CollectedInlineCss } from './types'
import type { PreloadCallbacks } from './types'
/**
* Abstracts the rendering of CSS files based on whether they are inlined or not.
......@@ -21,15 +21,15 @@ import type { PreloadCallbacks, CollectedInlineCss } from './types'
export function renderCssResource(
entryCssFiles: CssResource[],
ctx: AppRenderContext,
preloadCallbacks?: PreloadCallbacks,
collectedInlineCss?: CollectedInlineCss
preloadCallbacks?: PreloadCallbacks
) {
const {
componentMod: { createElement },
collectedInlineCss,
} = ctx
const inlineCssMode = collectedInlineCss?.inlineCssMode
const rootLayoutCSSPaths = collectedInlineCss?.rootLayoutCSSPaths
const inlineCssMode = collectedInlineCss.inlineCssMode
const rootLayoutCSSPaths = collectedInlineCss.rootLayoutCSSPaths
return entryCssFiles
.map((entryCssFile, index) => {
......@@ -55,7 +55,7 @@ export function renderCssResource(
)}${getAssetQueryString(ctx, true)}`
// Check if this CSS is from the root layout (shared across all pages)
const isRootLayoutCSS = rootLayoutCSSPaths?.has(entryCssFile.path)
const isRootLayoutCSS = rootLayoutCSSPaths.has(entryCssFile.path)
const isRSCRequest = ctx.parsedRequestHeaders.isRSCRequest
// Handle inlineCss: 'shared' mode
......@@ -66,7 +66,7 @@ export function renderCssResource(
}
// Initial HTML: collect for ServerInsertedHTML injection
if (entryCssFile.inlined) {
collectedInlineCss!.styles.push({
collectedInlineCss.styles.push({
href: fullHref,
content: entryCssFile.content!,
precedence: precedence,
......
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