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
+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>;
}