Skip to content

Commit 8ff3048

Browse files
authored
feat(runtime): make shadow root adopt scoped component styles (#6028)
1 parent f4b48e9 commit 8ff3048

1 file changed

Lines changed: 27 additions & 14 deletions

File tree

src/runtime/styles.ts

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -107,21 +107,34 @@ export const addStyle = (styleContainerNode: any, cmpMeta: d.ComponentRuntimeMet
107107
: styleContainerNode.querySelector('style');
108108
(styleContainerNode as HTMLElement).insertBefore(styleElm, referenceNode);
109109
} else if ('host' in styleContainerNode) {
110-
/**
111-
* If a scoped component is used within a shadow root, we want to insert the styles
112-
* at the beginning of the shadow root node.
113-
*
114-
* However if there is already a style node in the ShadowRoot, we just append
115-
* the styles to the existing node.
116-
*
117-
* Note: order of how styles are applied is important. The new style node
118-
* should be inserted before the existing style node.
119-
*/
120-
const existingStyleContainer = styleContainerNode.querySelector('style');
121-
if (existingStyleContainer) {
122-
existingStyleContainer.innerHTML = style + existingStyleContainer.innerHTML;
110+
if (supportsConstructableStylesheets) {
111+
/**
112+
* If a scoped component is used within a shadow root then turn the styles into a
113+
* constructable stylesheet and add it to the shadow root's adopted stylesheets.
114+
*
115+
* Note: order of how styles are adopted is important. The new stylesheet should be
116+
* adopted before the existing styles.
117+
*/
118+
const stylesheet = new CSSStyleSheet();
119+
stylesheet.replaceSync(style);
120+
styleContainerNode.adoptedStyleSheets = [stylesheet, ...styleContainerNode.adoptedStyleSheets];
123121
} else {
124-
(styleContainerNode as HTMLElement).prepend(styleElm);
122+
/**
123+
* If a scoped component is used within a shadow root and constructable stylesheets are
124+
* not supported, we want to insert the styles at the beginning of the shadow root node.
125+
*
126+
* However, if there is already a style node in the shadow root, we just append
127+
* the styles to the existing node.
128+
*
129+
* Note: order of how styles are applied is important. The new style node
130+
* should be inserted before the existing style node.
131+
*/
132+
const existingStyleContainer = styleContainerNode.querySelector('style');
133+
if (existingStyleContainer) {
134+
existingStyleContainer.innerHTML = style + existingStyleContainer.innerHTML;
135+
} else {
136+
(styleContainerNode as HTMLElement).prepend(styleElm);
137+
}
125138
}
126139
} else {
127140
styleContainerNode.append(styleElm);

0 commit comments

Comments
 (0)