diff --git a/init.ts b/init.ts index ad7e2773..e3609e1c 100644 --- a/init.ts +++ b/init.ts @@ -1,4 +1,4 @@ -import { join, resolve } from "./src/dev/deps.ts"; +import { join, parse, resolve } from "./src/dev/deps.ts"; import { error } from "./src/dev/error.ts"; import { collect, generate } from "./src/dev/mod.ts"; @@ -15,12 +15,24 @@ To generate a project in the current directory: USAGE: fresh-init + +OPTIONS: + --force Overwrite existing files + --twind Setup project to use 'twind' for styling `; const CONFIRM_EMPTY_MESSAGE = "The target directory is not empty (files could get overwritten). Do you want to continue anyway?"; -if (Deno.args.length !== 1) { +const USE_TWIND_MESSAGE = + "Do you want to use 'twind' (https://twind.dev/) for styling?"; + +const flags = parse(Deno.args, { + boolean: ["force", "twind"], + default: { "force": null, "twind": null }, +}); + +if (flags._.length !== 1) { error(help); } @@ -31,7 +43,10 @@ try { const dir = [...Deno.readDirSync(directory)]; const isEmpty = dir.length === 0 || dir.length === 1 && dir[0].name === ".git"; - if (!isEmpty && !confirm(CONFIRM_EMPTY_MESSAGE)) { + if ( + !isEmpty && + !(flags.force === null ? confirm(CONFIRM_EMPTY_MESSAGE) : flags.force) + ) { error("Directory is not empty."); } } catch (err) { @@ -40,34 +55,46 @@ try { } } +const useTwind = flags.twind === null + ? confirm(USE_TWIND_MESSAGE) + : flags.twind; + await Deno.mkdir(join(directory, "routes", "api"), { recursive: true }); await Deno.mkdir(join(directory, "islands"), { recursive: true }); await Deno.mkdir(join(directory, "static"), { recursive: true }); +if (useTwind) await Deno.mkdir(join(directory, "utils"), { recursive: true }); -const IMPORT_MAP_JSON = JSON.stringify( - { - "imports": { - "$fresh/": new URL("./", import.meta.url).href, - "preact": "https://esm.sh/preact@10.6.6", - "preact/": "https://esm.sh/preact@10.6.6/", - "preact-render-to-string": - "https://esm.sh/preact-render-to-string@5.1.20?deps=preact@10.6.6", - }, - }, - null, - 2, -); +const importMap = { + "imports": { + "$fresh/": new URL("./", import.meta.url).href, + "preact": "https://esm.sh/preact@10.6.6", + "preact/": "https://esm.sh/preact@10.6.6/", + "preact-render-to-string": + "https://esm.sh/preact-render-to-string@5.1.20?deps=preact@10.6.6", + } as Record, +}; +if (useTwind) { + importMap.imports["$twind"] = "https://esm.sh/twind@0.16.17"; + importMap.imports["$twind/"] = "https://esm.sh/twind@0.16.17/"; + importMap.imports["twind"] = "./utils/twind.ts"; +} +const IMPORT_MAP_JSON = JSON.stringify(importMap, null, 2) + "\n"; await Deno.writeTextFile(join(directory, "import_map.json"), IMPORT_MAP_JSON); -const ROUTES_INDEX_TSX = `/** @jsx h */ -import { h } from "preact"; -import Counter from "../islands/Counter.tsx"; +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"; export default function Home() { return ( -
- the fresh logo: a sliced lemon dripping with juice -

