Unverified Commit 4e445982 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Progressive enhancement for form state (#55584)

This PR implements progressive enhancement for `useFormState`:
1. Inline the form state in `__next_f` and use it for hydration.
2. Encode the new form state based on the action return value, and pass
it to Flight/Fizz.

Also fixed a problem caused by inconsistent React tree structure between
static-generation and non-static-generation.
parent 730b43d0
......@@ -39,12 +39,17 @@ let initialServerDataWriter: ReadableStreamDefaultController | undefined =
let initialServerDataLoaded = false
let initialServerDataFlushed = false
let initialFormStateData: null | any = null
function nextServerDataCallback(
seg: [isBootStrap: 0] | [isNotBootstrap: 1, responsePartial: string]
seg:
| [isBootStrap: 0]
| [isNotBootstrap: 1, responsePartial: string]
| [isFormState: 2, formState: any]
): number {
if (seg[0] === 0) {
initialServerDataBuffer = []
} else {
} else if (seg[0] === 1) {
if (!initialServerDataBuffer)
throw new Error('Unexpected server data: missing bootstrap script.')
......@@ -53,6 +58,8 @@ function nextServerDataCallback(
} else {
initialServerDataBuffer.push(seg[1])
}
} else if (seg[0] === 2) {
initialFormStateData = seg[1]
}
return 0
}
......@@ -149,7 +156,9 @@ function hydrate() {
reactRoot.render(reactEl)
} else {
React.startTransition(() => {
ReactDOMClient.hydrateRoot(appElement, reactEl)
;(ReactDOMClient as any).hydrateRoot(appElement, reactEl, {
experimental_formState: initialFormStateData,
})
})
}
......
......@@ -46,12 +46,17 @@ let initialServerDataWriter: ReadableStreamDefaultController | undefined =
let initialServerDataLoaded = false
let initialServerDataFlushed = false
let initialFormStateData: null | any = null
function nextServerDataCallback(
seg: [isBootStrap: 0] | [isNotBootstrap: 1, responsePartial: string]
seg:
| [isBootStrap: 0]
| [isNotBootstrap: 1, responsePartial: string]
| [isFormState: 2, formState: any]
): void {
if (seg[0] === 0) {
initialServerDataBuffer = []
} else {
} else if (seg[0] === 1) {
if (!initialServerDataBuffer)
throw new Error('Unexpected server data: missing bootstrap script.')
......@@ -60,6 +65,8 @@ function nextServerDataCallback(
} else {
initialServerDataBuffer.push(seg[1])
}
} else if (seg[0] === 2) {
initialFormStateData = seg[1]
}
}
......@@ -290,7 +297,10 @@ export function hydrate() {
}
} else {
React.startTransition(() =>
(ReactDOMClient as any).hydrateRoot(appElement, reactEl, options)
(ReactDOMClient as any).hydrateRoot(appElement, reactEl, {
...options,
experimental_formState: initialFormStateData,
})
)
}
......
......@@ -5,10 +5,16 @@ import { createSearchParamsBailoutProxy } from './searchparams-bailout-proxy'
export default function StaticGenerationSearchParamsBailoutProvider({
Component,
propsForComponent,
isStaticGeneration,
}: {
Component: React.ComponentType<any>
propsForComponent: any
isStaticGeneration: boolean
}) {
const searchParams = createSearchParamsBailoutProxy()
return <Component searchParams={searchParams} {...propsForComponent} />
if (isStaticGeneration) {
const searchParams = createSearchParamsBailoutProxy()
return <Component searchParams={searchParams} {...propsForComponent} />
}
return <Component {...propsForComponent} />
}
......@@ -254,13 +254,24 @@ export async function handleAction({
serverActionsManifest: any
generateFlight: (options: {
actionResult: ActionResult
formState?: any
skipFlight: boolean
asNotFound?: boolean
}) => Promise<RenderResult>
staticGenerationStore: StaticGenerationStore
requestStore: RequestStore
serverActionsBodySizeLimit?: SizeLimit
}): Promise<undefined | RenderResult | 'not-found'> {
}): Promise<
| undefined
| {
type: 'not-found'
}
| {
type: 'done'
result: RenderResult | undefined
formState?: any
}
> {
let actionId = req.headers[ACTION.toLowerCase()] as string
const contentType = req.headers['content-type']
const isURLEncodedAction =
......@@ -302,12 +313,13 @@ export async function handleAction({
}
let actionResult: RenderResult | undefined
let formState: any | undefined
try {
await actionAsyncStorage.run({ isAction: true }, async () => {
if (process.env.NEXT_RUNTIME === 'edge') {
// Use react-server-dom-webpack/server.edge
const { decodeReply, decodeAction } = ComponentMod
const { decodeReply, decodeAction, decodeFormState } = ComponentMod
const webRequest = req as unknown as WebNextRequest
if (!webRequest.body) {
......@@ -321,7 +333,9 @@ export async function handleAction({
bound = await decodeReply(formData, serverModuleMap)
} else {
const action = await decodeAction(formData, serverModuleMap)
await action()
const actionReturnedState = await action()
formState = decodeFormState(actionReturnedState, formData)
// Skip the fetch path
return
}
......@@ -351,6 +365,7 @@ export async function handleAction({
decodeReply,
decodeReplyFromBusboy,
decodeAction,
decodeFormState,
} = require(`react-server-dom-webpack/server.node`)
if (isMultipartAction) {
......@@ -372,7 +387,9 @@ export async function handleAction({
})
const formData = await fakeRequest.formData()
const action = await decodeAction(formData, serverModuleMap)
await action()
const actionReturnedState = await action()
formState = await decodeFormState(actionReturnedState, formData)
// Skip the fetch path
return
}
......@@ -440,7 +457,11 @@ export async function handleAction({
}
})
return actionResult
return {
type: 'done',
result: actionResult,
formState,
}
} catch (err) {
if (isRedirectError(err)) {
const redirectUrl = getURLFromRedirectError(err)
......@@ -453,12 +474,15 @@ export async function handleAction({
})
if (isFetchAction) {
return createRedirectRenderResult(
req,
res,
redirectUrl,
staticGenerationStore
)
return {
type: 'done',
result: await createRedirectRenderResult(
req,
res,
redirectUrl,
staticGenerationStore
),
}
}
if (err.mutableCookies) {
......@@ -473,7 +497,10 @@ export async function handleAction({
res.setHeader('Location', redirectUrl)
res.statusCode = 303
return new RenderResult('')
return {
type: 'done',
result: new RenderResult(''),
}
} else if (isNotFoundError(err)) {
res.statusCode = 404
......@@ -487,13 +514,18 @@ export async function handleAction({
try {
await promise
} catch {}
return generateFlight({
skipFlight: false,
actionResult: promise,
asNotFound: true,
})
return {
type: 'done',
result: await generateFlight({
skipFlight: false,
actionResult: promise,
asNotFound: true,
}),
}
}
return {
type: 'not-found',
}
return 'not-found'
}
if (isFetchAction) {
......@@ -504,11 +536,14 @@ export async function handleAction({
await promise
} catch {}
return generateFlight({
actionResult: promise,
// if the page was not revalidated, we can skip the rendering the flight tree
skipFlight: !staticGenerationStore.pathWasRevalidated,
})
return {
type: 'done',
result: await generateFlight({
actionResult: promise,
// if the page was not revalidated, we can skip the rendering the flight tree
skipFlight: !staticGenerationStore.pathWasRevalidated,
}),
}
}
throw err
......
......@@ -997,10 +997,11 @@ export const renderToHTMLOrFlight: AppPageRender = (
<>
{isPage ? metadataOutlet : null}
{/* <Component /> needs to be the first element because we use `findDOMNode` in layout router to locate it. */}
{isPage && isClientComponent && isStaticGeneration ? (
{isPage && isClientComponent ? (
<StaticGenerationSearchParamsBailoutProvider
propsForComponent={props}
Component={Component}
isStaticGeneration={isStaticGeneration}
/>
) : (
<Component {...props} />
......@@ -1325,6 +1326,7 @@ export const renderToHTMLOrFlight: AppPageRender = (
clientReferenceManifest,
serverContexts,
rscChunks: [],
formState: null,
}
const validateRootLayout = dev
......@@ -1347,7 +1349,8 @@ export const renderToHTMLOrFlight: AppPageRender = (
*/
const createServerComponentsRenderer = (
loaderTreeToRender: LoaderTree,
preinitScripts: () => void
preinitScripts: () => void,
formState: null | any
) =>
createServerComponentRenderer<{
asNotFound: boolean
......@@ -1410,7 +1413,7 @@ export const renderToHTMLOrFlight: AppPageRender = (
)
},
ComponentMod,
serverComponentsRenderOpts,
{ ...serverComponentsRenderOpts, formState },
serverComponentsErrorHandler,
nonce
)
......@@ -1435,6 +1438,7 @@ export const renderToHTMLOrFlight: AppPageRender = (
async ({
asNotFound,
tree,
formState,
}: {
/**
* This option is used to indicate that the page should be rendered as
......@@ -1444,6 +1448,7 @@ export const renderToHTMLOrFlight: AppPageRender = (
*/
asNotFound: boolean
tree: LoaderTree
formState: any
}) => {
const polyfills = buildManifest.polyfillFiles
.filter(
......@@ -1466,7 +1471,8 @@ export const renderToHTMLOrFlight: AppPageRender = (
)
const ServerComponentsRenderer = createServerComponentsRenderer(
tree,
preinitScripts
preinitScripts,
formState
)
const content = (
<HeadManagerContext.Provider
......@@ -1556,6 +1562,7 @@ export const renderToHTMLOrFlight: AppPageRender = (
nonce,
// Include hydration scripts in the HTML
bootstrapScripts: [bootstrapScript],
experimental_formState: formState,
},
})
......@@ -1621,6 +1628,7 @@ export const renderToHTMLOrFlight: AppPageRender = (
transformStream: cloneTransformStream(
serverComponentsRenderOpts.transformStream
),
formState,
}
const errorType = is404
......@@ -1707,6 +1715,7 @@ export const renderToHTMLOrFlight: AppPageRender = (
nonce,
// Include hydration scripts in the HTML
bootstrapScripts: [errorBootstrapScript],
experimental_formState: formState,
},
})
......@@ -1746,24 +1755,33 @@ export const renderToHTMLOrFlight: AppPageRender = (
serverActionsBodySizeLimit,
})
if (actionRequestResult === 'not-found') {
const notFoundLoaderTree = createNotFoundLoaderTree(loaderTree)
return new RenderResult(
await bodyResult({
asNotFound: true,
tree: notFoundLoaderTree,
}),
{ ...extraRenderResultMeta }
)
} else if (actionRequestResult) {
actionRequestResult.extendMetadata(extraRenderResultMeta)
return actionRequestResult
let formState: null | any = null
if (actionRequestResult) {
if (actionRequestResult.type === 'not-found') {
const notFoundLoaderTree = createNotFoundLoaderTree(loaderTree)
return new RenderResult(
await bodyResult({
asNotFound: true,
tree: notFoundLoaderTree,
formState,
}),
{ ...extraRenderResultMeta }
)
} else if (actionRequestResult.type === 'done') {
if (actionRequestResult.result) {
actionRequestResult.result.extendMetadata(extraRenderResultMeta)
return actionRequestResult.result
} else if (actionRequestResult.formState) {
formState = actionRequestResult.formState
}
}
}
const renderResult = new RenderResult(
await bodyResult({
asNotFound: pagePath === '/404',
tree: loaderTree,
formState,
}),
{
...extraRenderResultMeta,
......
......@@ -23,6 +23,7 @@ export function createServerComponentRenderer<Props>(
clientReferenceManifest,
serverContexts,
rscChunks,
formState,
}: {
transformStream: TransformStream<Uint8Array, Uint8Array>
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>
......@@ -30,6 +31,7 @@ export function createServerComponentRenderer<Props>(
[ServerContextName: string, JSONValue: Object | number | string]
>
rscChunks: Uint8Array[]
formState: null | any
},
serverComponentsErrorHandler: ReturnType<typeof createErrorHandler>,
nonce?: string
......@@ -60,6 +62,7 @@ export function createServerComponentRenderer<Props>(
clientReferenceManifest,
rscChunks,
flightResponseRef,
formState,
nonce
)
return use(response)
......
......@@ -2,6 +2,7 @@ const {
renderToReadableStream,
decodeReply,
decodeAction,
decodeFormState,
// eslint-disable-next-line import/no-extraneous-dependencies
} = require('react-server-dom-webpack/server.edge')
......@@ -38,6 +39,7 @@ export {
renderToReadableStream,
decodeReply,
decodeAction,
decodeFormState,
preloadStyle,
preloadFont,
preconnect,
......
......@@ -5,6 +5,10 @@ import { htmlEscapeJsonString } from '../htmlescape'
const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'
const INLINE_FLIGHT_PAYLOAD_BOOTSTRAP = 0
const INLINE_FLIGHT_PAYLOAD_DATA = 1
const INLINE_FLIGHT_PAYLOAD_FORM_STATE = 2
/**
* Render Flight stream.
* This is only used for renderToHTML, the Flight response does not need additional wrappers.
......@@ -15,6 +19,7 @@ export function useFlightResponse(
clientReferenceManifest: ClientReferenceManifest,
rscChunks: Uint8Array[],
flightResponseRef: FlightResponseRef,
formState: null | any,
nonce?: string
): Promise<JSX.Element> {
if (flightResponseRef.current !== null) {
......@@ -53,7 +58,9 @@ export function useFlightResponse(
writer.write(
encodeText(
`${startScriptTag}(self.__next_f=self.__next_f||[]).push(${htmlEscapeJsonString(
JSON.stringify([0])
JSON.stringify([INLINE_FLIGHT_PAYLOAD_BOOTSTRAP])
)});self.__next_f.push(${htmlEscapeJsonString(
JSON.stringify([INLINE_FLIGHT_PAYLOAD_FORM_STATE, formState])
)})</script>`
)
)
......@@ -70,7 +77,7 @@ export function useFlightResponse(
} else {
const responsePartial = decodeText(value, textDecoder)
const scripts = `${startScriptTag}self.__next_f.push(${htmlEscapeJsonString(
JSON.stringify([1, responsePartial])
JSON.stringify([INLINE_FLIGHT_PAYLOAD_DATA, responsePartial])
)})</script>`
writer.write(encodeText(scripts))
......
/* eslint-disable jest/no-standalone-expect */
import { createNextDescribe } from 'e2e-utils'
import { check } from 'next-test-utils'
createNextDescribe(
'app-dir action useFormState',
{
files: __dirname,
dependencies: {
react: 'latest',
'react-dom': 'latest',
},
},
({ next }) => {
it('should support submitting form state with JS', async () => {
const browser = await next.browser('/client/form-state')
await browser.eval(`document.getElementById('name-input').value = 'test'`)
await browser.elementByCss('#submit-form').click()
await check(() => {
return browser.elementByCss('#form-state').text()
}, 'initial-state:test')
})
it('should support submitting form state without JS', async () => {
const browser = await next.browser('/client/form-state', {
disableJavaScript: true,
})
await browser.eval(`document.getElementById('name-input').value = 'test'`)
await browser.elementByCss('#submit-form').click()
// It should inline the form state into HTML so it can still be hydrated.
await check(() => {
return browser.elementByCss('#form-state').text()
}, 'initial-state:test')
})
it('should support hydrating the app from progressively enhanced form request', async () => {
const browser = await next.browser('/client/form-state')
// Simulate a progressively enhanced form request
await browser.eval(`document.getElementById('name-input').value = 'test'`)
await browser.eval(`document.getElementById('form-state-form').submit()`)
await check(() => {
return browser.elementByCss('#form-state').text()
}, 'initial-state:test')
// Should hydrate successfully
await check(() => {
return browser.elementByCss('#hydrated').text()
}, 'hydrated')
})
}
)
'use server'
export async function appendName(state, formData) {
return state + ':' + formData.get('name')
}
'use client'
import { experimental_useFormState } from 'react-dom'
import { appendName } from './actions'
import { useEffect, useState } from 'react'
export default function Page() {
const [state, appendNameFormAction] = experimental_useFormState(
appendName,
'initial-state'
)
const [hydrated, setHydrated] = useState(false)
useEffect(() => {
setHydrated(true)
}, [])
return (
<>
<form id="form-state-form" action={appendNameFormAction}>
<p id="form-state">{state}</p>
<input id="name-input" name="name" />
<button id="submit-form" type="submit">
log
</button>
</form>
{hydrated ? <p id="hydrated">hydrated</p> : null}
</>
)
}
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