feat: add twindv1 plugin (#946)

This commit is contained in:
Thomas Crescenzi
2023-02-24 12:32:29 -05:00
committed by GitHub
parent ed66986500
commit 5bb67aff1f
3 changed files with 84 additions and 0 deletions
+31
View File
@@ -0,0 +1,31 @@
import { stringify, virtual } from "https://esm.sh/@twind/core@1.1.3";
import { Plugin } from "../server.ts";
import { Options, setup, STYLE_ELEMENT_ID } from "./twindv1/shared.ts";
export type { Options };
export default function twindv1(options: Options): Plugin {
const sheet = virtual(true);
setup(options, sheet);
const main = `data:application/javascript,import hydrate from "${
new URL("./twindv1/main.ts", import.meta.url).href
}";
import options from "${options.selfURL}";
export default function(state) { hydrate(options, state); }`;
return {
name: "twind",
entrypoints: { "main": main },
render(ctx) {
const res = ctx.render();
const cssText = stringify(sheet.target);
const scripts = [];
if (res.requiresHydration) {
scripts.push({ entrypoint: "main", state: [] });
}
return {
scripts,
styles: [{ cssText, id: STYLE_ELEMENT_ID }],
};
},
};
}
+5
View File
@@ -0,0 +1,5 @@
import { getSheet, setup, TwindConfig } from "https://esm.sh/@twind/core@1.1.3";
export default function hydrate(options: TwindConfig) {
setup(options, getSheet());
}
+48
View File
@@ -0,0 +1,48 @@
import { JSX, options as preactOptions, VNode } from "preact";
import {
setup as twSetup,
Sheet,
tw,
TwindConfig,
} from "https://esm.sh/@twind/core@1.1.3";
export const STYLE_ELEMENT_ID = "__FRSH_TWIND";
export interface Options extends TwindConfig {
/** The import.meta.url of the module defining these options. */
selfURL: string;
}
declare module "preact" {
namespace JSX {
interface DOMAttributes<Target extends EventTarget> {
class?: string;
className?: string;
}
}
}
export function setup({ selfURL: _selfURL, ...config }: Options, sheet: Sheet) {
twSetup(config, sheet);
const originalHook = preactOptions.vnode;
// deno-lint-ignore no-explicit-any
preactOptions.vnode = (vnode: VNode<JSX.DOMAttributes<any>>) => {
if (typeof vnode.type === "string" && typeof vnode.props === "object") {
const { props } = vnode;
const classes: string[] = [];
if (props.class) {
classes.push(tw(props.class));
props.class = undefined;
}
if (props.className) {
classes.push(tw(props.className));
}
if (classes.length) {
props.class = classes.join(" ");
}
}
originalHook?.(vnode);
};
}