UNPKG

@stratakit/foundations

Version:
42 lines (41 loc) 1.51 kB
import { getOwnerDocument, getWindow, isBrowser } from "./~utils.js"; const styleSheets = new Map( Object.entries({ default: /* @__PURE__ */ new WeakMap() }) ); function loadStyles(rootNode, { css, key = "default" }) { let cleanup = () => { }; const loaded = (() => { if (!isBrowser) return false; const ownerDocument = getOwnerDocument(rootNode); const _window = getWindow(rootNode); if (!ownerDocument || !_window) return false; if (!supportsAdoptedStylesheets && !rootNode.querySelector(`style[data-kiwi="${key}"]`)) { const styleElement = ownerDocument.createElement("style"); styleElement.dataset.kiwi = key; styleElement.textContent = css; (rootNode.head || rootNode).appendChild(styleElement); cleanup = () => styleElement.remove(); return true; } const styleSheet = styleSheets.get(key)?.get(_window) || new _window.CSSStyleSheet(); if (!styleSheets.get(key)?.has(_window)) { styleSheets.get(key)?.set(_window, styleSheet); } styleSheet.replaceSync(css); if (!rootNode.adoptedStyleSheets.includes(styleSheet)) { rootNode.adoptedStyleSheets.push(styleSheet); cleanup = () => { rootNode.adoptedStyleSheets = rootNode.adoptedStyleSheets.filter( (sheet) => sheet !== styleSheet ); }; } return true; })(); return { loaded, cleanup }; } const supportsAdoptedStylesheets = isBrowser && "adoptedStyleSheets" in Document.prototype; export { loadStyles };