From 660e0f5fefe9ccee36e9ef51bc6f726f403f6877 Mon Sep 17 00:00:00 2001 From: Luca Casonato Date: Tue, 9 Aug 2022 21:41:11 +0200 Subject: [PATCH] feat: twind plugin (#513) This adds a first-party twind plugin to use twind for styling. --- .vscode/extensions.json | 6 +++ .vscode/import_map.json | 1 - init.ts | 78 ++++++++++----------------- plugins/twind.ts | 40 ++++++++++++++ plugins/twind/main.ts | 21 ++++++++ plugins/twind/shared.ts | 80 ++++++++++++++++++++++++++++ tests/cli_test.ts | 8 +-- www/components/Button.tsx | 3 +- www/components/DocsSidebar.tsx | 25 ++++----- www/components/Footer.tsx | 17 ++---- www/components/Icons.tsx | 5 +- www/components/NavigationBar.tsx | 7 ++- www/import_map.json | 1 - www/islands/Counter.tsx | 7 +-- www/islands/LemonDrop.tsx | 5 +- www/main.ts | 21 ++------ www/routes/docs/[...slug].tsx | 91 ++++++++++++++------------------ www/routes/index.tsx | 81 ++++++++++++---------------- www/twind.config.js | 16 ++++++ www/utils/twind.ts | 21 -------- 20 files changed, 296 insertions(+), 238 deletions(-) create mode 100644 .vscode/extensions.json create mode 100644 plugins/twind.ts create mode 100644 plugins/twind/main.ts create mode 100644 plugins/twind/shared.ts create mode 100644 www/twind.config.js delete mode 100644 www/utils/twind.ts diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 00000000..971c0ed5 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,6 @@ +{ + "recommendations": [ + "denoland.vscode-deno", + "sastan.twind-intellisense" + ] +} diff --git a/.vscode/import_map.json b/.vscode/import_map.json index 2aed60a3..2ba2e0fc 100644 --- a/.vscode/import_map.json +++ b/.vscode/import_map.json @@ -3,7 +3,6 @@ "imports": { "$fresh/": "../", - "@twind": "../www/utils/twind.ts", "twind": "https://esm.sh/twind@0.16.17", "twind/": "https://esm.sh/twind@0.16.17/", diff --git a/init.ts b/init.ts index 12992e3c..3e6432eb 100644 --- a/init.ts +++ b/init.ts @@ -90,9 +90,6 @@ await Deno.mkdir(join(resolvedDirectory, "components"), { recursive: true }); if (useVSCode) { await Deno.mkdir(join(resolvedDirectory, ".vscode"), { recursive: true }); } -if (useTwind) { - await Deno.mkdir(join(resolvedDirectory, "utils"), { recursive: true }); -} const importMap = { "imports": { @@ -104,7 +101,6 @@ const importMap = { } as Record, }; if (useTwind) { - importMap.imports["@twind"] = "./utils/twind.ts"; importMap.imports["twind"] = "https://esm.sh/twind@0.16.17"; importMap.imports["twind/"] = "https://esm.sh/twind@0.16.17/"; } @@ -114,20 +110,19 @@ await Deno.writeTextFile( IMPORT_MAP_JSON, ); -let ROUTES_INDEX_TSX = `/** @jsx h */ -import { h } from "preact";\n`; -if (useTwind) ROUTES_INDEX_TSX += `import { tw } from "@twind";\n`; -ROUTES_INDEX_TSX += `import Counter from "../islands/Counter.tsx"; +const ROUTES_INDEX_TSX = `/** @jsx h */ +import { h } from "preact"; +import Counter from "../islands/Counter.tsx"; export default function Home() { return ( - + the fresh logo: a sliced lemon dripping with juice - + Welcome to \`fresh\`. Try updating this message in the ./routes/index.tsx file, and refresh.

@@ -144,17 +139,16 @@ await Deno.writeTextFile( const COMPONENTS_BUTTON_TSX = `/** @jsx h */ import { h } from "preact"; import { IS_BROWSER } from "$fresh/runtime.ts"; -${useTwind ? 'import { tw } from "@twind";\n' : ""} export function Button(props: h.JSX.HTMLAttributes) { return ( ); } `; - await Deno.writeTextFile( join(resolvedDirectory, "islands", "Counter.tsx"), ISLANDS_COUNTER_TSX, @@ -232,19 +222,14 @@ await Deno.writeTextFile( ROUTES_API_JOKE_TS, ); -const UTILS_TWIND_TS = `import { IS_BROWSER } from "$fresh/runtime.ts"; -import { Configuration, setup } from "twind"; -export * from "twind"; -export const config: Configuration = { - darkMode: "class", - mode: "silent", -}; -if (IS_BROWSER) setup(config); +const TWIND_CONFIG_JS = + `/** @type {import("$fresh/plugins/twind.ts").Options} */ +export default {}; `; if (useTwind) { await Deno.writeTextFile( - join(resolvedDirectory, "utils", "twind.ts"), - UTILS_TWIND_TS, + join(resolvedDirectory, "twind.config.js"), + TWIND_CONFIG_JS, ); } @@ -277,34 +262,21 @@ let MAIN_TS = `/// /// /// -import { ${ - useTwind ? "InnerRenderFunction, RenderContext, " : "" -}start } from "$fresh/server.ts"; +import { start } from "$fresh/server.ts"; import manifest from "./fresh.gen.ts"; `; if (useTwind) { MAIN_TS += ` -import { config, setup } from "@twind"; -import { virtualSheet } from "twind/sheets"; - -const sheet = virtualSheet(); -sheet.reset(); -setup({ ...config, sheet }); - -function render(ctx: RenderContext, render: InnerRenderFunction) { - const snapshot = ctx.state.get("twind") as unknown[] | null; - sheet.reset(snapshot || undefined); - render(); - ctx.styles.splice(0, ctx.styles.length, ...(sheet).target); - const newSnapshot = sheet.reset(); - ctx.state.set("twind", newSnapshot); -} - +import twindPlugin from "$fresh/plugins/twind.ts"; +import twindConfig from "./twind.config.js"; `; } -MAIN_TS += `await start(manifest${useTwind ? ", { render }" : ""});\n`; +MAIN_TS += ` +await start(manifest${ + useTwind ? ", { plugins: [twindPlugin(twindConfig)] }" : "" +});\n`; const MAIN_TS_PATH = join(resolvedDirectory, "main.ts"); await Deno.writeTextFile(MAIN_TS_PATH, MAIN_TS); @@ -368,6 +340,10 @@ const vscodeExtensions = { recommendations: ["denoland.vscode-deno"], }; +if (useTwind) { + vscodeExtensions.recommendations.push("sastan.twind-intellisense"); +} + const VSCODE_EXTENSIONS = JSON.stringify(vscodeExtensions, null, 2) + "\n"; if (useVSCode) { diff --git a/plugins/twind.ts b/plugins/twind.ts new file mode 100644 index 00000000..315309ea --- /dev/null +++ b/plugins/twind.ts @@ -0,0 +1,40 @@ +import { virtualSheet } from "twind/sheets"; +import { Plugin } from "../server.ts"; + +import { Options, setup, STYLE_ELEMENT_ID } from "./twind/shared.ts"; +export type { Options }; + +export default function twind(options: Options): Plugin { + const sheet = virtualSheet(); + setup(options, sheet); + return { + name: "twind", + entrypoints: { "main": new URL("./twind/main.ts", import.meta.url).href }, + render(ctx) { + sheet.reset(undefined); + const res = ctx.render(); + const cssText = [...sheet.target].join("\n"); + const snapshot = sheet.reset(); + const scripts = []; + if (res.requiresHydration) { + const precedences = snapshot[1]; + const mappings: (string | [string, string])[] = []; + for ( + const [key, value] of (snapshot[3] as Map).entries() + ) { + if (key === value) { + mappings.push(key); + } else { + mappings.push([key, value]); + } + } + const state = [options, precedences, mappings]; + scripts.push({ entrypoint: "main", state }); + } + return { + scripts, + styles: [{ cssText, id: STYLE_ELEMENT_ID }], + }; + }, + }; +} diff --git a/plugins/twind/main.ts b/plugins/twind/main.ts new file mode 100644 index 00000000..664da4e0 --- /dev/null +++ b/plugins/twind/main.ts @@ -0,0 +1,21 @@ +import { Sheet } from "twind"; +import { Options, setup, STYLE_ELEMENT_ID } from "./shared.ts"; + +type State = [Options, string[], [string, string][]]; + +export default function hydrate(state: State) { + const el = document.getElementById(STYLE_ELEMENT_ID) as HTMLStyleElement; + const rules = new Set(el.innerText.split("\n")); + const precedences = state[1]; + const mappings = new Map(state[2] + .map((v) => typeof v === "string" ? [v, v] : v)); + // deno-lint-ignore no-explicit-any + const sheetState: any[] = [precedences, rules, mappings, true]; + const target = el.sheet!; + const sheet: Sheet = { + target, + insert: (rule, index) => target.insertRule(rule, index), + init: (cb) => cb(sheetState.shift()), + }; + setup(state[0], sheet); +} diff --git a/plugins/twind/shared.ts b/plugins/twind/shared.ts new file mode 100644 index 00000000..79f747e9 --- /dev/null +++ b/plugins/twind/shared.ts @@ -0,0 +1,80 @@ +import { JSX, options as preactOptions, VNode } from "preact"; +import { + Configuration, + DarkMode, + setup as twSetup, + Sheet, + ThemeConfiguration, + tw, +} from "twind"; + +export const STYLE_ELEMENT_ID = "__FRSH_TWIND"; + +export interface Options { + /** + * Determines the dark mode strategy (default: `"media"`). + */ + darkMode?: DarkMode; + + /** + * The twind theme to use. + */ + theme?: ThemeConfiguration; + + /** + * ```js + * { + * ':new-variant': '& .selector', + * } + * ``` + */ + variants?: Record; + + /** + * Configure wether the class names should be emitted "as is", or if they + * should be hashed. + */ + hash?: boolean; +} + +declare module "preact" { + namespace JSX { + interface DOMAttributes { + class?: string; + className?: string; + } + } +} + +export function setup(options: Options, sheet: Sheet) { + const config: Configuration = { + darkMode: options.darkMode, + hash: options.hash, + mode: "silent", + sheet, + variants: options.variants, + theme: options.theme, + }; + twSetup(config); + + const originalHook = preactOptions.vnode; + // deno-lint-ignore no-explicit-any + preactOptions.vnode = (vnode: VNode>) => { + 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); + }; +} diff --git a/tests/cli_test.ts b/tests/cli_test.ts index f021be8e..32821997 100644 --- a/tests/cli_test.ts +++ b/tests/cli_test.ts @@ -206,6 +206,7 @@ Deno.test({ { "type": "file", "name": "README.md" }, { "type": "file", "name": "import_map.json" }, { "type": "file", "name": "fresh.gen.ts" }, + { "type": "file", "name": "twind.config.js" }, { "type": "directory", "name": "components", @@ -243,13 +244,6 @@ Deno.test({ { "type": "file", "name": "logo.svg" }, ], }, - { - "type": "directory", - "name": "utils", - "contents": [ - { "type": "file", "name": "twind.ts" }, - ], - }, { "type": "directory", "name": ".vscode", diff --git a/www/components/Button.tsx b/www/components/Button.tsx index d94503d7..868d9139 100644 --- a/www/components/Button.tsx +++ b/www/components/Button.tsx @@ -1,6 +1,5 @@ /** @jsx h */ import { h } from "preact"; -import { tw } from "@twind"; export function RoundedButton(props: h.JSX.HTMLAttributes) { return ( @@ -9,7 +8,7 @@ export function RoundedButton(props: h.JSX.HTMLAttributes) { touchAction: "manipulation", }} {...props} - class={tw`p-3 border border-transparent rounded-full text-white bg-green(500 hover:600) focus:(outline-none ring(2 offset-2 green-500)) disabled:(bg-green-200 cursor-default)`} + class="p-3 border border-transparent rounded-full text-white bg-green(500 hover:600) focus:(outline-none ring(2 offset-2 green-500)) disabled:(bg-green-200 cursor-default)}" /> ); } diff --git a/www/components/DocsSidebar.tsx b/www/components/DocsSidebar.tsx index 27e4658a..80c684f6 100644 --- a/www/components/DocsSidebar.tsx +++ b/www/components/DocsSidebar.tsx @@ -1,6 +1,5 @@ /** @jsx h */ import { h } from "preact"; -import { apply, tw } from "@twind"; import { CATEGORIES, @@ -10,7 +9,7 @@ import { export default function DocsSidebar(props: { path: string }) { return ( -
    +
      {CATEGORIES.map((category) => ( ))} @@ -18,24 +17,22 @@ export default function DocsSidebar(props: { path: string }) { ); } -const link = apply`text(gray-900 hover:gray-600)`; -const linkActive = apply`text(green-600 hover:green-500)`; +const link = "text(gray-900 hover:gray-600)"; +const linkActive = "text(green-600 hover:green-500)"; export function SidebarCategory(props: { path: string; category: TableOfContentsCategory; }) { - const outerItem = tw`my-2 block`; - const innerList = tw`pl-4 list-decimal` + " nested"; - const { title, href, entries } = props.category; - const outerLink = tw`${href == props.path ? linkActive : link} font-bold`; + + const outerLink = `${href == props.path ? linkActive : link} font-bold`; return ( -
    1. +
    2. {title} {entries.length > 0 && ( -
        +
          {entries.map((entry) => ( ))} @@ -49,12 +46,12 @@ export function SidebarEntry(props: { path: string; entry: TableOfContentsCategoryEntry; }) { - const innerItem = tw`my-0.5`; - const { title, href } = props.entry; - const innerLink = tw`${href == props.path ? linkActive : link} font-normal`; + + const innerLink = `${href == props.path ? linkActive : link} font-normal`; + return ( -
        1. +
        2. {title}
        3. ); diff --git a/www/components/Footer.tsx b/www/components/Footer.tsx index 8ba33d50..37f014ee 100644 --- a/www/components/Footer.tsx +++ b/www/components/Footer.tsx @@ -1,6 +1,5 @@ /** @jsx h */ import { h } from "preact"; -import { tw } from "@twind"; const LINKS = [ { @@ -18,23 +17,17 @@ const LINKS = [ ]; export default function Footer() { - const footer = - tw`border(t-2 gray-200) bg-gray-100 h-32 flex flex-col gap-4 justify-center`; - const inner = - tw`mx-auto max-w-screen-lg flex items-center justify-center gap-8`; - const linkStyle = tw`text-gray-600 hover:underline`; - const copyright = tw`text(gray-600 center)`; return ( -