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 @@
"selenium-webdriver": "4.0.0-beta.4",
"semver": "7.3.7",
"shell-quote": "1.7.3",
"styled-components": "5.3.3",
"styled-components": "6.0.0-beta.5",
"styled-jsx-plugin-postcss": "3.0.2",
"swr": "2.0.0-rc.0",
"tailwindcss": "1.1.3",
......
import type { FlightRouterState } from './app-render'
import { nonNullable } from '../lib/non-nullable'
const queueTask =
process.env.NEXT_RUNTIME === 'edge' ? globalThis.setTimeout : setImmediate
export type ReactReadableStream = ReadableStream<Uint8Array> & {
allReady?: Promise<void> | undefined
}
......@@ -149,21 +152,43 @@ export function renderToInitialStream({
return ReactDOMServer.renderToReadableStream(element, streamOptions)
}
export function createHeadInjectionTransformStream(
inject: () => Promise<string>
function createHeadInsertionTransformStream(
insert: () => Promise<string>
): TransformStream<Uint8Array, Uint8Array> {
let injected = false
let inserted = false
let freezing = false
return new TransformStream({
async transform(chunk, controller) {
const content = decodeText(chunk)
let index
if (!injected && (index = content.indexOf('</head')) !== -1) {
injected = true
const injectedContent =
content.slice(0, index) + (await inject()) + content.slice(index)
controller.enqueue(encodeText(injectedContent))
// While react is flushing chunks, we don't apply insertions
if (freezing) {
controller.enqueue(chunk)
return
}
const insertion = await insert()
if (inserted) {
controller.enqueue(encodeText(insertion))
controller.enqueue(chunk)
freezing = true
} 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)
} else {
queueTask(() => {
freezing = false
})
}
},
})
......@@ -333,7 +358,7 @@ export async function continueFromInitialStream(
suffixUnclosed != null ? createDeferredSuffixStream(suffixUnclosed) : null,
dataStream ? createInlineDataStream(dataStream) : 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
// hydration errors. Remove this once it's ready to be handled by react itself.
const serverInsertedHTML =
......
This diff is collapsed.
......@@ -38,7 +38,7 @@ describe('app dir - rsc basics', () => {
next = await createNext({
files: new FileRef(path.join(__dirname, './rsc-basic')),
dependencies: {
'styled-components': '6.0.0-beta.2',
'styled-components': '6.0.0-beta.5',
react: 'latest',
'react-dom': 'latest',
},
......@@ -309,11 +309,55 @@ describe('app dir - rsc basics', () => {
// from styled-components
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
expect(html).toMatch(
/<style>\s*\.this-wont-be-transformed\s*\{\s*color:\s*purple;\s*\}\s*<\/style>/
const isSuspenseyDataResolved =
/<style[^<>]*>(\s)*.+{padding:2px;(\s)*color:orange;}/.test(chunk)
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 () => {
......
......@@ -6,11 +6,6 @@ export default function Page() {
<div>
<Comp />
<StyledComp />
<style jsx>{`
.this-wont-be-transformed {
color: purple;
}
`}</style>
</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 Counter from '../../components/partial-hydration-counter'
import { createDataFetcher } from '../../lib/data'
let result
let promise
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
}
const Data = createDataFetcher('next_streaming_data', {
timeout: 1000,
})
export default function () {
return (
......
......@@ -16,8 +16,7 @@ export default function RootStyleRegistry({ children }) {
}
const styledComponentsFlushEffect = () => {
const styles = styledComponentsStyleSheet.getStyleElement()
styledComponentsStyleSheet.seal()
styledComponentsStyleSheet.instance.clearTag()
return <>{styles}</>
}
......
import { Suspense } from 'react'
import { createDataFetcher } from '../../lib/data'
import Nav from '../../components/nav'
let result
let promise
function Data() {
if (result) return result
if (!promise)
promise = new Promise((res) => {
setTimeout(() => {
result = 'next_streaming_data'
res()
}, 500)
})
throw promise
}
const Data = createDataFetcher('next_streaming_data', {
timeout: 500,
})
export default function Page() {
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'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
describe('app dir - rsc basics', () => {
describe('app dir - rsc errors', () => {
let next: NextInstance
const { isNextDeploy, isNextDev } = global as any
......@@ -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 () => {
const html = await renderViaHTTP(
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