Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: rsc server route #6528

Merged
merged 9 commits into from
Sep 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions examples/with-rsc/src/components/Counter.client.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use client';
import { useState } from 'react';
import { useAppContext } from 'ice';
import styles from './index.module.css';

export default function Counter() {
Expand All @@ -9,6 +10,9 @@ export default function Counter() {
setCount(count + 1);
}

const appContext = useAppContext();
console.log(appContext);

return (
<button className={styles.button} type="button" onClick={updateCount}>
👍🏻 {count}
Expand Down
9 changes: 5 additions & 4 deletions examples/with-rsc/src/pages/index.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import { useState } from 'react';
import { useAppContext } from 'ice';
import styles from './index.module.css';
// import Comments from '@/components/Comments';
// import Footer from '@/components/Footer';
import EditButton from '@/components/EditButton.client';
import Counter from '@/components/Counter.client';

export default function Home() {
console.log('Render: Index');

const appContext = useAppContext();
console.log(appContext);

return (
<div>
<div className={styles.app}>
<h2>Home Page</h2>
<Counter />
<EditButton noteId="editButton">
Expand Down
6 changes: 2 additions & 4 deletions examples/with-rsc/src/pages/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import { Outlet } from 'ice';

export default function Layout() {
export default function Layout(props) {
console.log('Render: Layout');

return (
<div>
<h1>Suspense App</h1>
<Outlet />
{props.children}
</div>
);
}
2 changes: 1 addition & 1 deletion packages/ice/src/plugins/web/task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ const getWebTask = ({ rootDir, command, userConfig }): Config => {
target: WEB,
...(userConfig.rsc ? {
// TODO: temporary solution for rsc.
entry: { main: [path.join(rootDir, RUNTIME_TMP_DIR, 'clientEntry.tsx')] },
entry: { main: [path.join(rootDir, RUNTIME_TMP_DIR, 'rsc.client.tsx')] },
} : {}),
};
};
Expand Down
11 changes: 6 additions & 5 deletions packages/ice/src/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,12 @@ export function getRoutesDefinition(nestRouteManifest: NestedRouteManifest[], la
routeImports.push(`import * as ${routeSpecifier} from '${formatPath(componentPath)}';`);
loadStatement = routeSpecifier;
}
const component = `Component: () => WrapRouteComponent({
routeId: '${id}',
isLayout: ${layout},
routeExports: ${lazy ? 'componentModule' : loadStatement},
})`;
const component = `Component: (props) => WrapRouteComponent({
routeId: '${id}',
isLayout: ${layout},
routeExports: ${lazy ? 'componentModule' : loadStatement},
children: props?.children
})`;
const loader = `loader: createRouteLoader({
routeId: '${id}',
requestContext,
Expand Down
19 changes: 0 additions & 19 deletions packages/ice/templates/core/clientEntry.tsx.ejs

This file was deleted.

5 changes: 5 additions & 0 deletions packages/ice/templates/core/entry.server.ts.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ export async function renderToResponse(requestContext, options: RenderOptions =
setRuntimeEnv(renderMode);

const mergedOptions = mergeOptions(options);

<% if(rsc) {-%>
return runtime.runRSCServerApp(requestContext, mergedOptions);
<% }-%>

return runtime.renderToResponse(requestContext, mergedOptions);
}

Expand Down
8 changes: 8 additions & 0 deletions packages/ice/templates/core/rsc.client.tsx.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<% if (importCoreJs) { -%>import 'core-js';<% } %>
import { runRSCClientApp } from '<%- iceRuntimePath %>';

const render = (customOptions = {}) => {
return runRSCClientApp();
};

<%- entryCode %>
9 changes: 7 additions & 2 deletions packages/runtime/src/AppContext.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
import * as React from 'react';
import type { AppContext } from './types.js';

const Context = React.createContext<AppContext | undefined>(undefined);
// @ts-ignore
const Context = React.createServerContext
// @ts-ignore
? React.createServerContext<AppContext | undefined>(undefined)
: React.createContext<AppContext | undefined>(undefined);

Context.displayName = 'AppContext';

function useAppContext() {
const value = React.useContext(Context);
const value: AppContext = React.useContext(Context);
return value;
}

function useAppData() {
const value = React.useContext(Context);
// @ts-ignore
return value.appData;
}

Expand Down
2 changes: 2 additions & 0 deletions packages/runtime/src/index.server.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
export { renderToResponse, renderToHTML, renderToEntry } from './runServerApp.js';
export { runRSCServerApp } from './runRSCServerApp.js';

export * from './index.js';
5 changes: 3 additions & 2 deletions packages/runtime/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ import type { RunClientAppOptions, CreateRoutes } from './runClientApp.js';
import { useAppContext as useInternalAppContext, useAppData, AppContextProvider } from './AppContext.js';
import { getAppData } from './appData.js';
import { useData, useConfig } from './RouteContext.js';
import runRSCApp from './runRSCApp.js';
import { runRSCClientApp } from './runRSCClientApp.js';

import {
Meta,
Title,
Expand Down Expand Up @@ -144,7 +145,7 @@ export {
WrapRouteComponent,
RouteErrorComponent,

runRSCApp,
runRSCClientApp,
};

export type {
Expand Down
7 changes: 5 additions & 2 deletions packages/runtime/src/routes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,16 @@ export function WrapRouteComponent(options: {
routeId: string;
isLayout?: boolean;
routeExports: ComponentModule;
children?: Array<ComponentModule>;
}) {
const { routeId, isLayout, routeExports } = options;
const { routeId, isLayout, routeExports, children } = options;

const { RouteWrappers } = useAppContext() || {};
return (
<RouteWrapper routeExports={routeExports} id={routeId} isLayout={isLayout} wrappers={RouteWrappers}>
<routeExports.default />
<routeExports.default>
{ children }
</routeExports.default>
</RouteWrapper>
);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,29 +1,26 @@
import * as React from 'react';
import * as ReactDOM from 'react-dom/client';
import pkg from 'react-server-dom-webpack/client';
const { createFromFetch } = pkg;

// @ts-ignore
const { Suspense, use } = React;
const { createFromFetch } = pkg;

export default async function runRSCApp() {
function Message({ response }) {
const body = use(response);
return <div>{body}</div>;
}

export async function runRSCClientApp() {
function App({ response }) {
return (
<Suspense fallback={<h1>Loading...</h1>}>
<Message response={response} />
{use(response)}
</Suspense>
);
}

const rscPath = location.href + (location.href.indexOf('?') ? '?rsc' : '&rsc');
const response = createFromFetch(
fetch('/?body'),
fetch(rscPath),
);

const container = document.getElementById('app');
const root = ReactDOM.createRoot(container);
root.render(<App response={response} />);
}
}
108 changes: 108 additions & 0 deletions packages/runtime/src/runRSCServerApp.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import * as React from 'react';
import * as ReactDOMServer from 'react-dom/server';
import { renderToPipeableStream } from 'react-server-dom-webpack/server.node';
import { AppContextProvider } from './AppContext.js';
import { DocumentContextProvider } from './Document.js';
import { loadRouteModules } from './routes.js';
import getAppConfig from './appConfig.js';
import getRequestContext from './requestContext.js';
import getLocation from './utils/getLocation.js';
import addLeadingSlash from './utils/addLeadingSlash.js';
import matchRoutes from './matchRoutes.js';
import type {
AppContext,
ServerContext,
RouteMatch,
RouteModules,
ServerRenderOptions as RenderOptions,
} from './types.js';

export async function runRSCServerApp(serverContext: ServerContext, renderOptions: RenderOptions) {
const { req, res } = serverContext;

const {
app,
createRoutes,
renderMode,
basename,
serverOnlyBasename,
clientManifest,
assetsManifest,
} = renderOptions;

const location = getLocation(req.url);
const requestContext = getRequestContext(location, serverContext);
const routes = createRoutes({
requestContext,
renderMode,
});
const finalBasename = addLeadingSlash(serverOnlyBasename || basename);
const matches = matchRoutes(routes, location, finalBasename);

const appConfig = getAppConfig(app);
const appContext: AppContext = {
appConfig,
appData: null,
renderMode,
assetsManifest,
basename: finalBasename,
matches: [],
};

if (req.url?.indexOf('rsc') === -1) {
return renderDocument(serverContext, renderOptions, appContext);
}

const routeModules = await loadRouteModules(matches.map(({ route: { id, lazy } }) => ({ id, lazy })));

const element = (
<AppContextProvider value={appContext}>
{renderMatches(matches, routeModules)}
</AppContextProvider>
);

const { pipe } = renderToPipeableStream(
element,
clientManifest,
);

pipe(res);
}

function renderMatches(matches: RouteMatch[], routeModules: RouteModules) {
return matches.reduceRight((children, match) => {
if (match.route) {
const Component = routeModules[match.route.id].default;

return React.createElement(Component, {
children,
});
}

return children;
}, React.createElement(null));
}

function renderDocument(requestContext, renderOptions, appContext) {
const { res } = requestContext;

const {
Document,
} = renderOptions;

const documentContext = {
main: null,
};

const htmlStr = ReactDOMServer.renderToString(
<AppContextProvider value={appContext}>
<DocumentContextProvider value={documentContext}>
<Document />
</DocumentContextProvider>
</AppContextProvider>,
);

res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.send(`<!DOCTYPE html>${htmlStr}`);
}

Loading
Loading