Unverified Commit 601e964e authored by Shu Ding's avatar Shu Ding Committed by GitHub

Colocate styles with special entries (#42506)

This PR ensures that in app dir, styles imported in loading.js,
error.js, not-found.js, and template.js are properly handled and
rendered together with these components.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
parent f975e3f7
...@@ -1095,7 +1095,9 @@ export const collectGenerateParams = async ( ...@@ -1095,7 +1095,9 @@ export const collectGenerateParams = async (
): Promise<GenerateParams> => { ): Promise<GenerateParams> => {
if (!Array.isArray(segment)) return generateParams if (!Array.isArray(segment)) return generateParams
const isLayout = !!segment[2]?.layout const isLayout = !!segment[2]?.layout
const mod = await (isLayout ? segment[2]?.layout?.() : segment[2]?.page?.()) const mod = await (isLayout
? segment[2]?.layout?.[0]?.()
: segment[2]?.page?.[0]?.())
const config = collectAppConfig(mod) const config = collectAppConfig(mod)
const result = { const result = {
......
...@@ -21,11 +21,11 @@ const PAGE_SEGMENT = 'page$' ...@@ -21,11 +21,11 @@ const PAGE_SEGMENT = 'page$'
// TODO-APP: check if this can be narrowed. // TODO-APP: check if this can be narrowed.
type ComponentModule = () => any type ComponentModule = () => any
type ModuleReference = [componentModule: ComponentModule, filePath: string]
export type ComponentsType = { export type ComponentsType = {
readonly [componentKey in ValueOf<typeof FILE_TYPES>]?: ComponentModule readonly [componentKey in ValueOf<typeof FILE_TYPES>]?: ModuleReference
} & { } & {
readonly layoutOrPagePath?: string readonly page?: ModuleReference
readonly page?: ComponentModule
} }
async function createTreeCodeFromPath({ async function createTreeCodeFromPath({
...@@ -67,9 +67,10 @@ async function createTreeCodeFromPath({ ...@@ -67,9 +67,10 @@ async function createTreeCodeFromPath({
if (resolvedPagePath) pages.push(resolvedPagePath) if (resolvedPagePath) pages.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. // 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[parallelKey] = `['', {}, {layoutOrPagePath: ${JSON.stringify( props[parallelKey] = `['', {}, {
resolvedPagePath page: [() => require(${JSON.stringify(
)}, page: () => require(${JSON.stringify(resolvedPagePath)})}]` resolvedPagePath
)}), ${JSON.stringify(resolvedPagePath)}]}]`
continue continue
} }
...@@ -105,11 +106,9 @@ async function createTreeCodeFromPath({ ...@@ -105,11 +106,9 @@ async function createTreeCodeFromPath({
if (filePath === undefined) { if (filePath === undefined) {
return '' return ''
} }
return `${ return `'${file}': [() => require(${JSON.stringify(
file === FILE_TYPES.layout filePath
? `layoutOrPagePath: ${JSON.stringify(filePath)},` )}), ${JSON.stringify(filePath)}],`
: ''
}'${file}': () => require(${JSON.stringify(filePath)}),`
}) })
.join('\n')} .join('\n')}
} }
......
...@@ -179,17 +179,18 @@ export class FlightClientEntryPlugin { ...@@ -179,17 +179,18 @@ export class FlightClientEntryPlugin {
for (const connection of compilation.moduleGraph.getOutgoingConnections( for (const connection of compilation.moduleGraph.getOutgoingConnections(
entryModule entryModule
)) { )) {
const layoutOrPageDependency = connection.dependency // Entry can be any user defined entry files such as layout, page, error, loading, etc.
const layoutOrPageRequest = connection.dependency.request const entryDependency = connection.dependency
const entryRequest = connection.dependency.request
const [clientComponentImports] = const [clientComponentImports] =
this.collectClientComponentsAndCSSForDependency({ this.collectClientComponentsAndCSSForDependency({
layoutOrPageRequest, entryRequest,
compilation, compilation,
dependency: layoutOrPageDependency, dependency: entryDependency,
}) })
const isAbsoluteRequest = path.isAbsolute(layoutOrPageRequest) const isAbsoluteRequest = path.isAbsolute(entryRequest)
// Next.js internals are put into a separate entry. // Next.js internals are put into a separate entry.
if (!isAbsoluteRequest) { if (!isAbsoluteRequest) {
...@@ -200,8 +201,8 @@ export class FlightClientEntryPlugin { ...@@ -200,8 +201,8 @@ export class FlightClientEntryPlugin {
} }
const relativeRequest = isAbsoluteRequest const relativeRequest = isAbsoluteRequest
? path.relative(compilation.options.context, layoutOrPageRequest) ? path.relative(compilation.options.context, entryRequest)
: layoutOrPageRequest : entryRequest
// Replace file suffix as `.js` will be added. // Replace file suffix as `.js` will be added.
const bundlePath = relativeRequest.replace(/\.(js|ts)x?$/, '') const bundlePath = relativeRequest.replace(/\.(js|ts)x?$/, '')
...@@ -308,14 +309,14 @@ export class FlightClientEntryPlugin { ...@@ -308,14 +309,14 @@ export class FlightClientEntryPlugin {
for (const connection of compilation.moduleGraph.getOutgoingConnections( for (const connection of compilation.moduleGraph.getOutgoingConnections(
entryModule entryModule
)) { )) {
const layoutOrPageDependency = connection.dependency const entryDependency = connection.dependency
const layoutOrPageRequest = connection.dependency.request const entryRequest = connection.dependency.request
const [, cssImports] = const [, cssImports] =
this.collectClientComponentsAndCSSForDependency({ this.collectClientComponentsAndCSSForDependency({
layoutOrPageRequest, entryRequest,
compilation, compilation,
dependency: layoutOrPageDependency, dependency: entryDependency,
clientEntryDependencyMap, clientEntryDependencyMap,
}) })
...@@ -353,12 +354,12 @@ export class FlightClientEntryPlugin { ...@@ -353,12 +354,12 @@ export class FlightClientEntryPlugin {
} }
collectClientComponentsAndCSSForDependency({ collectClientComponentsAndCSSForDependency({
layoutOrPageRequest, entryRequest,
compilation, compilation,
dependency, dependency,
clientEntryDependencyMap, clientEntryDependencyMap,
}: { }: {
layoutOrPageRequest: string entryRequest: string
compilation: any compilation: any
dependency: any /* Dependency */ dependency: any /* Dependency */
clientEntryDependencyMap?: Record<string, any> clientEntryDependencyMap?: Record<string, any>
...@@ -397,15 +398,15 @@ export class FlightClientEntryPlugin { ...@@ -397,15 +398,15 @@ export class FlightClientEntryPlugin {
: mod.resourceResolveData?.path + mod.resourceResolveData?.query : mod.resourceResolveData?.path + mod.resourceResolveData?.query
// Ensure module is not walked again if it's already been visited // Ensure module is not walked again if it's already been visited
if (!visitedBySegment[layoutOrPageRequest]) { if (!visitedBySegment[entryRequest]) {
visitedBySegment[layoutOrPageRequest] = new Set() visitedBySegment[entryRequest] = new Set()
} }
const storeKey = const storeKey =
(inClientComponentBoundary ? '0' : '1') + ':' + modRequest (inClientComponentBoundary ? '0' : '1') + ':' + modRequest
if (!modRequest || visitedBySegment[layoutOrPageRequest].has(storeKey)) { if (!modRequest || visitedBySegment[entryRequest].has(storeKey)) {
return return
} }
visitedBySegment[layoutOrPageRequest].add(storeKey) visitedBySegment[entryRequest].add(storeKey)
const isClientComponent = isClientComponentModule(mod) const isClientComponent = isClientComponentModule(mod)
...@@ -425,9 +426,8 @@ export class FlightClientEntryPlugin { ...@@ -425,9 +426,8 @@ export class FlightClientEntryPlugin {
} }
} }
serverCSSImports[layoutOrPageRequest] = serverCSSImports[entryRequest] = serverCSSImports[entryRequest] || []
serverCSSImports[layoutOrPageRequest] || [] serverCSSImports[entryRequest].push(modRequest)
serverCSSImports[layoutOrPageRequest].push(modRequest)
} }
// Check if request is for css file. // Check if request is for css file.
......
...@@ -6,6 +6,7 @@ export type ErrorComponent = React.ComponentType<{ ...@@ -6,6 +6,7 @@ export type ErrorComponent = React.ComponentType<{
}> }>
interface ErrorBoundaryProps { interface ErrorBoundaryProps {
errorComponent: ErrorComponent errorComponent: ErrorComponent
errorStyles?: React.ReactNode | undefined
} }
/** /**
...@@ -32,10 +33,13 @@ class ErrorBoundaryHandler extends React.Component< ...@@ -32,10 +33,13 @@ class ErrorBoundaryHandler extends React.Component<
render() { render() {
if (this.state.error) { if (this.state.error) {
return ( return (
<this.props.errorComponent <>
error={this.state.error} {this.props.errorStyles}
reset={this.reset} <this.props.errorComponent
/> error={this.state.error}
reset={this.reset}
/>
</>
) )
} }
...@@ -49,11 +53,15 @@ class ErrorBoundaryHandler extends React.Component< ...@@ -49,11 +53,15 @@ class ErrorBoundaryHandler extends React.Component<
*/ */
export function ErrorBoundary({ export function ErrorBoundary({
errorComponent, errorComponent,
errorStyles,
children, children,
}: ErrorBoundaryProps & { children: React.ReactNode }): JSX.Element { }: ErrorBoundaryProps & { children: React.ReactNode }): JSX.Element {
if (errorComponent) { if (errorComponent) {
return ( return (
<ErrorBoundaryHandler errorComponent={errorComponent}> <ErrorBoundaryHandler
errorComponent={errorComponent}
errorStyles={errorStyles}
>
{children} {children}
</ErrorBoundaryHandler> </ErrorBoundaryHandler>
) )
......
...@@ -257,15 +257,27 @@ export function InnerLayoutRouter({ ...@@ -257,15 +257,27 @@ export function InnerLayoutRouter({
function LoadingBoundary({ function LoadingBoundary({
children, children,
loading, loading,
loadingStyles,
hasLoading, hasLoading,
}: { }: {
children: React.ReactNode children: React.ReactNode
loading?: React.ReactNode loading?: React.ReactNode
loadingStyles?: React.ReactNode
hasLoading: boolean hasLoading: boolean
}): JSX.Element { }): JSX.Element {
if (hasLoading) { if (hasLoading) {
// @ts-expect-error TODO-APP: React.Suspense fallback type is wrong return (
return <React.Suspense fallback={loading}>{children}</React.Suspense> <React.Suspense
fallback={
<>
{loadingStyles}
{loading}
</>
}
>
{children}
</React.Suspense>
)
} }
return <>{children}</> return <>{children}</>
...@@ -322,6 +334,7 @@ function RedirectBoundary({ children }: { children: React.ReactNode }) { ...@@ -322,6 +334,7 @@ function RedirectBoundary({ children }: { children: React.ReactNode }) {
interface NotFoundBoundaryProps { interface NotFoundBoundaryProps {
notFound?: React.ReactNode notFound?: React.ReactNode
notFoundStyles?: React.ReactNode
children: React.ReactNode children: React.ReactNode
} }
...@@ -347,6 +360,7 @@ class NotFoundErrorBoundary extends React.Component< ...@@ -347,6 +360,7 @@ class NotFoundErrorBoundary extends React.Component<
return ( return (
<> <>
<meta name="robots" content="noindex" /> <meta name="robots" content="noindex" />
{this.props.notFoundStyles}
{this.props.notFound} {this.props.notFound}
</> </>
) )
...@@ -356,9 +370,13 @@ class NotFoundErrorBoundary extends React.Component< ...@@ -356,9 +370,13 @@ class NotFoundErrorBoundary extends React.Component<
} }
} }
function NotFoundBoundary({ notFound, children }: NotFoundBoundaryProps) { function NotFoundBoundary({
notFound,
notFoundStyles,
children,
}: NotFoundBoundaryProps) {
return notFound ? ( return notFound ? (
<NotFoundErrorBoundary notFound={notFound}> <NotFoundErrorBoundary notFound={notFound} notFoundStyles={notFoundStyles}>
{children} {children}
</NotFoundErrorBoundary> </NotFoundErrorBoundary>
) : ( ) : (
...@@ -375,20 +393,28 @@ export default function OuterLayoutRouter({ ...@@ -375,20 +393,28 @@ export default function OuterLayoutRouter({
segmentPath, segmentPath,
childProp, childProp,
error, error,
errorStyles,
templateStyles,
loading, loading,
loadingStyles,
hasLoading, hasLoading,
template, template,
notFound, notFound,
notFoundStyles,
rootLayoutIncluded, rootLayoutIncluded,
}: { }: {
parallelRouterKey: string parallelRouterKey: string
segmentPath: FlightSegmentPath segmentPath: FlightSegmentPath
childProp: ChildProp childProp: ChildProp
error: ErrorComponent error: ErrorComponent
errorStyles: React.ReactNode | undefined
templateStyles: React.ReactNode | undefined
template: React.ReactNode template: React.ReactNode
loading: React.ReactNode | undefined loading: React.ReactNode | undefined
loadingStyles: React.ReactNode | undefined
hasLoading: boolean hasLoading: boolean
notFound: React.ReactNode | undefined notFound: React.ReactNode | undefined
notFoundStyles: React.ReactNode | undefined
rootLayoutIncluded: boolean rootLayoutIncluded: boolean
}) { }) {
const context = useContext(LayoutRouterContext) const context = useContext(LayoutRouterContext)
...@@ -442,9 +468,16 @@ export default function OuterLayoutRouter({ ...@@ -442,9 +468,16 @@ export default function OuterLayoutRouter({
<TemplateContext.Provider <TemplateContext.Provider
key={preservedSegment} key={preservedSegment}
value={ value={
<ErrorBoundary errorComponent={error}> <ErrorBoundary errorComponent={error} errorStyles={errorStyles}>
<LoadingBoundary hasLoading={hasLoading} loading={loading}> <LoadingBoundary
<NotFoundBoundary notFound={notFound}> hasLoading={hasLoading}
loading={loading}
loadingStyles={loadingStyles}
>
<NotFoundBoundary
notFound={notFound}
notFoundStyles={notFoundStyles}
>
<RedirectBoundary> <RedirectBoundary>
<InnerLayoutRouter <InnerLayoutRouter
parallelRouterKey={parallelRouterKey} parallelRouterKey={parallelRouterKey}
...@@ -467,7 +500,10 @@ export default function OuterLayoutRouter({ ...@@ -467,7 +500,10 @@ export default function OuterLayoutRouter({
</ErrorBoundary> </ErrorBoundary>
} }
> >
{template} <>
{templateStyles}
{template}
</>
</TemplateContext.Provider> </TemplateContext.Provider>
) )
})} })}
......
...@@ -915,7 +915,7 @@ export async function renderToHTMLOrFlight( ...@@ -915,7 +915,7 @@ export async function renderToHTMLOrFlight(
} }
if (head) { if (head) {
const Head = await interopDefault(head()) const Head = await interopDefault(head[0]())
return <Head params={currentParams} /> return <Head params={currentParams} />
} }
...@@ -965,6 +965,39 @@ export async function renderToHTMLOrFlight( ...@@ -965,6 +965,39 @@ export async function renderToHTMLOrFlight(
const assetPrefix = renderOpts.assetPrefix || '' const assetPrefix = renderOpts.assetPrefix || ''
const createComponentAndStyles = async ({
filePath,
getComponent,
shouldPreload,
}: {
filePath: string
getComponent: () => any
shouldPreload?: boolean
}): Promise<any> => {
const cssHrefs = getCssInlinedLinkTags(
serverComponentManifest,
serverCSSManifest,
filePath,
serverCSSForEntries
)
const cacheBustingUrlSuffix = dev ? `?ts=${Date.now()}` : ''
const styles = cssHrefs
? cssHrefs.map((href, index) => (
<link
rel="stylesheet"
href={`${assetPrefix}/_next/${href}${cacheBustingUrlSuffix}`}
// @ts-ignore
precedence={shouldPreload ? 'high' : undefined}
key={index}
/>
))
: null
const Comp = await interopDefault(getComponent())
return [Comp, styles]
}
/** /**
* Use the provided loader tree to create the React Component tree. * Use the provided loader tree to create the React Component tree.
*/ */
...@@ -973,15 +1006,7 @@ export async function renderToHTMLOrFlight( ...@@ -973,15 +1006,7 @@ export async function renderToHTMLOrFlight(
loaderTree: [ loaderTree: [
segment, segment,
parallelRoutes, parallelRoutes,
{ { layout, template, error, loading, page, 'not-found': notFound },
layoutOrPagePath,
layout,
template,
error,
loading,
page,
'not-found': notFound,
},
], ],
parentParams, parentParams,
firstItem, firstItem,
...@@ -993,7 +1018,7 @@ export async function renderToHTMLOrFlight( ...@@ -993,7 +1018,7 @@ export async function renderToHTMLOrFlight(
rootLayoutIncluded?: boolean rootLayoutIncluded?: boolean
firstItem?: boolean firstItem?: boolean
}): Promise<{ Component: React.ComponentType }> => { }): Promise<{ Component: React.ComponentType }> => {
// TODO-APP: enable stylesheet per layout/page const layoutOrPagePath = layout?.[1] || page?.[1]
const stylesheets: string[] = layoutOrPagePath const stylesheets: string[] = layoutOrPagePath
? getCssInlinedLinkTags( ? getCssInlinedLinkTags(
serverComponentManifest, serverComponentManifest,
...@@ -1003,25 +1028,46 @@ export async function renderToHTMLOrFlight( ...@@ -1003,25 +1028,46 @@ export async function renderToHTMLOrFlight(
) )
: [] : []
const preloadedFontFiles = getPreloadedFontFilesInlineLinkTags( const preloadedFontFiles = layoutOrPagePath
serverComponentManifest, ? getPreloadedFontFilesInlineLinkTags(
serverCSSManifest!, serverComponentManifest,
fontLoaderManifest, serverCSSManifest!,
serverCSSForEntries, fontLoaderManifest,
layoutOrPagePath serverCSSForEntries,
) layoutOrPagePath
const Template = template )
? await interopDefault(template()) : []
: React.Fragment
const ErrorComponent = error ? await interopDefault(error()) : undefined const [Template, templateStyles] = template
const Loading = loading ? await interopDefault(loading()) : undefined ? await createComponentAndStyles({
filePath: template[1],
getComponent: template[0],
shouldPreload: true,
})
: [React.Fragment]
const [ErrorComponent, errorStyles] = error
? await createComponentAndStyles({
filePath: error[1],
getComponent: error[0],
})
: []
const [Loading, loadingStyles] = loading
? await createComponentAndStyles({
filePath: loading[1],
getComponent: loading[0],
})
: []
const isLayout = typeof layout !== 'undefined' const isLayout = typeof layout !== 'undefined'
const isPage = typeof page !== 'undefined' const isPage = typeof page !== 'undefined'
const layoutOrPageMod = isLayout const layoutOrPageMod = isLayout
? await layout() ? await layout[0]()
: isPage : isPage
? await page() ? await page[0]()
: undefined : undefined
/** /**
* Checks if the current segment is a root layout. * Checks if the current segment is a root layout.
*/ */
...@@ -1032,11 +1078,14 @@ export async function renderToHTMLOrFlight( ...@@ -1032,11 +1078,14 @@ export async function renderToHTMLOrFlight(
const rootLayoutIncludedAtThisLevelOrAbove = const rootLayoutIncludedAtThisLevelOrAbove =
rootLayoutIncluded || rootLayoutAtThisLevel rootLayoutIncluded || rootLayoutAtThisLevel
const NotFound = notFound const [NotFound, notFoundStyles] = notFound
? await interopDefault(notFound()) ? await createComponentAndStyles({
filePath: notFound[1],
getComponent: notFound[0],
})
: rootLayoutAtThisLevel : rootLayoutAtThisLevel
? DefaultNotFound ? [DefaultNotFound]
: undefined : []
if (typeof layoutOrPageMod?.revalidate === 'number') { if (typeof layoutOrPageMod?.revalidate === 'number') {
defaultRevalidate = layoutOrPageMod.revalidate defaultRevalidate = layoutOrPageMod.revalidate
...@@ -1147,14 +1196,18 @@ export async function renderToHTMLOrFlight( ...@@ -1147,14 +1196,18 @@ export async function renderToHTMLOrFlight(
parallelRouterKey={parallelRouteKey} parallelRouterKey={parallelRouteKey}
segmentPath={createSegmentPath(currentSegmentPath)} segmentPath={createSegmentPath(currentSegmentPath)}
loading={Loading ? <Loading /> : undefined} loading={Loading ? <Loading /> : undefined}
loadingStyles={loadingStyles}
hasLoading={Boolean(Loading)} hasLoading={Boolean(Loading)}
error={ErrorComponent} error={ErrorComponent}
errorStyles={errorStyles}
template={ template={
<Template> <Template>
<RenderFromTemplateContext /> <RenderFromTemplateContext />
</Template> </Template>
} }
templateStyles={templateStyles}
notFound={NotFound ? <NotFound /> : undefined} notFound={NotFound ? <NotFound /> : undefined}
notFoundStyles={notFoundStyles}
childProp={childProp} childProp={childProp}
rootLayoutIncluded={rootLayoutIncludedAtThisLevelOrAbove} rootLayoutIncluded={rootLayoutIncludedAtThisLevelOrAbove}
/>, />,
...@@ -1187,7 +1240,9 @@ export async function renderToHTMLOrFlight( ...@@ -1187,7 +1240,9 @@ export async function renderToHTMLOrFlight(
parallelRouterKey={parallelRouteKey} parallelRouterKey={parallelRouteKey}
segmentPath={segmentPath} segmentPath={segmentPath}
error={ErrorComponent} error={ErrorComponent}
errorStyles={errorStyles}
loading={Loading ? <Loading /> : undefined} loading={Loading ? <Loading /> : undefined}
loadingStyles={loadingStyles}
// TODO-APP: Add test for loading returning `undefined`. This currently can't be tested as the `webdriver()` tab will wait for the full page to load before returning. // TODO-APP: Add test for loading returning `undefined`. This currently can't be tested as the `webdriver()` tab will wait for the full page to load before returning.
hasLoading={Boolean(Loading)} hasLoading={Boolean(Loading)}
template={ template={
...@@ -1195,7 +1250,9 @@ export async function renderToHTMLOrFlight( ...@@ -1195,7 +1250,9 @@ export async function renderToHTMLOrFlight(
<RenderFromTemplateContext /> <RenderFromTemplateContext />
</Template> </Template>
} }
templateStyles={templateStyles}
notFound={NotFound ? <NotFound /> : undefined} notFound={NotFound ? <NotFound /> : undefined}
notFoundStyles={notFoundStyles}
childProp={childProp} childProp={childProp}
rootLayoutIncluded={rootLayoutIncludedAtThisLevelOrAbove} rootLayoutIncluded={rootLayoutIncludedAtThisLevelOrAbove}
/>, />,
......
'use client' 'use client'
import styles from './style.module.css'
export default function ErrorBoundary({ error, reset }) { export default function ErrorBoundary({ error, reset }) {
return ( return (
<> <>
<p id="error-boundary-message">An error occurred: {error.message}</p> <p id="error-boundary-message">An error occurred: {error.message}</p>
<button id="reset" onClick={() => reset()}> <button id="reset" onClick={() => reset()} className={styles.button}>
Try again Try again
</button> </button>
</> </>
......
import './style.css'
export default function Loading() { export default function Loading() {
return <h2>Loading...</h2> return <h2>Loading...</h2>
} }
import styles from './style.module.css'
export default function NotFound() { export default function NotFound() {
return <h1 id="not-found-component">Not Found!</h1> return (
<h1 id="not-found-component" className={styles.red}>
Not Found!
</h1>
)
} }
'use client' 'use client'
import { useState } from 'react' import { useState } from 'react'
import styles from './style.module.css'
export default function Template({ children }) { export default function Template({ children }) {
const [count, setCount] = useState(0) const [count, setCount] = useState(0)
return ( return (
<> <>
<h1>Template {count}</h1> <h1>Template {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button> <button className={styles.button} onClick={() => setCount(count + 1)}>
Increment
</button>
{children} {children}
</> </>
) )
......
import styles from './style.module.css'
export default function Template({ children }) { export default function Template({ children }) {
return ( return (
<> <>
<h1> <h1 className={styles.red}>
Template <span id="performance-now">{performance.now()}</span> Template <span id="performance-now">{performance.now()}</span>
</h1> </h1>
{children} {children}
......
...@@ -1507,6 +1507,72 @@ describe('app dir', () => { ...@@ -1507,6 +1507,72 @@ describe('app dir', () => {
).toBe('100px') ).toBe('100px')
}) })
}) })
describe('special entries', () => {
it('should include css imported in loading.js', async () => {
const html = await renderViaHTTP(next.url, '/loading-bug/hi')
// The link tag should be included together with loading
expect(html).toMatch(
/<link rel="stylesheet" href="(.+)\.css(\?ts=\d+)?"\/><h2>Loading...<\/h2>/
)
})
it('should include css imported in client template.js', async () => {
const browser = await webdriver(next.url, '/template/clientcomponent')
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('button')).fontSize`
)
).toBe('100px')
})
it('should include css imported in server template.js', async () => {
const browser = await webdriver(next.url, '/template/servercomponent')
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('h1')).color`
)
).toBe('rgb(255, 0, 0)')
})
it('should include css imported in client not-found.js', async () => {
const browser = await webdriver(
next.url,
'/not-found/clientcomponent'
)
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('h1')).color`
)
).toBe('rgb(255, 0, 0)')
})
it('should include css imported in server not-found.js', async () => {
const browser = await webdriver(
next.url,
'/not-found/servercomponent'
)
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('h1')).color`
)
).toBe('rgb(255, 0, 0)')
})
it('should include css imported in error.js', async () => {
const browser = await webdriver(next.url, '/error/client-component')
await browser.elementByCss('button').click()
// Wait for error page to render and CSS to be loaded
await new Promise((resolve) => setTimeout(resolve, 2000))
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('button')).fontSize`
)
).toBe('50px')
})
})
}) })
describe('searchParams prop', () => { describe('searchParams prop', () => {
......
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