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

Add unstable_useRefreshRoot (#32342)

## Feature

Resolves #32332

- [x] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [x] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`
parent 55d8a14e
...@@ -45,7 +45,14 @@ export function getRender({ ...@@ -45,7 +45,14 @@ export function getRender({
const renderServerComponentData = isServerComponent const renderServerComponentData = isServerComponent
? query.__flight__ !== undefined ? query.__flight__ !== undefined
: false : false
const serverComponentProps =
isServerComponent && query.__props__
? JSON.parse(query.__props__)
: undefined
delete query.__flight__ delete query.__flight__
delete query.__props__
const req = { const req = {
url: pathname, url: pathname,
...@@ -73,6 +80,7 @@ export function getRender({ ...@@ -73,6 +80,7 @@ export function getRender({
supportsDynamicHTML: true, supportsDynamicHTML: true,
concurrentFeatures: true, concurrentFeatures: true,
renderServerComponentData, renderServerComponentData,
serverComponentProps,
serverComponentManifest: isServerComponent ? rscManifest : null, serverComponentManifest: isServerComponent ? rscManifest : null,
ComponentMod: null, ComponentMod: null,
} }
......
/* global location */ /* global location */
import '@next/polyfill-module' import '@next/polyfill-module'
import React from 'react' import React, { useState } from 'react'
import ReactDOM from 'react-dom' import ReactDOM from 'react-dom'
import { StyleRegistry } from 'styled-jsx' import { StyleRegistry } from 'styled-jsx'
import { HeadManagerContext } from '../shared/lib/head-manager-context' import { HeadManagerContext } from '../shared/lib/head-manager-context'
...@@ -35,6 +35,7 @@ import { RouteAnnouncer } from './route-announcer' ...@@ -35,6 +35,7 @@ import { RouteAnnouncer } from './route-announcer'
import { createRouter, makePublicRouterInstance, useRouter } from './router' import { createRouter, makePublicRouterInstance, useRouter } from './router'
import isError from '../lib/is-error' import isError from '../lib/is-error'
import { trackWebVitalMetric } from './vitals' import { trackWebVitalMetric } from './vitals'
import { RefreshContext } from './rsc'
/// <reference types="react-dom/experimental" /> /// <reference types="react-dom/experimental" />
...@@ -643,12 +644,30 @@ const wrapApp = ...@@ -643,12 +644,30 @@ const wrapApp =
let RSCComponent: (props: any) => JSX.Element let RSCComponent: (props: any) => JSX.Element
if (process.env.__NEXT_RSC) { if (process.env.__NEXT_RSC) {
const {
createFromFetch,
} = require('next/dist/compiled/react-server-dom-webpack')
function createResponseCache() { function createResponseCache() {
return new Map<string, any>() return new Map<string, any>()
} }
const rscCache = createResponseCache() const rscCache = createResponseCache()
function fetchFlight(href: string, props?: any) {
const url = new URL(href, location.origin)
const searchParams = url.searchParams
searchParams.append('__flight__', '1')
if (props) {
searchParams.append('__props__', JSON.stringify(props))
}
return fetch(url.toString())
}
const getHref = () => {
const { pathname, search } = location
return pathname + search
}
const RSCWrapper = ({ const RSCWrapper = ({
cacheKey, cacheKey,
serialized, serialized,
...@@ -658,12 +677,8 @@ if (process.env.__NEXT_RSC) { ...@@ -658,12 +677,8 @@ if (process.env.__NEXT_RSC) {
serialized?: string serialized?: string
_fresh?: boolean _fresh?: boolean
}) => { }) => {
const {
createFromFetch,
} = require('next/dist/compiled/react-server-dom-webpack')
let response = rscCache.get(cacheKey) let response = rscCache.get(cacheKey)
// If there is no cache, or there is serialized data already
if (!response) { if (!response) {
response = createFromFetch( response = createFromFetch(
serialized serialized
...@@ -672,16 +687,10 @@ if (process.env.__NEXT_RSC) { ...@@ -672,16 +687,10 @@ if (process.env.__NEXT_RSC) {
t.writable.getWriter().write(new TextEncoder().encode(serialized)) t.writable.getWriter().write(new TextEncoder().encode(serialized))
return Promise.resolve({ body: t.readable }) return Promise.resolve({ body: t.readable })
})() })()
: (() => { : fetchFlight(getHref())
const { search, pathname } = location
const flightReqUrl =
pathname + search + (search ? '&' : '?') + '__flight__'
return fetch(flightReqUrl)
})()
) )
rscCache.set(cacheKey, response) rscCache.set(cacheKey, response)
} }
const root = response.readRoot() const root = response.readRoot()
return root return root
} }
...@@ -689,14 +698,31 @@ if (process.env.__NEXT_RSC) { ...@@ -689,14 +698,31 @@ if (process.env.__NEXT_RSC) {
RSCComponent = (props: any) => { RSCComponent = (props: any) => {
const cacheKey = useRouter().asPath const cacheKey = useRouter().asPath
const { __flight_serialized__, __flight_fresh__ } = props const { __flight_serialized__, __flight_fresh__ } = props
const [, dispatch] = useState({})
// @ts-ignore TODO: remove when react 18 types are supported
const startTransition = React.startTransition
const renrender = () => dispatch({})
// If there is no cache, or there is serialized data already
function refreshCache(nextProps: any) {
startTransition(() => {
const href = getHref()
const response = createFromFetch(fetchFlight(href, nextProps))
// FIXME: router.asPath can be different from current location due to navigation
rscCache.set(href, response)
renrender()
})
}
return ( return (
<React.Suspense fallback={null}> <RefreshContext.Provider value={refreshCache}>
<RSCWrapper <React.Suspense fallback={null}>
cacheKey={cacheKey} <RSCWrapper
serialized={__flight_serialized__} cacheKey={cacheKey}
_fresh={__flight_fresh__} serialized={__flight_serialized__}
/> _fresh={__flight_fresh__}
</React.Suspense> />
</React.Suspense>
</RefreshContext.Provider>
) )
} }
} }
......
import { createContext, useContext } from 'react'
export const RefreshContext = createContext((_: any) => {})
export function useRefreshRoot() {
return useContext(RefreshContext)
}
export * from './dist/client/rsc'
module.exports = {
unstable_useRefreshRoot: require('./dist/client/rsc').useRefreshRoot,
}
...@@ -209,6 +209,7 @@ export type RenderOptsPartial = { ...@@ -209,6 +209,7 @@ export type RenderOptsPartial = {
resolvedAsPath?: string resolvedAsPath?: string
serverComponentManifest?: any serverComponentManifest?: any
renderServerComponentData?: boolean renderServerComponentData?: boolean
serverComponentProps?: any
distDir?: string distDir?: string
locale?: string locale?: string
locales?: string[] locales?: string[]
...@@ -356,6 +357,7 @@ export async function renderToHTML( ...@@ -356,6 +357,7 @@ export async function renderToHTML(
getServerSideProps, getServerSideProps,
serverComponentManifest, serverComponentManifest,
renderServerComponentData, renderServerComponentData,
serverComponentProps,
isDataReq, isDataReq,
params, params,
previewProps, previewProps,
...@@ -1004,7 +1006,7 @@ export async function renderToHTML( ...@@ -1004,7 +1006,7 @@ export async function renderToHTML(
if (renderServerComponentData) { if (renderServerComponentData) {
const stream: ReadableStream = renderToReadableStream( const stream: ReadableStream = renderToReadableStream(
<OriginalComponent {...props.pageProps} />, <OriginalComponent {...props.pageProps} {...serverComponentProps} />,
serverComponentManifest serverComponentManifest
) )
const reader = stream.getReader() const reader = stream.getReader()
......
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