Skip to content

Commit

Permalink
preserve twind CSS after HMR
Browse files Browse the repository at this point in the history
  • Loading branch information
JLarky committed Aug 11, 2022
1 parent 47d621e commit 8bab179
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 8 deletions.
6 changes: 3 additions & 3 deletions packages/fogbender/src/floatingWidget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import { Token } from ".";

import { render } from "solid-js/web";
import { createSignal } from "solid-js";
import { tw, setup } from "twind";
import { tw } from "twind";
import { Events } from "./createIframe";
import { getSheet } from "./twind";
import { getTwind } from "./twind";

export function createFloatingWidget({ events }: { events: Events }, url: string, token: Token) {
const container = document.createElement("div");
Expand All @@ -31,7 +31,7 @@ export function createFloatingWidget({ events }: { events: Events }, url: string
const body = document.getElementsByTagName("body")[0];
container.attachShadow({ mode: "open" });
container.shadowRoot?.appendChild(button);
const { attach } = getSheet();
const { attach } = getTwind();
attach(container.shadowRoot);
body.appendChild(container);
render(() => {
Expand Down
32 changes: 27 additions & 5 deletions packages/fogbender/src/twind.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,11 @@ const createSheet = () => {
}
};

let signletonHolder: ReturnType<typeof createSheet> | undefined;
const createTwind = () => {
const sheet = createSheet();

export function getSheet() {
const { sheet } = signletonHolder || (signletonHolder = createSheet());
setup({
sheet,
sheet: sheet.sheet,
theme: {
extend: {
colors: {
Expand All @@ -44,5 +43,28 @@ export function getSheet() {
},
},
});
return signletonHolder;
return sheet;
};

let singletonHolder: ReturnType<typeof createTwind> | undefined;

export function getTwind() {
return singletonHolder || (singletonHolder = createTwind());
}

declare global {
// eslint-disable-next-line no-unused-vars
interface NodeModule {
hot?: {
data: { singletonHolder?: typeof singletonHolder };
dispose: (callback: (data: { singletonHolder?: typeof singletonHolder }) => void) => void;
};
}
}

if (module.hot) {
singletonHolder = module.hot?.data?.singletonHolder || singletonHolder;
module.hot.dispose(data => {
data.singletonHolder = singletonHolder;
});
}

0 comments on commit 8bab179

Please sign in to comment.