feat: add context information to render function (#46)
This commit is contained in:
+20
-18
@@ -19,23 +19,25 @@ export default function Home() {
|
|||||||
|
|
||||||
function Counter() {
|
function Counter() {
|
||||||
const [count, setCount] = useState(0);
|
const [count, setCount] = useState(0);
|
||||||
return <div class={tw`mt-4 border rounded p-4 text-center`}>
|
return (
|
||||||
<p class={tw`text-lg font-medium`}>Current count: {count}</p>
|
<div class={tw`mt-4 border rounded p-4 text-center`}>
|
||||||
<div class={tw`flex gap-2 mt-4 justify-center`}>
|
<p class={tw`text-lg font-medium`}>Current count: {count}</p>
|
||||||
<RoundedButton
|
<div class={tw`flex gap-2 mt-4 justify-center`}>
|
||||||
type="button"
|
<RoundedButton
|
||||||
onClick={() => setCount(count - 1)}
|
type="button"
|
||||||
disabled={!IS_BROWSER}
|
onClick={() => setCount(count - 1)}
|
||||||
>
|
disabled={!IS_BROWSER}
|
||||||
<IconMinus />
|
>
|
||||||
</RoundedButton>
|
<IconMinus />
|
||||||
<RoundedButton
|
</RoundedButton>
|
||||||
type="button"
|
<RoundedButton
|
||||||
onClick={() => setCount(count + 1)}
|
type="button"
|
||||||
disabled={!IS_BROWSER}
|
onClick={() => setCount(count + 1)}
|
||||||
>
|
disabled={!IS_BROWSER}
|
||||||
<IconPlus />
|
>
|
||||||
</RoundedButton>
|
<IconPlus />
|
||||||
|
</RoundedButton>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>;
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,11 +15,13 @@ export default function ModuleInfoPage({ params }: PageProps) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const { latest, versions } = info;
|
const { latest, versions } = info;
|
||||||
return <p>
|
return (
|
||||||
The module `{params.module}` has {versions.length} versions, with {latest}
|
<p>
|
||||||
{" "}
|
The module `{params.module}` has {versions.length} versions, with {latest}
|
||||||
being the most recent.
|
{" "}
|
||||||
</p>;
|
being the most recent.
|
||||||
|
</p>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ModuleInfo {
|
interface ModuleInfo {
|
||||||
|
|||||||
+11
-9
@@ -80,15 +80,17 @@ export default function Home() {
|
|||||||
|
|
||||||
function Counter() {
|
function Counter() {
|
||||||
const [count, setCount] = useState(0);
|
const [count, setCount] = useState(0);
|
||||||
return <div>
|
return (
|
||||||
<p>{count}</p>
|
<div>
|
||||||
<button onClick={() => setCount(count - 1)} disabled={!IS_BROWSER}>
|
<p>{count}</p>
|
||||||
-1
|
<button onClick={() => setCount(count - 1)} disabled={!IS_BROWSER}>
|
||||||
</button>
|
-1
|
||||||
<button onClick={() => setCount(count + 1)} disabled={!IS_BROWSER}>
|
</button>
|
||||||
+1
|
<button onClick={() => setCount(count + 1)} disabled={!IS_BROWSER}>
|
||||||
</button>
|
+1
|
||||||
</div>;
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
await Deno.writeTextFile(
|
await Deno.writeTextFile(
|
||||||
|
|||||||
@@ -1,4 +1,19 @@
|
|||||||
export interface PageProps {
|
export interface PageProps {
|
||||||
|
/** The URL of the request that resulted in this page being rendered. */
|
||||||
|
url: URL;
|
||||||
|
|
||||||
|
/** The route matcher (e.g. /blog/:id) that the request matched for this page
|
||||||
|
* to be rendered. */
|
||||||
|
route: string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The paramteres that were matched from the route.
|
||||||
|
*
|
||||||
|
* For the `/foo/:bar` route with url `/foo/123`, `params` would be
|
||||||
|
* `{ bar: '123' }`. For a route with no matchers, `params` would be `{}`. For
|
||||||
|
* a wildcard route, like `/foo/:path*` with url `/foo/bar/baz`, `params` would
|
||||||
|
* be `{ path: [ 'bar', 'baz' ] }`.
|
||||||
|
*/
|
||||||
params: Record<string, string | string[]>;
|
params: Record<string, string | string[]>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -94,7 +94,7 @@ export class ServerContext {
|
|||||||
for (const page of this.#pages) {
|
for (const page of this.#pages) {
|
||||||
const bundlePath = `/${page.name}.js`;
|
const bundlePath = `/${page.name}.js`;
|
||||||
const imports = [bundleAssetUrl(bundlePath)];
|
const imports = [bundleAssetUrl(bundlePath)];
|
||||||
routes[page.route] = async (_, match) => {
|
routes[page.route] = async (req, match) => {
|
||||||
const preloads = this.#bundler.getPreloads(bundlePath).map(
|
const preloads = this.#bundler.getPreloads(bundlePath).map(
|
||||||
bundleAssetUrl,
|
bundleAssetUrl,
|
||||||
);
|
);
|
||||||
@@ -103,6 +103,7 @@ export class ServerContext {
|
|||||||
imports: page.runtimeJS ? imports : [],
|
imports: page.runtimeJS ? imports : [],
|
||||||
preloads: page.runtimeJS ? preloads : [],
|
preloads: page.runtimeJS ? preloads : [],
|
||||||
renderer: this.#renderer,
|
renderer: this.#renderer,
|
||||||
|
url: new URL(req.url),
|
||||||
params: match.params,
|
params: match.params,
|
||||||
});
|
});
|
||||||
return new Response(body, {
|
return new Response(body, {
|
||||||
|
|||||||
+32
-17
@@ -2,12 +2,14 @@ import { renderToString } from "./deps.ts";
|
|||||||
import { ComponentChild, h } from "../runtime/deps.ts";
|
import { ComponentChild, h } from "../runtime/deps.ts";
|
||||||
import { DATA_CONTEXT } from "../runtime/hooks.ts";
|
import { DATA_CONTEXT } from "../runtime/hooks.ts";
|
||||||
import { Page, Renderer } from "./types.ts";
|
import { Page, Renderer } from "./types.ts";
|
||||||
|
import { PageProps } from "../runtime/types.ts";
|
||||||
|
|
||||||
export interface RenderOptions {
|
export interface RenderOptions {
|
||||||
page: Page;
|
page: Page;
|
||||||
imports: string[];
|
imports: string[];
|
||||||
preloads: string[];
|
preloads: string[];
|
||||||
params: Record<string, string>;
|
url: URL;
|
||||||
|
params: Record<string, string | string[]>;
|
||||||
renderer: Renderer;
|
renderer: Renderer;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -17,9 +19,13 @@ export class RenderContext {
|
|||||||
#id: string;
|
#id: string;
|
||||||
#state: Map<string, unknown> = new Map();
|
#state: Map<string, unknown> = new Map();
|
||||||
#head: ComponentChild[] = [];
|
#head: ComponentChild[] = [];
|
||||||
|
#url: URL;
|
||||||
|
#route: string;
|
||||||
|
|
||||||
constructor(id: string) {
|
constructor(id: string, url: URL, route: string) {
|
||||||
this.#id = id;
|
this.#id = id;
|
||||||
|
this.#url = url;
|
||||||
|
this.#route = route;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A unique ID for this logical JIT render. */
|
/** A unique ID for this logical JIT render. */
|
||||||
@@ -42,12 +48,23 @@ export class RenderContext {
|
|||||||
get head(): ComponentChild[] {
|
get head(): ComponentChild[] {
|
||||||
return this.#head;
|
return this.#head;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The URL of the page being rendered. */
|
||||||
|
get url(): URL {
|
||||||
|
return this.#url;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The route matcher (e.g. /blog/:id) that the request matched for this page
|
||||||
|
* to be rendered. */
|
||||||
|
get route(): string {
|
||||||
|
return this.#route;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const MAX_SUSPENSE_DEPTH = 10;
|
const MAX_SUSPENSE_DEPTH = 10;
|
||||||
|
|
||||||
export async function render(opts: RenderOptions): Promise<string> {
|
export async function render(opts: RenderOptions): Promise<string> {
|
||||||
const props = { params: opts.params };
|
const props = { params: opts.params, url: opts.url, route: opts.page.route };
|
||||||
|
|
||||||
const dataCache = new Map();
|
const dataCache = new Map();
|
||||||
|
|
||||||
@@ -56,7 +73,7 @@ export async function render(opts: RenderOptions): Promise<string> {
|
|||||||
children: h(opts.page.component, props),
|
children: h(opts.page.component, props),
|
||||||
});
|
});
|
||||||
|
|
||||||
const ctx = new RenderContext(crypto.randomUUID());
|
const ctx = new RenderContext(crypto.randomUUID(), opts.url, opts.page.route);
|
||||||
|
|
||||||
let suspended = 0;
|
let suspended = 0;
|
||||||
const renderWithRenderer = (): string | Promise<string> => {
|
const renderWithRenderer = (): string | Promise<string> => {
|
||||||
@@ -97,19 +114,15 @@ export async function render(opts: RenderOptions): Promise<string> {
|
|||||||
opts.renderer.postRender(ctx, bodyHtml);
|
opts.renderer.postRender(ctx, bodyHtml);
|
||||||
|
|
||||||
let templateProps: {
|
let templateProps: {
|
||||||
params?: Record<string, string>;
|
props: PageProps;
|
||||||
data?: [string, unknown][];
|
data?: [string, unknown][];
|
||||||
} | undefined = { params: opts.params, data: [...dataCache.entries()] };
|
} | undefined = { props, data: [...dataCache.entries()] };
|
||||||
if (Object.entries(templateProps.params!).length === 0) {
|
|
||||||
delete templateProps.params;
|
|
||||||
}
|
|
||||||
if (templateProps.data!.length === 0) {
|
if (templateProps.data!.length === 0) {
|
||||||
delete templateProps.data;
|
delete templateProps.data;
|
||||||
}
|
}
|
||||||
if (Object.entries(templateProps).length === 0) {
|
|
||||||
templateProps = undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
// If this is a static render (runtimeJS is false), then we don't need to
|
||||||
|
// render the props into the template.
|
||||||
if (opts.imports.length === 0) {
|
if (opts.imports.length === 0) {
|
||||||
templateProps = undefined;
|
templateProps = undefined;
|
||||||
}
|
}
|
||||||
@@ -144,11 +157,13 @@ export function template(opts: TemplateOptions): string {
|
|||||||
<body>
|
<body>
|
||||||
<div dangerouslySetInnerHTML={{ __html: opts.bodyHtml }} id="__FRSH" />
|
<div dangerouslySetInnerHTML={{ __html: opts.bodyHtml }} id="__FRSH" />
|
||||||
{opts.props !== undefined
|
{opts.props !== undefined
|
||||||
? <script
|
? (
|
||||||
id="__FRSH_PROPS"
|
<script
|
||||||
type="application/json"
|
id="__FRSH_PROPS"
|
||||||
dangerouslySetInnerHTML={{ __html: JSON.stringify(opts.props) }}
|
type="application/json"
|
||||||
/>
|
dangerouslySetInnerHTML={{ __html: JSON.stringify(opts.props) }}
|
||||||
|
/>
|
||||||
|
)
|
||||||
: null}
|
: null}
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { h, PageProps } from "../../deps.ts";
|
||||||
|
|
||||||
|
export default function Home(props: PageProps) {
|
||||||
|
return <div>{JSON.stringify(props)}</div>;
|
||||||
|
}
|
||||||
+12
-10
@@ -2,19 +2,21 @@
|
|||||||
// This file SHOULD be checked into source version control.
|
// This file SHOULD be checked into source version control.
|
||||||
// To update this file, run `fresh routes`.
|
// To update this file, run `fresh routes`.
|
||||||
|
|
||||||
import * as $0 from "./pages/api/name.ts";
|
import * as $0 from "./pages/index.tsx";
|
||||||
import * as $1 from "./pages/api/get_only.ts";
|
import * as $1 from "./pages/static.tsx";
|
||||||
import * as $2 from "./pages/static.tsx";
|
import * as $2 from "./pages/props/[id].tsx";
|
||||||
import * as $3 from "./pages/[name].tsx";
|
import * as $3 from "./pages/api/get_only.ts";
|
||||||
import * as $4 from "./pages/index.tsx";
|
import * as $4 from "./pages/api/name.ts";
|
||||||
|
import * as $5 from "./pages/[name].tsx";
|
||||||
|
|
||||||
const routes = {
|
const routes = {
|
||||||
pages: {
|
pages: {
|
||||||
"./pages/api/name.ts": $0,
|
"./pages/index.tsx": $0,
|
||||||
"./pages/api/get_only.ts": $1,
|
"./pages/static.tsx": $1,
|
||||||
"./pages/static.tsx": $2,
|
"./pages/props/[id].tsx": $2,
|
||||||
"./pages/[name].tsx": $3,
|
"./pages/api/get_only.ts": $3,
|
||||||
"./pages/index.tsx": $4,
|
"./pages/api/name.ts": $4,
|
||||||
|
"./pages/[name].tsx": $5,
|
||||||
},
|
},
|
||||||
baseUrl: import.meta.url,
|
baseUrl: import.meta.url,
|
||||||
};
|
};
|
||||||
|
|||||||
+12
-1
@@ -17,13 +17,24 @@ Deno.test("/ page prerender", async () => {
|
|||||||
body,
|
body,
|
||||||
`<script id="__FRSH_PROPS" type="application/json">`,
|
`<script id="__FRSH_PROPS" type="application/json">`,
|
||||||
);
|
);
|
||||||
assert(!body.includes(`"params"`));
|
|
||||||
assertStringIncludes(
|
assertStringIncludes(
|
||||||
body,
|
body,
|
||||||
`"data":[["home","Hello!"]]`,
|
`"data":[["home","Hello!"]]`,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
Deno.test("/props/123 page prerender", async () => {
|
||||||
|
const resp = await router(new Request("https://fresh.deno.dev/props/123"));
|
||||||
|
assert(resp);
|
||||||
|
assertEquals(resp.status, 200);
|
||||||
|
assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8");
|
||||||
|
const body = await resp.text();
|
||||||
|
assertStringIncludes(
|
||||||
|
body,
|
||||||
|
`{"props":{"params":{"id":"123"},"url":"https://fresh.deno.dev/props/123","route":"/props/:id"}}`,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
Deno.test("/[name] page prerender", async () => {
|
Deno.test("/[name] page prerender", async () => {
|
||||||
const resp = await router(new Request("https://fresh.deno.dev/foo"));
|
const resp = await router(new Request("https://fresh.deno.dev/foo"));
|
||||||
assert(resp);
|
assert(resp);
|
||||||
|
|||||||
Reference in New Issue
Block a user