Unverified Commit 31500ba2 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Refactor client component out of client runtime (#37238)

Co-authored-by: 's avatarShu Ding <g@shud.in>
Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent bbcfc0d2
...@@ -106,7 +106,7 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{ ...@@ -106,7 +106,7 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{
// Add page itself to the list of components // Add page itself to the list of components
componentsCode.push( componentsCode.push(
`'${pathToUrlPath(pagePath).replace( `'${pathToUrlPath(pagePath).replace(
new RegExp(`/page+(${extensions.join('|')})$`), new RegExp(`(${extensions.join('|')})$`),
'' ''
// use require so that we can bust the require cache // use require so that we can bust the require cache
)}': () => require('${pagePath}')` )}': () => require('${pagePath}')`
...@@ -117,6 +117,8 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{ ...@@ -117,6 +117,8 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{
${componentsCode.join(',\n')} ${componentsCode.join(',\n')}
}; };
export const AppRouter = require('next/dist/client/components/app-router.client.js').default
export const __next_app_webpack_require__ = __webpack_require__ export const __next_app_webpack_require__ = __webpack_require__
` `
return result return result
......
...@@ -93,16 +93,41 @@ export class FlightManifestPlugin { ...@@ -93,16 +93,41 @@ export class FlightManifestPlugin {
: `./${ssrNamedModuleId}` : `./${ssrNamedModuleId}`
const exportsInfo = compilation.moduleGraph.getExportsInfo(mod) const exportsInfo = compilation.moduleGraph.getExportsInfo(mod)
const moduleExportedKeys = ['', '*'].concat( const cjsExports = [
[...exportsInfo.exports] ...new Set(
.map((exportInfo) => { [].concat(
mod.dependencies.map((dep: any) => {
// Match CommonJsSelfReferenceDependency
if (dep.type === 'cjs self exports reference') {
// `module.exports = ...`
if (dep.base === 'module.exports') {
return 'default'
}
// `exports.foo = ...`, `exports.default = ...`
if (dep.base === 'exports') {
return dep.names.filter(
(name: any) => name !== '__esModule'
)
}
}
return null
})
)
),
]
const moduleExportedKeys = ['', '*']
.concat(
[...exportsInfo.exports].map((exportInfo) => {
if (exportInfo.provided) { if (exportInfo.provided) {
return exportInfo.name return exportInfo.name
} }
return null return null
}) }),
.filter(Boolean) ...cjsExports
) )
.filter((name) => name !== null)
moduleExportedKeys.forEach((name) => { moduleExportedKeys.forEach((name) => {
if (!moduleExports[name]) { if (!moduleExports[name]) {
......
...@@ -4,10 +4,7 @@ import '../build/polyfills/polyfill-module' ...@@ -4,10 +4,7 @@ import '../build/polyfills/polyfill-module'
import ReactDOMClient from 'react-dom/client' import ReactDOMClient from 'react-dom/client'
// @ts-ignore startTransition exists when using React 18 // @ts-ignore startTransition exists when using React 18
import React from 'react' import React from 'react'
import { import { createFromReadableStream } from 'next/dist/compiled/react-server-dom-webpack'
createFromFetch,
createFromReadableStream,
} from 'next/dist/compiled/react-server-dom-webpack'
/// <reference types="react-dom/experimental" /> /// <reference types="react-dom/experimental" />
...@@ -151,76 +148,11 @@ const RSCComponent = () => { ...@@ -151,76 +148,11 @@ const RSCComponent = () => {
return <ServerRoot cacheKey={cacheKey} /> return <ServerRoot cacheKey={cacheKey} />
} }
function fetchFlight(href: string) {
const url = new URL(href, location.origin)
const searchParams = url.searchParams
searchParams.append('__flight__', '1')
return fetch(url.toString())
}
function useServerResponse(cacheKey: string) {
let response = rscCache.get(cacheKey)
if (response) return response
response = createFromFetch(fetchFlight(getCacheKey()))
rscCache.set(cacheKey, response)
return response
}
const AppRouterContext = React.createContext({})
// TODO: move to client component when handling is implemented
function AppRouter({ initialUrl, children }: any) {
const initialState = {
url: initialUrl,
}
const previousUrlRef = React.useRef(initialState)
const [current, setCurrent] = React.useState(initialState)
const appRouter = React.useMemo(() => {
return {
push: (url: string) => {
previousUrlRef.current = current
setCurrent({ ...current, url })
// TODO: update url eagerly or not?
window.history.pushState(current, '', url)
},
url: current.url,
}
}, [current])
// @ts-ignore TODO: for testing
window.appRouter = appRouter
console.log({
appRouter,
previous: previousUrlRef.current,
current,
})
let root
if (current.url !== previousUrlRef.current?.url) {
// eslint-disable-next-line
const data = useServerResponse(current.url)
root = data.readRoot()
}
return (
<AppRouterContext.Provider value={appRouter}>
{root ? root : children}
</AppRouterContext.Provider>
)
}
export function hydrate() { export function hydrate() {
renderReactElement(appElement!, () => ( renderReactElement(appElement!, () => (
<React.StrictMode> <React.StrictMode>
<Root> <Root>
<AppRouter initialUrl={location.pathname}> <RSCComponent />
<RSCComponent />
</AppRouter>
</Root> </Root>
</React.StrictMode> </React.StrictMode>
)) ))
......
import React from 'react'
import { createFromFetch } from 'next/dist/compiled/react-server-dom-webpack'
import { AppRouterContext } from '../../shared/lib/app-router-context'
function createResponseCache() {
return new Map<string, any>()
}
const rscCache = createResponseCache()
const getCacheKey = () => {
const { pathname, search } = location
return pathname + search
}
function fetchFlight(href: string) {
const url = new URL(href, location.origin)
const searchParams = url.searchParams
searchParams.append('__flight__', '1')
return fetch(url.toString())
}
function fetchServerResponse(cacheKey: string) {
let response = rscCache.get(cacheKey)
if (response) return response
response = createFromFetch(fetchFlight(getCacheKey()))
rscCache.set(cacheKey, response)
return response
}
// TODO: move to client component when handling is implemented
export default function AppRouter({ initialUrl, children }: any) {
const initialState = {
url: initialUrl,
}
const previousUrlRef = React.useRef(initialState)
const [current, setCurrent] = React.useState(initialState)
const appRouter = React.useMemo(() => {
return {
prefetch: () => {},
replace: () => {},
push: (url: string) => {
previousUrlRef.current = current
setCurrent({ ...current, url })
// TODO: update url eagerly or not?
window.history.pushState(current, '', url)
},
url: current.url,
}
}, [current])
if (typeof window !== 'undefined') {
// @ts-ignore TODO: for testing
window.appRouter = appRouter
console.log({
appRouter,
previous: previousUrlRef.current,
current,
})
}
let root
if (current.url !== previousUrlRef.current?.url) {
// eslint-disable-next-line
const data = fetchServerResponse(current.url)
root = data.readRoot()
}
return (
<AppRouterContext.Provider value={appRouter}>
{root ? root : children}
</AppRouterContext.Provider>
)
}
...@@ -9,7 +9,8 @@ import { ...@@ -9,7 +9,8 @@ import {
PrefetchOptions, PrefetchOptions,
resolveHref, resolveHref,
} from '../shared/lib/router/router' } from '../shared/lib/router/router'
import { useRouter } from './router' import { RouterContext } from '../shared/lib/router-context'
import { AppRouterContext } from '../shared/lib/app-router-context'
import { useIntersection } from './use-intersection' import { useIntersection } from './use-intersection'
type Url = string | UrlObject type Url = string | UrlObject
...@@ -269,7 +270,12 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>( ...@@ -269,7 +270,12 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
} }
const p = prefetchProp !== false const p = prefetchProp !== false
const router = useRouter() let router = React.useContext(RouterContext)
const appRouter = React.useContext(AppRouterContext)
if (appRouter) {
router = appRouter
}
const { href, as } = React.useMemo(() => { const { href, as } = React.useMemo(() => {
const [resolvedHref, resolvedAs] = resolveHref(router, hrefProp, true) const [resolvedHref, resolvedAs] = resolveHref(router, hrefProp, true)
......
...@@ -355,6 +355,15 @@ export async function renderToHTML( ...@@ -355,6 +355,15 @@ export async function renderToHTML(
// } // }
} }
const AppRouter = ComponentMod.AppRouter
const WrappedComponentWithRouter = () => {
return (
<AppRouter initialUrl={req.url}>
<WrappedComponent />
</AppRouter>
)
}
const bootstrapScripts = !isSubtreeRender const bootstrapScripts = !isSubtreeRender
? buildManifest.rootMainFiles.map((src) => '/_next/' + src) ? buildManifest.rootMainFiles.map((src) => '/_next/' + src)
: undefined : undefined
...@@ -368,7 +377,7 @@ export async function renderToHTML( ...@@ -368,7 +377,7 @@ export async function renderToHTML(
const search = stringifyQuery(query) const search = stringifyQuery(query)
const Component = createServerComponentRenderer( const Component = createServerComponentRenderer(
WrappedComponent, WrappedComponentWithRouter,
ComponentMod, ComponentMod,
{ {
cachePrefix: pathname + (search ? `?${search}` : ''), cachePrefix: pathname + (search ? `?${search}` : ''),
...@@ -393,7 +402,7 @@ export async function renderToHTML( ...@@ -393,7 +402,7 @@ export async function renderToHTML(
if (renderServerComponentData) { if (renderServerComponentData) {
return new RenderResult( return new RenderResult(
renderToReadableStream( renderToReadableStream(
<WrappedComponent />, <WrappedComponentWithRouter />,
serverComponentManifest serverComponentManifest
).pipeThrough(createBufferedTransformStream()) ).pipeThrough(createBufferedTransformStream())
) )
......
...@@ -1733,13 +1733,10 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1733,13 +1733,10 @@ export default abstract class Server<ServerOptions extends Options = Options> {
let page = pathname let page = pathname
const bubbleNoFallback = !!query._nextBubbleNoFallback const bubbleNoFallback = !!query._nextBubbleNoFallback
delete query._nextBubbleNoFallback delete query._nextBubbleNoFallback
// map the route to the actual bundle name e.g. // map the route to the actual bundle name
// `/dashboard/rootonly/hello` -> `/dashboard+rootonly/hello`
const getOriginalappPath = (appPath: string) => { const getOriginalappPath = (appPath: string) => {
if (this.nextConfig.experimental.appDir) { if (this.nextConfig.experimental.appDir) {
const originalappPath = const originalappPath = this.appPathRoutes?.[appPath]
this.appPathRoutes?.[`${appPath}/index`] ||
this.appPathRoutes?.[`${appPath}`]
if (!originalappPath) { if (!originalappPath) {
return null return null
......
import React from 'react'
export const AppRouterContext = React.createContext<any>(null as any)
if (process.env.NODE_ENV !== 'production') {
AppRouterContext.displayName = 'AppRouterContext'
}
export default function DashboardPage(props) { export default function DashboardIndexPage() {
return ( return (
<> <>
<p>hello from root/dashboard</p> <p>hello from root/dashboard/index</p>
</> </>
) )
} }
export default function DashboardPage(props) {
return (
<>
<p>hello from root/dashboard</p>
</>
)
}
...@@ -52,11 +52,16 @@ describe('views dir', () => { ...@@ -52,11 +52,16 @@ describe('views dir', () => {
expect(html).toContain('hello world') expect(html).toContain('hello world')
}) })
it('should serve from root', async () => { it('should serve from app', async () => {
const html = await renderViaHTTP(next.url, '/dashboard') const html = await renderViaHTTP(next.url, '/dashboard')
expect(html).toContain('hello from root/dashboard') expect(html).toContain('hello from root/dashboard')
}) })
it('should serve /index as separate page', async () => {
const html = await renderViaHTTP(next.url, '/dashboard/index')
expect(html).toContain('hello from root/dashboard/index')
})
it('should include layouts when no direct parent layout', async () => { it('should include layouts when no direct parent layout', async () => {
const html = await renderViaHTTP(next.url, '/dashboard/integrations') const html = await renderViaHTTP(next.url, '/dashboard/integrations')
const $ = cheerio.load(html) const $ = cheerio.load(html)
......
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