(el: Element, shadowDOMTarget?: ShadowRoot)
| 24 | * @param shadowDOMTarget - The shadow root to add the styles to. |
| 25 | */ |
| 26 | export function attachStyles(el: Element, shadowDOMTarget?: ShadowRoot) { |
| 27 | const root = el.getRootNode() |
| 28 | const container: Document | ShadowRoot = |
| 29 | shadowDOMTarget ?? |
| 30 | // A shadow root is a document fragment with a host. `instanceof ShadowRoot` |
| 31 | // would miss shadow roots from other windows, e.g. picture-in-picture. |
| 32 | (root.nodeType === 11 && 'host' in root |
| 33 | ? (root as ShadowRoot) |
| 34 | : el.ownerDocument) |
| 35 | // Not supported before Safari 16.4 and Firefox 101, nor in jsdom. |
| 36 | if (!('adoptedStyleSheets' in (container as object))) return |
| 37 | |
| 38 | const doc = container.ownerDocument ?? container |
| 39 | let sheet = sheets.get(doc) |
| 40 | if (!sheet) { |
| 41 | sheet = new (doc.defaultView ?? window).CSSStyleSheet() |
| 42 | sheet.replaceSync(cssText) |
| 43 | sheets.set(doc, sheet) |
| 44 | } |
| 45 | |
| 46 | if (!container.adoptedStyleSheets.includes(sheet)) { |
| 47 | container.adoptedStyleSheets = [...container.adoptedStyleSheets, sheet] |
| 48 | } |
| 49 | } |
no test coverage detected