Skip to content

Instantly share code, notes, and snippets.

@intrnl
Last active September 12, 2023 08:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save intrnl/a3acf78af06d7efbb02388ba9fb7e4bc to your computer and use it in GitHub Desktop.
Save intrnl/a3acf78af06d7efbb02388ba9fb7e4bc to your computer and use it in GitHub Desktop.
let uid = 0;
let inserted = false;
const stylesheet = /*#__PURE__*/ new CSSStyleSheet();
const build = (bake: (name: string, body: string) => string) => {
if (import.meta.env.DEV) {
const seen = new WeakSet<TemplateStringsArray>();
const cache = new Map<number, string>();
return (strings: TemplateStringsArray, ...values: any[]): string => {
const body = String.raw({ raw: strings }, ...values);
const hash = cyrb53a(body);
let name = cache.get(hash);
console.assert(!seen.has(strings), `we've already seen this CSS before!`);
seen.add(strings);
if (!name) {
cache.set(hash, (name = `v` + uid++));
if (!inserted) {
document.adoptedStyleSheets.push(stylesheet);
inserted = true;
}
stylesheet.insertRule(bake(name, body));
}
return name;
};
}
return (strings: TemplateStringsArray, ...values: any[]): string => {
const body = String.raw({ raw: strings }, ...values);
const name = `v` + uid++;
if (!inserted) {
document.adoptedStyleSheets.push(stylesheet);
inserted = true;
}
stylesheet.insertRule(bake(name, body));
return name;
};
};
export const globalStyle = build((_name, body) => body);
export const css = build((name, body) => `.${name}{${body}}`);
export const keyframes = build((name, body) => `@keyframes ${name}{${body}}`);
export const variable = () => {
return `--v-${uid++}`;
};
/**
* https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
*/
const cyrb53a = (str: string, seed = 0) => {
let h1 = 0xdeadbeef ^ seed;
let h2 = 0x41c6ce57 ^ seed;
for (let i = 0, ch; i < str.length; i++) {
ch = str.charCodeAt(i);
h1 = Math.imul(h1 ^ ch, 0x85ebca77);
h2 = Math.imul(h2 ^ ch, 0xc2b2ae3d);
}
h1 ^= Math.imul(h1 ^ (h2 >>> 15), 0x735a2d97);
h2 ^= Math.imul(h2 ^ (h1 >>> 15), 0xcaf649a9);
h1 ^= h2 >>> 16;
h2 ^= h1 >>> 16;
return 2097152 * (h2 >>> 0) + (h1 >>> 11);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment