fix: hydrate in twind-v1-plugin (#1050)

This commit is contained in:
y3km21
2023-03-13 01:31:41 +09:00
committed by GitHub
parent 7e72fa236c
commit 7f2ec612b2
15 changed files with 597 additions and 2 deletions
+14 -2
View File
@@ -1,5 +1,17 @@
import { getSheet, setup, TwindConfig } from "https://esm.sh/@twind/core@1.1.3";
import {
cssom,
getSheet,
setup,
TwindConfig,
} from "https://esm.sh/@twind/core@1.1.3";
import { STYLE_ELEMENT_ID } from "./shared.ts";
export default function hydrate(options: TwindConfig) {
setup(options, getSheet());
const elem = document.getElementById(STYLE_ELEMENT_ID) as HTMLStyleElement;
const sheet = cssom(elem);
sheet.resume = getSheet().resume.bind(sheet);
document.querySelector('[data-twind="claimed"]')?.remove();
setup(options, sheet);
}
+10
View File
@@ -0,0 +1,10 @@
{
"tasks": {
"start": "deno run -A --watch=static/,routes/ dev.ts"
},
"importMap": "./import_map.json",
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "preact"
}
}
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env -S deno run -A --watch=static/,routes/
import dev from "$fresh/dev.ts";
await dev(import.meta.url, "./main.ts");
+26
View File
@@ -0,0 +1,26 @@
// DO NOT EDIT. This file is generated by fresh.
// This file SHOULD be checked into source version control.
// This file is automatically updated during development when running `dev.ts`.
import config from "./deno.json" assert { type: "json" };
import * as $0 from "./routes/check-duplication.tsx";
import * as $1 from "./routes/insert-cssrules.tsx";
import * as $2 from "./routes/static.tsx";
import * as $$0 from "./islands/CheckDuplication.tsx";
import * as $$1 from "./islands/InsertCssrules.tsx";
const manifest = {
routes: {
"./routes/check-duplication.tsx": $0,
"./routes/insert-cssrules.tsx": $1,
"./routes/static.tsx": $2,
},
islands: {
"./islands/CheckDuplication.tsx": $$0,
"./islands/InsertCssrules.tsx": $$1,
},
baseUrl: import.meta.url,
config,
};
export default manifest;
@@ -0,0 +1,10 @@
{
"imports": {
"$fresh/": "../../",
"preact": "https://esm.sh/preact@10.11.0",
"preact/": "https://esm.sh/preact@10.11.0/",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@5.2.4",
"@preact/signals": "https://esm.sh/*@preact/signals@1.0.3",
"@preact/signals-core": "https://esm.sh/*@preact/signals-core@1.0.1"
}
}
@@ -0,0 +1,63 @@
// https://github.com/denoland/fresh/pull/1050
import { useEffect, useState } from "preact/hooks";
import { cmpCssRules } from "../utils/utils.ts";
/**
* Returns a cssrulelist of styleElement matching the selector.
*/
function getCssrules(selector: string) {
const elem = document.querySelector(selector) as HTMLStyleElement;
return elem?.sheet?.cssRules;
}
export default function CheckDuplication() {
const [cssRulesFRSHTWIND, setCssRulesFRSHTWIND] = useState<
undefined | CSSRuleList
>(undefined);
const [cssRulesClaimed, setCssRulesClaimed] = useState<
undefined | CSSRuleList
>(undefined);
// Init
useEffect(() => {
// get <style id="__FRSH_TWIND">
setCssRulesFRSHTWIND(getCssrules("#__FRSH_TWIND"));
// get <style data-twind="claimed">
// see https://github.com/tw-in-js/twind/blob/main/packages/core/src/sheets.ts#L5-L16
setCssRulesClaimed(
getCssrules('[data-twind="claimed"]:not(#__FRSH_TWIND)'),
);
});
return (
<div class="p-2">
{/* At least one class is required in the islands for hydrate to work. */}
<h2>Check duplicated cssrules</h2>
{/* Status of duplicates */}
{(() => {
if (cssRulesFRSHTWIND != null && cssRulesClaimed != null) {
return (
<div>
<p>Error :</p>
<p id="numDuplicates">
{`${
cmpCssRules(
cssRulesFRSHTWIND,
cssRulesClaimed,
)
}`}
</p>
<p>cssrules are duplicated</p>
</div>
);
} else if (cssRulesFRSHTWIND != null && cssRulesClaimed == null) {
return <p id="okNoDuplicates">Ok : No duplicates</p>;
} else {
return <p id="errorNoExistsRules">Error : Cssrules does not exist</p>;
}
})()}
</div>
);
}
@@ -0,0 +1,73 @@
// https://github.com/denoland/fresh/pull/1050
import { useEffect, useState } from "preact/hooks";
/**
* Returns a number of cssrules set by twind.
*/
function getNumCssrules(): number | undefined {
const elem = document.getElementById("__FRSH_TWIND") as HTMLStyleElement;
return elem.sheet?.cssRules.length;
}
export default function InsertCssrules() {
const [numDefCssRules, setNumDefCssRules] = useState<number | undefined>(
undefined,
);
const [numCssRules, setNumCssRules] = useState<number | undefined>(undefined);
const [insertedStyles, setInsertedStyles] = useState("");
// Init numDefCssRules
useEffect(() => {
setNumDefCssRules(getNumCssrules());
}, []);
// Init and Update numCssRules
useEffect(() => {
setNumCssRules(getNumCssrules());
}, [insertedStyles]);
return (
<div>
<h2>Insert cssrule in islands</h2>
<div>
<p>Default Number of __FRSH_TWIND CssRules :</p>
<p id="defaultNumCssRules" class={`text-xl`}>
{numDefCssRules ? numDefCssRules : "Error : Cannot get cssrules"}
</p>
</div>
<div>
<p>Current Number of __FRSH_TWIND CssRules :</p>
<p id="currentNumCssRules" class={`text-xl ${insertedStyles}`}>
{numCssRules ? numCssRules : "Error : Cannot get cssrules"}
</p>
</div>
{/* Status of insert css rules */}
{(() => {
if (insertedStyles === "") {
return <p id="waitClickButton">Plese click button</p>;
} else if (numDefCssRules === numCssRules) {
return (
<p id="errorInsertCssrules">
{'Error: A cssrule has been inserted into a style sheet other than <style id="__FRSH_TWIND">'}
</p>
);
} else {
return <p id="okInsertCssRuleSuccess">Success</p>;
}
})()}
<button
id="insertCssRuleButton"
onClick={() => {
setInsertedStyles("text-green-600");
}}
disabled={insertedStyles === "" ? false : true}
>
Add `text-green-600` to Cureent Number Class
</button>
</div>
);
}
+11
View File
@@ -0,0 +1,11 @@
/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="dom.iterable" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />
import { start } from "$fresh/server.ts";
import manifest from "./fresh.gen.ts";
import options from "./options.ts";
await start(manifest, options);
+5
View File
@@ -0,0 +1,5 @@
import { FreshOptions } from "$fresh/server.ts";
import twindPlugin from "../../plugins/twindv1.ts";
import twindConfig from "./twind.config.ts";
export default { plugins: [twindPlugin(twindConfig)] } as FreshOptions;
@@ -0,0 +1,9 @@
import CheckDuplication from "../islands/CheckDuplication.tsx";
export default function Home() {
return (
<div>
<CheckDuplication></CheckDuplication>
</div>
);
}
@@ -0,0 +1,9 @@
import InsertCssrules from "../islands/InsertCssrules.tsx";
export default function Home() {
return (
<div>
<InsertCssrules></InsertCssrules>
</div>
);
}
@@ -0,0 +1,11 @@
import { Head } from "$fresh/runtime.ts";
export default function Home() {
return (
<div>
<h1 id="helloTwind" class="text-xl text-blue-600">
Hello Twind!
</h1>
</div>
);
}
@@ -0,0 +1,9 @@
import { defineConfig } from "https://esm.sh/@twind/core@1.1.3";
import presetTailwind from "https://esm.sh/@twind/preset-tailwind@1.1.4";
export default {
...defineConfig({
presets: [presetTailwind()],
}),
selfURL: import.meta.url,
};
@@ -0,0 +1,26 @@
/**
* Returns the number of string duplicates that compare two string[].
*/
export function cmpStringArray(a: string[], b: string[]) {
const bSet = new Set(b);
const duplicateString = a.filter((value) => {
return bSet.has(value);
});
return duplicateString.length;
}
/**
* Returns the number of csstext duplicates that compare two cssrulelist.
*/
export function cmpCssRules(a: CSSRuleList, b: CSSRuleList) {
const aCssTextArray = Array.from(a).map((elem: CSSRule) => {
return elem.cssText;
});
const bCssTextArray = Array.from(b).map((elem: CSSRule) => {
return elem.cssText;
});
return cmpStringArray(aCssTextArray, bCssTextArray);
}
+316
View File
@@ -0,0 +1,316 @@
import { assert, delay, puppeteer, TextLineStream } from "./deps.ts";
import { cmpStringArray } from "./fixture_twind_hydrate/utils/utils.ts";
/**
* Start the server with the main file.
*
* Returns a page instance and a method to terminate the server.
*/
async function setUpServer(path: string) {
const serverProcessCmd = new Deno.Command("deno", {
args: [
"run",
"-A",
path,
],
stdout: "piped",
stderr: "inherit",
});
const serverProcess = serverProcessCmd.spawn();
const lines = serverProcess.stdout
.pipeThrough(new TextDecoderStream())
.pipeThrough(new TextLineStream());
let started = false;
for await (const line of lines) {
if (line.includes("Listening on http://")) {
started = true;
break;
}
}
if (!started) {
throw new Error("Server didn't start up");
}
await delay(100);
const browser = await puppeteer.launch({ args: ["--no-sandbox"] });
const page = await browser.newPage();
/**
* terminate server
*/
const terminate = async () => {
await browser.close();
serverProcess.kill("SIGKILL");
await serverProcess.status;
// TextDecoder leaks, so close it manually.
const denoResourcesMap = new Map(
Object.entries(Deno.resources()).map(([rid, representation]) => {
return [representation, parseInt(rid)];
}),
);
const textDecoderRid = denoResourcesMap.get("textDecoder");
if (textDecoderRid != null) {
Deno.close(textDecoderRid);
}
};
return { page: page, terminate: terminate };
}
/**
* Main file path
*/
const MAIN_FILE_PATH = "./tests/fixture_twind_hydrate/main.ts";
Deno.test({
name: "twind static test",
async fn(t) {
// Preparation
const server = await setUpServer(MAIN_FILE_PATH);
const page = server.page;
/**
* Compare the class of element of any id with the selectorText of cssrules in stylesheet.
* Ensure that twind compliles the class of element.
*/
async function compiledCssRulesTest(id: string, styleId: string) {
const elemClassList = await page.evaluate((selector) => {
const classList = document.querySelector(selector)?.classList;
if (classList != null) {
return Array.from(classList);
} else {
return [];
}
}, `#${id}`);
assert(elemClassList.length !== 0, `Element of id=${id} has no class`);
const twindCssRules = await page.evaluate((selector) => {
const styleElem = document.querySelector(selector);
if (styleElem == null) {
return [];
}
const cssRules = (styleElem as HTMLStyleElement).sheet?.cssRules;
if (cssRules == null) {
return [];
}
return Array.from(cssRules).map((cssRule) => {
const cssStyleRule = cssRule as CSSStyleRule;
return cssStyleRule.selectorText;
});
}, `#${styleId}`);
const twindCssRulesSet = new Set(twindCssRules);
for (const elemClass of elemClassList) {
assert(
twindCssRulesSet.has("." + elemClass),
`'${elemClass}' is not compiled by twind`,
);
}
}
await page.goto("http://localhost:8000/static", {
waitUntil: "networkidle2",
});
// For avoid leaking async ops.
await delay(10);
await t.step("Twind complies cssrules from dom class in ssr", async () => {
await compiledCssRulesTest("helloTwind", "__FRSH_TWIND");
});
await server.terminate();
},
});
Deno.test({
name: "No duplicate twind cssrules",
async fn(t) {
// Preparation
const server = await setUpServer(MAIN_FILE_PATH);
const page = server.page;
/**
* Ensure that the cssrule of the two style elements specified do not duplicate.
* PR946 fails and PR1050 passes.
*/
async function noDuplicatesTest(
twindStyleElemSelector: string,
twindClaimedStyleElemSelector: string,
) {
const twindCssRuleList = await page.evaluate((selector) => {
const elem = document.querySelector(selector) as HTMLStyleElement;
const cssRules = elem?.sheet?.cssRules;
if (cssRules != null) {
return Array.from(cssRules).map((el) => {
return el.cssText;
});
} else {
return null;
}
}, twindStyleElemSelector);
if (twindCssRuleList == null) {
assert(false, `StyleElement(${twindStyleElemSelector}) is no exists`);
}
const twindClaimedCssRuleList = await page.evaluate((selector) => {
const elem = document.querySelector(selector) as HTMLStyleElement;
const cssRules = elem?.sheet?.cssRules;
if (cssRules != null) {
return Array.from(cssRules).map((el) => {
return el.cssText;
});
} else {
return null;
}
}, twindClaimedStyleElemSelector);
if (twindClaimedCssRuleList == null) {
// There is only one style element by twind.
return;
}
const numDuplicates = cmpStringArray(
twindCssRuleList,
twindClaimedCssRuleList,
);
assert(false, `${numDuplicates} cssrules are duplicated`);
}
await page.goto("http://localhost:8000/check-duplication", {
waitUntil: "networkidle2",
});
// For avoid leaking async ops.
await delay(10);
await t.step("Ensure no dupulicate twind cssrules in islands", async () => {
await noDuplicatesTest(
"#__FRSH_TWIND",
'[data-twind="claimed"]:not(#__FRSH_TWIND)',
);
});
await server.terminate();
},
});
Deno.test({
name: "Dynamically insert cssrules",
async fn(t) {
// Preparation
const server = await setUpServer(MAIN_FILE_PATH);
const page = server.page;
/**
* Ensure that the class dynamically inserted in islands is compiled by twind.
* PR946 fails and PR1050 passes.
*/
async function DynamicallyInsertCssrulesTest(twindStyleId: string) {
const numCssRulesBeforeInsert = await page.$eval(
`#${twindStyleId}`,
(el) => {
const styleElem = el as HTMLStyleElement;
const cssRules = styleElem.sheet?.cssRules;
const numCssRules = cssRules?.length;
return numCssRules != null ? numCssRules : NaN;
},
);
assert(
!isNaN(numCssRulesBeforeInsert),
"StyleElement(#${twindStyleId}) is no exists",
);
const classBeforeInsert = await page.$eval(
"#currentNumCssRules",
(el) => {
return Array.from(el.classList) as string[];
},
);
// After click, `text-green-600` is inserted to the class of the element in #currentNumCssRules.
await page.$eval("#insertCssRuleButton", (el) => {
return el.click();
});
const [numCssRulesAfterInsert, twindCssRulesAfterInsert] = await page
.$eval(`#${twindStyleId}`, (el) => {
const styleElem = el as HTMLStyleElement;
const cssRules = styleElem.sheet?.cssRules;
const numCssRules = cssRules?.length;
const cssRulesSelectorTextArray = cssRules != null
? Array.from(cssRules).map((el) => {
return (el as CSSStyleRule).selectorText;
})
: null;
return [
numCssRules != null ? numCssRules : NaN,
cssRulesSelectorTextArray,
] as [number, string[] | null];
});
assert(
!isNaN(numCssRulesAfterInsert),
`StyleElement(#${twindStyleId}) is no exists`,
);
const classAfterInsert = await page.$eval("#currentNumCssRules", (el) => {
return Array.from(el.classList) as string[];
});
const classBeforeInsertSet = new Set(classBeforeInsert);
const dynInsertedClassArray = classAfterInsert.filter((c) => {
return !classBeforeInsertSet.has(c);
});
// Check if the added class is compiled by twind.
const twindCssRulesAfterInsertSet = new Set(twindCssRulesAfterInsert);
for (const insertedClass of dynInsertedClassArray) {
assert(
twindCssRulesAfterInsertSet.has(`.${insertedClass}`),
`'${insertedClass} has been inserted into a style sheet other than <style id="${twindStyleId}">'`,
);
}
// If twind in csr monitors <style id="${twindStyleId}"> ,
// the class(not compiled) just inserted will be compiled
// and the cssrule will increase.
assert(
numCssRulesBeforeInsert !== numCssRulesAfterInsert,
`Cssrule has been inserted into a style sheet other than <style id="${twindStyleId}"> or it was compiled at the time of SSR.`,
);
}
await page.goto("http://localhost:8000/insert-cssrules", {
waitUntil: "networkidle2",
});
// For avoid leaking async ops.
await delay(10);
await t.step(
"Ensure that the class dynamically inserted in islands is compiled",
async () => {
await DynamicallyInsertCssrulesTest("__FRSH_TWIND");
},
);
await server.terminate();
},
});