core/registries/style.registry.ts
core/registries/style.registry.ts is a file in Bane's Lab Site. 56 lines of code and 22 definitions.
import { createElement } from "#core/factories/element.factory";
import { isStaticRender } from "#core/predicates/document.predicate";
const NONCE_SELECTOR = "meta[property='csp-nonce']";
const STYLE_TAG = "style";
const TOKEN_PREFIX = "styled-";
const TOKEN_SELECTOR = ".";
const EMPTY_BLOCK = " {}";
const declarations = new WeakMap<Element, CSSStyleDeclaration>();
let sheet: CSSStyleSheet | null = null;
let opened = false;
let issued = 0;
const nonceOf = function nonceOf(): string {
const meta = document.querySelector(NONCE_SELECTOR);
return meta instanceof HTMLMetaElement ? meta.nonce : "";
};
const openSheet = function openSheet(): CSSStyleSheet | null {
if (opened) {
return sheet;
}
opened = true;
if (isStaticRender()) {
return null;
}
const holder = createElement(STYLE_TAG);
holder.nonce = nonceOf();
document.head.append(holder);
const { sheet: made } = holder;
sheet = made;
return sheet;
};
const declarationOf = function declarationOf(element: Element): CSSStyleDeclaration | null {
const held = declarations.get(element);
if (held !== undefined) {
return held;
}
const open = openSheet();
if (open === null) {
return null;
}
issued += 1;
const token = TOKEN_PREFIX + String(issued);
const at = open.insertRule(TOKEN_SELECTOR + token + EMPTY_BLOCK, open.cssRules.length);
const rule = open.cssRules[at];
if (!(rule instanceof CSSStyleRule)) {
return null;
}
element.classList.add(token);
declarations.set(element, rule.style);
return rule.style;
};
export const declareStyle = function declareStyle(element: Element, property: string, value: string): void {
declarationOf(element)?.setProperty(property, value);
};
export const declaredStyle = function declaredStyle(element: Element, property: string): string {
return declarations.get(element)?.getPropertyValue(property) ?? "";
};