+ + the fresh logo: a sliced lemon dripping with juice + Welcome to \`fresh\`. Try update this message in the ./routes/index.tsx file, and refresh.

@@ -81,18 +108,44 @@ await Deno.writeTextFile( ROUTES_INDEX_TSX, ); -const ISLANDS_COUNTER_TSX = `/** @jsx h */ +let ISLANDS_COUNTER_TSX = `/** @jsx h */ import { h } from "preact"; import { useState } from "preact/hooks"; import { IS_BROWSER } from "$fresh/runtime.ts"; - +${useTwind ? 'import { tw } from "twind";\n' : ""} interface CounterProps { start: number; } export default function Counter(props: CounterProps) { const [count, setCount] = useState(props.start); - return ( +`; + +if (useTwind) { + ISLANDS_COUNTER_TSX += + ` const btn = tw\`px-2 py-1 border(gray-100 1) hover:bg-gray-200\`;\n`; + ISLANDS_COUNTER_TSX += ` return ( +
+

{count}

+ + +
+ ); +`; +} else { + ISLANDS_COUNTER_TSX += ` return (

{count}

); -} `; +} +ISLANDS_COUNTER_TSX += `}\n`; await Deno.writeTextFile( join(directory, "islands", "Counter.tsx"), ISLANDS_COUNTER_TSX, @@ -150,6 +204,22 @@ 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); +`; +if (useTwind) { + await Deno.writeTextFile( + join(directory, "utils", "twind.ts"), + UTILS_TWIND_TS, + ); +} + const STATIC_LOGO = ` @@ -163,7 +233,7 @@ await Deno.writeTextFile( STATIC_LOGO, ); -const MAIN_TS = `/// +let MAIN_TS = `/// /// /// /// @@ -171,9 +241,30 @@ const MAIN_TS = `/// import { start } from "$fresh/server.ts"; import manifest from "./fresh.gen.ts"; - -await start(manifest); `; + +if (useTwind) { + MAIN_TS += ` +import { virtualSheet } from "$twind/sheets"; +import { config, setup } from "twind"; + +const sheet = virtualSheet(); +sheet.reset(); +setup({ ...config, sheet }); + +function render(ctx, render) { + 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); +} + +`; +} + +MAIN_TS += `await start(manifest${useTwind ? ", { render }" : ""});\n`; const MAIN_TS_PATH = join(directory, "main.ts"); await Deno.writeTextFile(MAIN_TS_PATH, MAIN_TS); @@ -191,16 +282,13 @@ try { // this throws on windows } -const DENO_CONFIG = JSON.stringify( - { - tasks: { - start: "deno run -A --watch=static/,routes/ dev.ts", - }, - importMap: "./import_map.json", +const config = { + tasks: { + start: "deno run -A --watch=static/,routes/ dev.ts", }, - null, - 2, -); + importMap: "./import_map.json", +}; +const DENO_CONFIG = JSON.stringify(config, null, 2) + "\n"; await Deno.writeTextFile(join(directory, "deno.json"), DENO_CONFIG); diff --git a/src/dev/deps.ts b/src/dev/deps.ts index 6bf93f5f..a0a54c52 100644 --- a/src/dev/deps.ts +++ b/src/dev/deps.ts @@ -9,3 +9,4 @@ export { } from "https://deno.land/std@0.128.0/path/mod.ts"; export { walk } from "https://deno.land/std@0.128.0/fs/walk.ts"; export { bold, red } from "https://deno.land/std@0.128.0/fmt/colors.ts"; +export { parse } from "https://deno.land/std@0.128.0/flags/mod.ts"; diff --git a/tests/cli_test.ts b/tests/cli_test.ts index 23c40c7e..d270c440 100644 --- a/tests/cli_test.ts +++ b/tests/cli_test.ts @@ -46,7 +46,7 @@ Deno.test({ await t.step("execute init command", async () => { const cliProcess = Deno.run({ - cmd: ["deno", "run", "-A", "init.ts", tmpDirName], + cmd: ["deno", "run", "-A", "init.ts", tmpDirName, "--no-twind"], stdout: "null", }); const { code } = await cliProcess.status(); @@ -97,6 +97,7 @@ Deno.test({ }, { "type": "report", "directories": 3, "files": 8 }, ]; + await t.step("check generated files", async () => { await assertFileExistence(targetFileTree); }); @@ -156,3 +157,136 @@ Deno.test({ sanitizeOps: false, sanitizeResources: false, }); + +Deno.test({ + name: "fresh-init --twind", + async fn(t) { + // Preparation + const tmpDirName = await Deno.makeTempDir(); + + await t.step("execute init command", async () => { + const cliProcess = Deno.run({ + cmd: ["deno", "run", "-A", "init.ts", tmpDirName, "--twind"], + stdout: "null", + }); + const { code } = await cliProcess.status(); + cliProcess.close(); + assertEquals(code, 0); + }); + + // NOTE: generated by `tree -J ` + const targetFileTree: FileTree[] = [ + { + "type": "directory", + "name": tmpDirName, + "contents": [ + { "type": "file", "name": "README.md" }, + { "type": "file", "name": "import_map.json" }, + { "type": "file", "name": "fresh.gen.ts" }, + { + "type": "directory", + "name": "islands", + "contents": [ + { "type": "file", "name": "Counter.tsx" }, + ], + }, + { "type": "file", "name": "main.ts" }, + { + "type": "directory", + "name": "routes", + "contents": [ + { "type": "file", "name": "[name].tsx" }, + { + "type": "directory", + "name": "api", + "contents": [ + { "type": "file", "name": "joke.ts" }, + ], + }, + { "type": "file", "name": "index.tsx" }, + ], + }, + { + "type": "directory", + "name": "static", + "contents": [ + { "type": "file", "name": "logo.svg" }, + ], + }, + { + "type": "directory", + "name": "utils", + "contents": [ + { "type": "file", "name": "twind.ts" }, + ], + }, + ], + }, + { "type": "report", "directories": 4, "files": 9 }, + ]; + + await t.step("check generated files", async () => { + await assertFileExistence(targetFileTree); + }); + + await t.step("start up the server and access the root page", async () => { + const serverProcess = Deno.run({ + cmd: ["deno", "run", "-A", "main.ts"], + stdout: "piped", + stderr: "inherit", + cwd: tmpDirName, + }); + + const lines = serverProcess.stdout.readable + .pipeThrough(new TextDecoderStream()) + .pipeThrough(new TextLineStream()); + + let started = false; + for await (const line of lines) { + console.log(line); + if (line.includes("Server listening on http://")) { + started = true; + break; + } + } + if (!started) { + throw new Error("Server didn't start up"); + } + + await delay(100); + + // Access the root page + const res = await fetch("http://localhost:8000"); + await res.body?.cancel(); + assertEquals(res.status, 200); + + // verify the island is revived. + const browser = await puppeteer.launch({ args: ["--no-sandbox"] }); + const page = await browser.newPage(); + await page.goto("http://localhost:8000", { waitUntil: "networkidle2" }); + + const counter = await page.$("body > div > div > p"); + let counterValue = await counter?.evaluate((el) => el.textContent); + assert(counterValue === "3"); + + const fontWeight = await counter?.evaluate((el) => + getComputedStyle(el).fontWeight + ); + assertEquals(fontWeight, "700"); + + const buttonPlus = await page.$("body > div > div > button:nth-child(3)"); + await buttonPlus?.click(); + + counterValue = await counter?.evaluate((el) => el.textContent); + assert(counterValue === "4"); + await page.close(); + await browser.close(); + + await lines.cancel(); + serverProcess.kill("SIGTERM"); + serverProcess.close(); + }); + }, + sanitizeOps: false, + sanitizeResources: false, +});