From 9ee03e09bb3ab577abd809d9817853feb2458572 Mon Sep 17 00:00:00 2001 From: Luca Casonato Date: Tue, 11 Oct 2022 11:15:12 +0200 Subject: [PATCH] fix: twind style generation in islands (#830) Fixes #778 --- plugins/twind.ts | 13 +++++++++---- plugins/twind/main.ts | 19 ++++++++++++++----- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/plugins/twind.ts b/plugins/twind.ts index 4966213e..da11ee8f 100644 --- a/plugins/twind.ts +++ b/plugins/twind.ts @@ -18,11 +18,15 @@ export default function(state) { hydrate(options, state); }`; render(ctx) { sheet.reset(undefined); const res = ctx.render(); - const cssText = [...sheet.target].join("\n"); + const cssTexts = [...sheet.target]; const snapshot = sheet.reset(); const scripts = []; + let cssText: string; if (res.requiresHydration) { - const precedences = snapshot[1]; + const precedences = snapshot[1] as number[]; + cssText = cssTexts.map((cssText, i) => + `${cssText}/*${precedences[i].toString(36)}*/` + ).join("\n"); const mappings: (string | [string, string])[] = []; for ( const [key, value] of (snapshot[3] as Map).entries() @@ -33,8 +37,9 @@ export default function(state) { hydrate(options, state); }`; mappings.push([key, value]); } } - const state = [precedences, mappings]; - scripts.push({ entrypoint: "main", state }); + scripts.push({ entrypoint: "main", state: mappings }); + } else { + cssText = cssTexts.join("\n"); } return { scripts, diff --git a/plugins/twind/main.ts b/plugins/twind/main.ts index cc9b5ff1..8943564f 100644 --- a/plugins/twind/main.ts +++ b/plugins/twind/main.ts @@ -1,17 +1,26 @@ import { Sheet } from "twind"; import { Options, setup, STYLE_ELEMENT_ID } from "./shared.ts"; -type State = [string[], [string, string][]]; +type State = [string, string][]; export default function hydrate(options: Options, state: State) { const el = document.getElementById(STYLE_ELEMENT_ID) as HTMLStyleElement; - const rules = new Set(el.innerText.split("\n")); - const precedences = state[0]; - const mappings = new Map(state[1] - .map((v) => typeof v === "string" ? [v, v] : v)); + const rules = new Set(); + const precedences: number[] = []; + const mappings = new Map( + state.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 ruleText = Array.from(target.cssRules).map((r) => r.cssText); + for (const r of ruleText) { + const m = r.lastIndexOf("/*"); + const precedence = parseInt(r.slice(m + 2, -2), 36); + const rule = r.slice(0, m); + rules.add(rule); + precedences.push(precedence); + } const sheet: Sheet = { target, insert: (rule, index) => target.insertRule(rule, index),