|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright 2026 Google LLC |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +import {type CSSResult, type CSSResultOrNative} from 'lit'; |
| 8 | + |
| 9 | +/** |
| 10 | + * Owner types that can adopt stylesheets using `adoptStyles()`. |
| 11 | + */ |
| 12 | +export type AdoptStylesOwner = DocumentOrShadowRoot | Element; |
| 13 | + |
| 14 | +/** |
| 15 | + * Adopts the given stylesheets to the provided document or shadow root owner. |
| 16 | + * |
| 17 | + * @example |
| 18 | + * ```ts |
| 19 | + * import globalStylesheet from './stylesheet.css' with {type: 'css'}; |
| 20 | + * |
| 21 | + * adoptStyles(document, globalStylesheet); |
| 22 | + * ``` |
| 23 | + * |
| 24 | + * If an element is provided, the styles are adopted to the element's owner |
| 25 | + * document. If the element is within a shadow root, the styles are also adopted |
| 26 | + * to the host shadow root. |
| 27 | + * |
| 28 | + * @example |
| 29 | + * ```ts |
| 30 | + * import hostClasses from './stylesheet.css' with {type: 'css'}; |
| 31 | + * |
| 32 | + * class LightDomElement extends HTMLElement { |
| 33 | + * connectedCallback() { |
| 34 | + * adoptStyles(this, hostClasses); |
| 35 | + * this.classList.add('host-class'); |
| 36 | + * } |
| 37 | + * } |
| 38 | + * ``` |
| 39 | + * |
| 40 | + * @param owner The owner document, shadow root, or element to adopt the |
| 41 | + * styles to. |
| 42 | + * @param styles The styles to adopt. |
| 43 | + */ |
| 44 | +export function adoptStyles( |
| 45 | + owner: AdoptStylesOwner | null | undefined, |
| 46 | + styles: CSSResultOrNative | CSSResultOrNative[], |
| 47 | +): void { |
| 48 | + if (!owner) return; |
| 49 | + |
| 50 | + styles = Array.isArray(styles) ? styles : [styles]; |
| 51 | + const isCSSResult = (style: CSSResultOrNative): style is CSSResult => |
| 52 | + 'styleSheet' in style; |
| 53 | + const stylesheets: CSSStyleSheet[] = styles.map((cssResultOrNative) => |
| 54 | + isCSSResult(cssResultOrNative) |
| 55 | + ? cssResultOrNative.styleSheet! |
| 56 | + : cssResultOrNative, |
| 57 | + ); |
| 58 | + |
| 59 | + const adopt = ( |
| 60 | + node: DocumentOrShadowRoot | Node | null, |
| 61 | + stylesheets: CSSStyleSheet[], |
| 62 | + ): node is DocumentOrShadowRoot => { |
| 63 | + if (node && 'adoptedStyleSheets' in node) { |
| 64 | + node.adoptedStyleSheets = Array.from( |
| 65 | + new Set([...node.adoptedStyleSheets, ...stylesheets]), |
| 66 | + ); |
| 67 | + return true; |
| 68 | + } |
| 69 | + return false; |
| 70 | + }; |
| 71 | + |
| 72 | + if (adopt(owner, stylesheets)) { |
| 73 | + // Styles adopted directly on the owner document or shadow root. |
| 74 | + return; |
| 75 | + } |
| 76 | + |
| 77 | + // When provided an element, adopt styles to the element's document and host |
| 78 | + // shadow root, if present. |
| 79 | + adopt(owner.ownerDocument, stylesheets); |
| 80 | + adopt(owner.getRootNode(), stylesheets); |
| 81 | +} |
0 commit comments