Unverified Commit 6dbf9c32 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Handle dynamic css-in-js styles under suspense (#42293)

We insert the content returning from `useServerInsertedHTML` to head
element for app dir, but it shouldn't only inject once since there're
suspense boundaries that could hold insertions.

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have a helpful link attached, see `contributing.md`
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 66dc68f9
...@@ -196,7 +196,7 @@ ...@@ -196,7 +196,7 @@
"selenium-webdriver": "4.0.0-beta.4", "selenium-webdriver": "4.0.0-beta.4",
"semver": "7.3.7", "semver": "7.3.7",
"shell-quote": "1.7.3", "shell-quote": "1.7.3",
"styled-components": "5.3.3", "styled-components": "6.0.0-beta.5",
"styled-jsx-plugin-postcss": "3.0.2", "styled-jsx-plugin-postcss": "3.0.2",
"swr": "2.0.0-rc.0", "swr": "2.0.0-rc.0",
"tailwindcss": "1.1.3", "tailwindcss": "1.1.3",
......
import type { FlightRouterState } from './app-render' import type { FlightRouterState } from './app-render'
import { nonNullable } from '../lib/non-nullable' import { nonNullable } from '../lib/non-nullable'
const queueTask =
process.env.NEXT_RUNTIME === 'edge' ? globalThis.setTimeout : setImmediate
export type ReactReadableStream = ReadableStream<Uint8Array> & { export type ReactReadableStream = ReadableStream<Uint8Array> & {
allReady?: Promise<void> | undefined allReady?: Promise<void> | undefined
} }
...@@ -149,21 +152,43 @@ export function renderToInitialStream({ ...@@ -149,21 +152,43 @@ export function renderToInitialStream({
return ReactDOMServer.renderToReadableStream(element, streamOptions) return ReactDOMServer.renderToReadableStream(element, streamOptions)
} }
export function createHeadInjectionTransformStream( function createHeadInsertionTransformStream(
inject: () => Promise<string> insert: () => Promise<string>
): TransformStream<Uint8Array, Uint8Array> { ): TransformStream<Uint8Array, Uint8Array> {
let injected = false let inserted = false
let freezing = false
return new TransformStream({ return new TransformStream({
async transform(chunk, controller) { async transform(chunk, controller) {
const content = decodeText(chunk) // While react is flushing chunks, we don't apply insertions
let index if (freezing) {
if (!injected && (index = content.indexOf('</head')) !== -1) { controller.enqueue(chunk)
injected = true return
const injectedContent = }
content.slice(0, index) + (await inject()) + content.slice(index)
controller.enqueue(encodeText(injectedContent)) const insertion = await insert()
if (inserted) {
controller.enqueue(encodeText(insertion))
controller.enqueue(chunk)
freezing = true
} else { } else {
const content = decodeText(chunk)
const index = content.indexOf('</head')
if (index !== -1) {
const insertedHeadContent =
content.slice(0, index) + insertion + content.slice(index)
controller.enqueue(encodeText(insertedHeadContent))
freezing = true
inserted = true
}
}
if (!inserted) {
controller.enqueue(chunk) controller.enqueue(chunk)
} else {
queueTask(() => {
freezing = false
})
} }
}, },
}) })
...@@ -333,7 +358,7 @@ export async function continueFromInitialStream( ...@@ -333,7 +358,7 @@ export async function continueFromInitialStream(
suffixUnclosed != null ? createDeferredSuffixStream(suffixUnclosed) : null, suffixUnclosed != null ? createDeferredSuffixStream(suffixUnclosed) : null,
dataStream ? createInlineDataStream(dataStream) : null, dataStream ? createInlineDataStream(dataStream) : null,
suffixUnclosed != null ? createSuffixStream(closeTag) : null, suffixUnclosed != null ? createSuffixStream(closeTag) : null,
createHeadInjectionTransformStream(async () => { createHeadInsertionTransformStream(async () => {
// TODO-APP: Insert server side html to end of head in app layout rendering, to avoid // TODO-APP: Insert server side html to end of head in app layout rendering, to avoid
// hydration errors. Remove this once it's ready to be handled by react itself. // hydration errors. Remove this once it's ready to be handled by react itself.
const serverInsertedHTML = const serverInsertedHTML =
......
This diff is collapsed.
...@@ -38,7 +38,7 @@ describe('app dir - rsc basics', () => { ...@@ -38,7 +38,7 @@ describe('app dir - rsc basics', () => {
next = await createNext({ next = await createNext({
files: new FileRef(path.join(__dirname, './rsc-basic')), files: new FileRef(path.join(__dirname, './rsc-basic')),
dependencies: { dependencies: {
'styled-components': '6.0.0-beta.2', 'styled-components': '6.0.0-beta.5',
react: 'latest', react: 'latest',
'react-dom': 'latest', 'react-dom': 'latest',
}, },
...@@ -309,11 +309,55 @@ describe('app dir - rsc basics', () => { ...@@ -309,11 +309,55 @@ describe('app dir - rsc basics', () => {
// from styled-components // from styled-components
expect(head).toMatch(/{color:(\s*)blue;?}/) expect(head).toMatch(/{color:(\s*)blue;?}/)
})
it('should render css-in-js suspense boundary correctly', async () => {
await fetchViaHTTP(next.url, '/css-in-js/suspense', null, {}).then(
async (response) => {
const results = []
await resolveStreamResponse(response, (chunk: string) => {
// check if rsc refresh script for suspense show up, the test content could change with react version
const hasRCScript = /\$RC=function/.test(chunk)
if (hasRCScript) results.push('refresh-script')
// css-in-js like styled-jsx in server components won't be transformed const isSuspenseyDataResolved =
expect(html).toMatch( /<style[^<>]*>(\s)*.+{padding:2px;(\s)*color:orange;}/.test(chunk)
/<style>\s*\.this-wont-be-transformed\s*\{\s*color:\s*purple;\s*\}\s*<\/style>/ if (isSuspenseyDataResolved) results.push('data')
const isFallbackResolved = chunk.includes('fallback')
if (isFallbackResolved) results.push('fallback')
})
expect(results).toEqual(['fallback', 'data', 'refresh-script'])
}
) )
// // TODO-APP: fix streaming/suspense within browser for test suite
// const browser = await webdriver(next.url, '/css-in-js', { waitHydration: false })
// const footer = await browser.elementByCss('#footer')
// expect(await footer.text()).toBe('wait for fallback')
// expect(
// await browser.eval(
// `window.getComputedStyle(document.querySelector('#footer')).borderColor`
// )
// ).toBe('rgb(255, 165, 0)')
// // Suspense is not rendered yet
// expect(
// await browser.eval(
// `document.querySelector('#footer-inner')`
// )
// ).toBe('null')
// // Wait for suspense boundary
// await check(
// () => browser.elementByCss('#footer').text(),
// 'wait for footer'
// )
// expect(
// await browser.eval(
// `window.getComputedStyle(document.querySelector('#footer-inner')).color`
// )
// ).toBe('rgb(255, 165, 0)')
}) })
it('should stick to the url without trailing /page suffix', async () => { it('should stick to the url without trailing /page suffix', async () => {
......
...@@ -6,11 +6,6 @@ export default function Page() { ...@@ -6,11 +6,6 @@ export default function Page() {
<div> <div>
<Comp /> <Comp />
<StyledComp /> <StyledComp />
<style jsx>{`
.this-wont-be-transformed {
color: purple;
}
`}</style>
</div> </div>
) )
} }
'use client'
import { Suspense } from 'react'
import styled from 'styled-components'
import { createDataFetcher } from '../../../lib/data'
const Footer = styled.div`
border: 1px solid orange;
color: blue;
`
const FootInner = styled.span`
padding: 2px;
color: orange;
`
const readData = createDataFetcher('streaming', {
timeout: 4000,
expire: 4000,
})
function SuspenseyFooter() {
readData()
// generate large chunk of text to let the suspensey styling be inserted before the suspense script
return (
<FootInner id="footer-inner">
{'(generate-large-footer-text)'.repeat(30)}
</FootInner>
)
}
export default function page() {
return (
<div>
<Footer id="footer">
{`wait for `}
<Suspense fallback={`fallback`}>
<SuspenseyFooter />
</Suspense>
</Footer>
</div>
)
}
import { Suspense } from 'react' import { Suspense } from 'react'
import Counter from '../../components/partial-hydration-counter' import Counter from '../../components/partial-hydration-counter'
import { createDataFetcher } from '../../lib/data'
let result const Data = createDataFetcher('next_streaming_data', {
let promise timeout: 1000,
function Data() { })
if (result) {
try {
return result
} finally {
promise = null
result = null
}
}
if (!promise)
promise = new Promise((res) => {
setTimeout(() => {
result = 'next_streaming_data'
res()
}, 1000)
})
throw promise
}
export default function () { export default function () {
return ( return (
......
...@@ -16,8 +16,7 @@ export default function RootStyleRegistry({ children }) { ...@@ -16,8 +16,7 @@ export default function RootStyleRegistry({ children }) {
} }
const styledComponentsFlushEffect = () => { const styledComponentsFlushEffect = () => {
const styles = styledComponentsStyleSheet.getStyleElement() const styles = styledComponentsStyleSheet.getStyleElement()
styledComponentsStyleSheet.seal() styledComponentsStyleSheet.instance.clearTag()
return <>{styles}</> return <>{styles}</>
} }
......
import { Suspense } from 'react' import { Suspense } from 'react'
import { createDataFetcher } from '../../lib/data'
import Nav from '../../components/nav' import Nav from '../../components/nav'
let result const Data = createDataFetcher('next_streaming_data', {
let promise timeout: 500,
function Data() { })
if (result) return result
if (!promise)
promise = new Promise((res) => {
setTimeout(() => {
result = 'next_streaming_data'
res()
}, 500)
})
throw promise
}
export default function Page() { export default function Page() {
return ( return (
......
export function createDataFetcher(data, { timeout = 0, expire = 10 }) {
let result
let promise
return function Data() {
if (result) return result
if (!promise)
promise = new Promise((resolve) => {
setTimeout(() => {
result = data
setTimeout(() => {
result = undefined
promise = undefined
}, expire)
resolve()
}, timeout)
})
throw promise
}
}
...@@ -3,7 +3,7 @@ import { check, fetchViaHTTP, renderViaHTTP } from 'next-test-utils' ...@@ -3,7 +3,7 @@ import { check, fetchViaHTTP, renderViaHTTP } from 'next-test-utils'
import { createNext, FileRef } from 'e2e-utils' import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base' import { NextInstance } from 'test/lib/next-modes/base'
describe('app dir - rsc basics', () => { describe('app dir - rsc errors', () => {
let next: NextInstance let next: NextInstance
const { isNextDeploy, isNextDev } = global as any const { isNextDeploy, isNextDev } = global as any
...@@ -90,6 +90,14 @@ describe('app dir - rsc basics', () => { ...@@ -90,6 +90,14 @@ describe('app dir - rsc basics', () => {
) )
}) })
it('should not transform css-in-js such as styled-jsx in server components', async () => {
const html = await renderViaHTTP(next.url, '/not-transform/styled-jsx')
expect(html).toMatch(
/<style>\s*\.this-wont-be-transformed\s*\{\s*color:\s*purple;\s*\}\s*<\/style>/
)
})
it('should error when page component export is not valid', async () => { it('should error when page component export is not valid', async () => {
const html = await renderViaHTTP( const html = await renderViaHTTP(
next.url, next.url,
......
export default function RootLayout({ children }) {
return (
<html>
<head></head>
<body>{children}</body>
</html>
)
}
export default function page() {
return (
<style jsx>{`
.this-wont-be-transformed {
color: purple;
}
`}</style>
)
}
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