@@ -23,7 +23,7 @@ export function createComponent(
23
23
"<template> is required"
24
24
) ;
25
25
26
- const styles = definedElement . querySelectorAll ( "style" ) ;
26
+ const styles = [ ... definedElement . querySelectorAll ( "style" ) , ... globalStyles ] ;
27
27
const scripts = definedElement . querySelectorAll ( "script" ) ;
28
28
29
29
const usedAttributes = getUsedAttributes ( template , [ "data-attr" , "data-if" ] ) ;
@@ -38,6 +38,12 @@ export function createComponent(
38
38
39
39
readonly #cleanupFns = new Set < CleanupFn > ( ) ;
40
40
41
+ readonly #styleGroup = document . createElement ( "style" ) ;
42
+
43
+ get shadowRoot ( ) : ShadowRoot {
44
+ return returnIfDefined ( super . shadowRoot ) ;
45
+ }
46
+
41
47
constructor ( ) {
42
48
super ( ) ;
43
49
const content = cloneNode ( template . content ) ;
@@ -78,9 +84,12 @@ export function createComponent(
78
84
}
79
85
80
86
#attach( content : DocumentFragment ) : void {
81
- const shadowRoot = this . attachShadow ( { mode : "open" } ) ;
82
- shadowRoot . appendChild ( content ) ;
83
- this . #setShadowStyles( shadowRoot ) ;
87
+ this . attachShadow ( { mode : "open" } ) ;
88
+ this . shadowRoot . appendChild ( content ) ;
89
+
90
+ for ( const style of styles ) {
91
+ this . appendStyle ( style ) ;
92
+ }
84
93
}
85
94
86
95
#applyAttr( name : string , value : string | null ) : void {
@@ -107,16 +116,6 @@ export function createComponent(
107
116
}
108
117
}
109
118
110
- #setShadowStyles( shadowRoot : ShadowRoot ) {
111
- const group = document . createElement ( "style" ) ;
112
- group . setAttribute ( "data-define-html" , "" ) ;
113
- for ( const style of styles ) {
114
- group . append ( cloneNode ( style ) ) ;
115
- }
116
- group . append ( ...globalStyles . map ( ( el ) => cloneNode ( el ) ) ) ;
117
- shadowRoot . append ( group ) ;
118
- }
119
-
120
119
#execScripts( ) : void {
121
120
for ( const script of scripts ) {
122
121
executeScript ( script , href , this )
@@ -153,12 +152,19 @@ export function createComponent(
153
152
}
154
153
}
155
154
155
+ appendStyle ( style : HTMLLinkElement | HTMLStyleElement ) {
156
+ if ( this . #styleGroup. childElementCount === 0 ) {
157
+ this . shadowRoot . append ( this . #styleGroup) ;
158
+ }
159
+ this . #styleGroup. append ( cloneNode ( style ) ) ;
160
+ }
161
+
156
162
querySelector ( selector : string ) : Element | null {
157
- return returnIfDefined ( this . shadowRoot ) . querySelector ( selector ) ;
163
+ return this . shadowRoot . querySelector ( selector ) ;
158
164
}
159
165
160
166
querySelectorAll ( selector : string ) : NodeListOf < Element > {
161
- return returnIfDefined ( this . shadowRoot ) . querySelectorAll ( selector ) ;
167
+ return this . shadowRoot . querySelectorAll ( selector ) ;
162
168
}
163
169
}
164
170
0 commit comments