UNPKG

@stratakit/foundations

Version:

Foundational pieces of StrataKit

53 lines (52 loc) 1.75 kB
import { getOwnerDocument, getWindow, isBrowser } from "./~utils.js"; const styleSheets = new Map(Object.entries({ default: /* @__PURE__ */ new WeakMap() })); const styleSheetRefs = new Map(Object.entries({ default: /* @__PURE__ */ new WeakMap() })); function loadStyles(rootNode, { css, key = "default" }) { let cleanup = () => { }; const loaded = (() => { if (!isBrowser) return false; if (!supportsAdoptedStylesheets) return false; const ownerDocument = getOwnerDocument(rootNode); const _window = getWindow(rootNode); if (!ownerDocument || !_window) return false; const styleSheet = styleSheets.get(key)?.get(_window) || new _window.CSSStyleSheet(); if (!styleSheets.has(key)) styleSheets.set(key, /* @__PURE__ */ new WeakMap()); if (!styleSheets.get(key)?.has(_window)) { styleSheets.get(key)?.set(_window, styleSheet); styleSheet.replaceSync(css); } const refs = styleSheetRefs.get(key) || /* @__PURE__ */ new WeakMap(); if (!styleSheetRefs.has(key)) styleSheetRefs.set(key, refs); const currentCount = refs.get(rootNode) || 0; refs.set(rootNode, currentCount + 1); if (!rootNode.adoptedStyleSheets.includes(styleSheet)) { rootNode.adoptedStyleSheets.push(styleSheet); } cleanup = () => { const count = refs.get(rootNode) || 0; if (count <= 1) { refs.delete(rootNode); rootNode.adoptedStyleSheets = rootNode.adoptedStyleSheets.filter((sheet) => sheet !== styleSheet); } else { refs.set(rootNode, count - 1); } }; return true; })(); return { loaded, cleanup }; } const supportsAdoptedStylesheets = isBrowser && "adoptedStyleSheets" in Document.prototype; export { loadStyles };