generated from adamrybinski/haunted-snow
-
Notifications
You must be signed in to change notification settings - Fork 1
/
useCSS.js
44 lines (42 loc) · 1.69 KB
/
useCSS.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// from https://github.com/whoisryosuke/spooky-ui/blob/master/packages/hooks/src/useConstructableStylesheets.js
import { useLayoutEffect, supportsAdoptingStyleSheets } from "./deps.js";
export function useCSS(el, styles) {
/**
* Applies styling to the element shadowRoot using the [[`styles`]]
* property. Styling will apply using `shadowRoot.adoptedStyleSheets` where
* available and will fallback otherwise. When Shadow DOM is polyfilled,
* ShadyCSS scopes styles and adds them to the document. When Shadow DOM
* is available but `adoptedStyleSheets` is not, styles are appended to the
* end of the `shadowRoot` to [mimic spec
* behavior](https://wicg.github.io/construct-stylesheets/#using-constructed-stylesheets).
*/
const adoptStyles = (el) => {
if (styles.length === 0) {
return;
}
// There are three separate cases here based on Shadow DOM support.
// (1) shadowRoot polyfilled: use ShadyCSS
// (2) shadowRoot.adoptedStyleSheets available: use it
// (3) shadowRoot.adoptedStyleSheets polyfilled: append styles after
// rendering
if (window.ShadyCSS !== undefined && !window.ShadyCSS.nativeShadow) {
window.ShadyCSS.ScopingShim.prepareAdoptedCssText(
styles.map((s) => s.cssText),
el.localName
);
} else if (supportsAdoptingStyleSheets) {
el.shadowRoot.adoptedStyleSheets = styles.map((s) =>
s instanceof CSSStyleSheet ? s : s.styleSheet
);
} else {
styles.forEach((s) => {
const style = document.createElement("style");
style.textContent = s.cssText;
el.shadowRoot.appendChild(style);
});
}
};
useLayoutEffect(() => {
adoptStyles(el);
}, [styles]);
}