feat: add custom render function support (#30)

This commit is contained in:
Luca Casonato
2021-06-16 19:36:12 +02:00
committed by GitHub
parent 1346105a79
commit 940f34d811
11 changed files with 236 additions and 39 deletions
+11
View File
@@ -0,0 +1,11 @@
import { h, tw } from "../deps.ts";
export function RoundedButton(props: h.JSX.HTMLAttributes<HTMLButtonElement>) {
return (
<button
{...props}
class={tw
`p-3 border border-transparent rounded-full text-white bg-indigo(600 hover:700) focus:(outline-none ring(2 offset-2 indigo-500)) disabled:(bg-indigo-200 cursor-default)`}
/>
);
}
+41
View File
@@ -0,0 +1,41 @@
import { h, tw } from "../deps.ts";
export function IconMinus() {
return (
<svg
class={tw`h-6 w-6`}
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M20 12H4"
/>
</svg>
);
}
export function IconPlus() {
return (
<svg
class={tw`h-6 w-6`}
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 6v6m0 0v6m0-6h6m-6 0H6"
/>
</svg>
);
}
+6
View File
@@ -1 +1,7 @@
export * from "../runtime.ts";
import { IS_BROWSER } from "../runtime.ts";
import { setup, tw } from "https://esm.sh/twind";
export { setup, tw };
if (IS_BROWSER) {
setup({});
}
+32
View File
@@ -0,0 +1,32 @@
// This module adds twind support.
import {
getStyleTagProperties,
virtualSheet,
} from "https://esm.sh/twind/sheets";
import { h, setup } from "../deps.ts";
import { RenderContext, RenderFn } from "../server_deps.ts";
const sheet = virtualSheet();
const initial = sheet.reset();
setup({ sheet });
export function render(ctx: RenderContext, render: RenderFn) {
const snapshot = ctx.state.get("twindSnapshot") as unknown[] | null;
sheet.reset(snapshot || initial);
render();
const newSnapshot = sheet.reset(initial);
ctx.state.set("twindSnapshot", newSnapshot);
}
export function postRender(ctx: RenderContext) {
const snapshot = ctx.state.get("twindSnapshot") as unknown[] | null;
if (snapshot !== null) {
sheet.reset(snapshot);
const { id, textContent } = getStyleTagProperties(sheet);
ctx.head.push(
h("style", { id, dangerouslySetInnerHTML: { __html: textContent } }),
);
}
sheet.reset(initial);
}
+26 -18
View File
@@ -1,33 +1,41 @@
import { h, IS_BROWSER, useState } from "../deps.ts";
import { RoundedButton } from "../components/Button.tsx";
import { IconMinus, IconPlus } from "../components/Icons.tsx";
import { h, IS_BROWSER, tw, useState } from "../deps.ts";
export default function Home() {
return (
<div>
<p>
<div class={tw`max-w-screen-md px-4 mx-auto my-8`}>
<p class={tw`font-bold`}>
Welcome to `fresh`. Try update this message in the ./pages/index.tsx
file, and refresh.
</p>
<Counter />
<p>{IS_BROWSER ? "Viewing browser render." : "Viewing JIT render."}</p>
<p class={tw`mt-4`}>
{IS_BROWSER ? "Viewing browser render." : "Viewing JIT render."}
</p>
</div>
);
}
function Counter() {
const [count, setCount] = useState(0);
return <div>
<p>{count}</p>
<button
onClick={() => setCount(count - 1)}
disabled={!IS_BROWSER}
>
-1
</button>
<button
onClick={() => setCount(count + 1)}
disabled={!IS_BROWSER}
>
+1
</button>
return <div class={tw`mt-4 border rounded p-4 text-center`}>
<p class={tw`text-lg font-medium`}>Current count: {count}</p>
<div class={tw`flex gap-2 mt-4 justify-center`}>
<RoundedButton
type="button"
onClick={() => setCount(count - 1)}
disabled={!IS_BROWSER}
>
<IconMinus />
</RoundedButton>
<RoundedButton
type="button"
onClick={() => setCount(count + 1)}
disabled={!IS_BROWSER}
>
<IconPlus />
</RoundedButton>
</div>
</div>;
}
+8 -6
View File
@@ -3,16 +3,18 @@
// To update this file, run `fresh routes`.
import * as $0 from "./pages/api/joke.ts";
import * as $1 from "./pages/x/[module].tsx";
import * as $2 from "./pages/[name].tsx";
import * as $3 from "./pages/index.tsx";
import * as $1 from "./pages/_render.ts";
import * as $2 from "./pages/x/[module].tsx";
import * as $3 from "./pages/[name].tsx";
import * as $4 from "./pages/index.tsx";
const routes = {
pages: {
"./pages/api/joke.ts": $0,
"./pages/x/[module].tsx": $1,
"./pages/[name].tsx": $2,
"./pages/index.tsx": $3,
"./pages/_render.ts": $1,
"./pages/x/[module].tsx": $2,
"./pages/[name].tsx": $3,
"./pages/index.tsx": $4,
},
baseUrl: import.meta.url,
};
+1
View File
@@ -0,0 +1 @@
export * from "../server.ts";
+26 -3
View File
@@ -4,17 +4,26 @@ import { Bundler } from "./bundle.ts";
import { INTERNAL_PREFIX } from "./constants.ts";
import { JS_PREFIX } from "./constants.ts";
import { BUILD_ID } from "./constants.ts";
import { ApiRoute, ApiRouteModule, Page, PageModule } from "./types.ts";
import {
ApiRoute,
ApiRouteModule,
Page,
PageModule,
Renderer,
RendererModule,
} from "./types.ts";
import { render } from "./render.tsx";
export class ServerContext {
#pages: Page[];
#apiRoutes: ApiRoute[];
#bundler: Bundler;
#renderer: Renderer;
constructor(pages: Page[], apiRoutes: ApiRoute[]) {
constructor(pages: Page[], apiRoutes: ApiRoute[], renderer: Renderer) {
this.#pages = pages;
this.#apiRoutes = apiRoutes;
this.#renderer = renderer;
this.#bundler = new Bundler(pages);
}
@@ -28,6 +37,7 @@ export class ServerContext {
// Extract all pages, and prepare them into this `Page` structure.
const pages: Page[] = [];
const apiRoutes: ApiRoute[] = [];
let renderer: Renderer = DEFAULT_RENDERER;
for (const [self, module] of Object.entries(routes.pages)) {
const url = new URL(self, baseUrl).href;
if (!url.startsWith(baseUrl)) {
@@ -60,12 +70,17 @@ export class ServerContext {
runtimeJS: config?.runtimeJS ?? true,
};
pages.push(page);
} else if (
path === "/_render.tsx" || path === "/_render.ts" ||
path === "/_render.jsx" || path === "/_render.js"
) {
renderer = module as RendererModule;
}
}
sortRoutes(pages);
sortRoutes(apiRoutes);
return new ServerContext(pages, apiRoutes);
return new ServerContext(pages, apiRoutes, renderer);
}
/**
@@ -86,6 +101,7 @@ export class ServerContext {
page,
imports: page.runtimeJS ? imports : [],
preloads: page.runtimeJS ? preloads : [],
renderer: this.#renderer,
params: match.params,
});
return new Response(body, {
@@ -151,6 +167,13 @@ function bundleAssetUrl(path: string) {
return `${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}${path}`;
}
const DEFAULT_RENDERER: Renderer = {
render(_ctx, render) {
render();
},
postRender(_ctx) {},
};
/**
* Sort pages by their relative routing priority, based on the parts in the
* route matcher
+4 -2
View File
@@ -1,9 +1,11 @@
import { ServerContext } from "./context.ts";
import { router } from "./deps.ts";
import { ApiRouteModule, PageModule } from "./types.ts";
import { ApiRouteModule, PageModule, RendererModule } from "./types.ts";
export { RenderContext } from "./render.tsx";
export type { RenderFn } from "./render.tsx";
export interface Routes {
pages: Record<string, PageModule | ApiRouteModule>;
pages: Record<string, PageModule | ApiRouteModule | RendererModule>;
baseUrl: string;
}
+70 -10
View File
@@ -1,13 +1,47 @@
import { renderToString } from "./deps.ts";
import { h } from "../runtime/deps.ts";
import { generateUuid, renderToString } from "./deps.ts";
import { ComponentChild, h } from "../runtime/deps.ts";
import { DATA_CONTEXT } from "../runtime/hooks.ts";
import { Page } from "./types.ts";
import { Page, Renderer } from "./types.ts";
export interface RenderOptions {
page: Page;
imports: string[];
preloads: string[];
params: Record<string, string>;
renderer: Renderer;
}
export type RenderFn = () => void;
export class RenderContext {
#id: string;
#state: Map<string, unknown> = new Map();
#head: ComponentChild[] = [];
constructor(id: string) {
this.#id = id;
}
/** A unique ID for this logical JIT render. */
get id(): string {
return this.#id;
}
/**
* State that is persisted between multiple renders with the same render
* context. This is useful because one logical JIT render could have multiple
* preact render passes due to suspense.
*/
get state(): Map<string, unknown> {
return this.#state;
}
/**
* Items to add to the <head> for this render.
*/
get head(): ComponentChild[] {
return this.#head;
}
}
const MAX_SUSPENSE_DEPTH = 10;
@@ -22,22 +56,45 @@ export async function render(opts: RenderOptions): Promise<string> {
children: h(opts.page.component, props),
});
const ctx = new RenderContext(generateUuid());
let suspended = 0;
const render = (): string | Promise<string> => {
const renderWithRenderer = (): string | Promise<string> => {
if (++suspended > MAX_SUSPENSE_DEPTH) {
throw new Error(
`Reached maximum suspense depth of ${MAX_SUSPENSE_DEPTH}.`,
);
}
try {
return renderToString(vnode);
} catch (e) {
if (e && e.then) return e.then(render);
throw e;
let body: string | null = null;
let promise: Promise<unknown> | null = null;
function render() {
try {
body = renderToString(vnode);
} catch (e) {
if (e && e.then) {
promise = e;
return;
}
throw e;
}
}
opts.renderer.render(ctx, render);
if (body !== null) {
return body;
} else if (promise !== null) {
return (promise as Promise<unknown>).then(renderWithRenderer);
} else {
throw new Error("`render` function not called by renderer.");
}
};
const bodyHtml = await render();
const bodyHtml = await renderWithRenderer();
opts.renderer.postRender(ctx, bodyHtml);
let templateProps: {
params?: Record<string, string>;
@@ -61,6 +118,7 @@ export async function render(opts: RenderOptions): Promise<string> {
bodyHtml,
imports: opts.imports,
preloads: opts.preloads,
head: ctx.head,
props: templateProps,
});
@@ -70,6 +128,7 @@ export async function render(opts: RenderOptions): Promise<string> {
export interface TemplateOptions {
bodyHtml: string;
imports: string[];
head: ComponentChild[];
preloads: string[];
props: unknown;
}
@@ -80,6 +139,7 @@ export function template(opts: TemplateOptions): string {
<head>
{opts.preloads.map((src) => <link rel="modulepreload" href={src} />)}
{opts.imports.map((src) => <script src={src} type="module"></script>)}
{opts.head}
</head>
<body>
<div dangerouslySetInnerHTML={{ __html: opts.bodyHtml }} id="__FRSH" />
+11
View File
@@ -1,6 +1,7 @@
import { ComponentType } from "../runtime/deps.ts";
import { router } from "./deps.ts";
import { PageConfig, PageProps } from "../runtime/types.ts";
import { RenderContext, RenderFn } from "./render.tsx";
export interface PageModule {
default: ComponentType<PageProps>;
@@ -25,3 +26,13 @@ export interface ApiRoute {
name: string;
handlers: Record<string, router.MatchHandler>;
}
export interface RendererModule {
render(ctx: RenderContext, render: RenderFn): void;
postRender(ctx: RenderContext, bodyHtml: string): void;
}
export interface Renderer {
render(ctx: RenderContext, render: RenderFn): void;
postRender(ctx: RenderContext, bodyHtml: string): void;
}