1# ShadyCSS 2 3ShadyCSS provides a library to simulate ShadowDOM style encapsulation (ScopingShim), a shim for the proposed CSS mixin `@apply` syntax (ApplyShim), and a library to integrate document-level stylesheets with both of the former libraries (CustomStyleInterface). 4 5## Requirements 6ShadyCSS requires support for the `<template>` element, ShadowDOM, MutationObserver, Promise, and Object.assign 7 8## Loading 9 10ShadyCSS can be used by loading the ScopingShim, ApplyShim, CustomStyleInterface, or any combination of those. 11 12The most-supported loading order is: 131. ScopingShim 141. ApplyShim 151. CustomStyleInterface 16 17All libraries will expose an object on `window` named `ShadyCSS` with the following interface: 18 19```js 20ShadyCSS = { 21 prepareTemplate(templateElement, elementName, elementExtension){}, 22 styleElement(element){}, 23 styleSubtree(element, overrideProperties){}, 24 styleDocument(overrideProperties){}, 25 getComputedStyleValue(element, propertyName){ 26 return // style value for property name on element 27 }, 28 nativeCss: Boolean, 29 nativeShadow: Boolean 30} 31``` 32 33## About ScopingShim 34 35ScopingShim provides simulated ShadyDOM style encapsulation, and a shim for CSS Custom Properties. 36 37ScopingShim works by rewriting style contents and transforming selectors to enforce scoping. 38Additionally, if CSS Custom Properties is not detected, ScopingShim will replace CSS Custom Property usage with realized values. 39 40### Example: 41Here's an example of a custom element when Scoping Shim is not needed. 42 43```html 44<my-element> 45 <!-- shadow-root --> 46 <style> 47 :host { 48 display: block; 49 } 50 #container slot::slotted(*) { 51 color: gray; 52 } 53 #foo { 54 color: black; 55 } 56 </style> 57 <div id="foo">Shadow</div> 58 <div id="container"> 59 <slot> 60 <!-- span distributed here --> 61 </slot> 62 </div> 63 <!-- /shadow-root --> 64 <span>Light</span> 65</my-element> 66``` 67 68becomes: 69 70```html 71<style scope="my-element"> 72my-element { 73 display: block; 74} 75#container.my-element > * { 76 color: gray; 77} 78#foo.my-element { 79 color: black; 80} 81</style> 82<my-element> 83<div id="foo">Shadow</div> 84<div id="container"> 85 <span>Light</span> 86</div> 87</my-element> 88``` 89 90## About ApplyShim 91 92ApplyShim provides a shim for the `@apply` syntax proposed at https://tabatkins.github.io/specs/css-apply-rule/, which expands the definition CSS Custom Properties to include objects that can be applied as a block. 93 94This is done by transforming the block definition into a set of CSS Custom Properties, and replacing uses of `@apply` with consumption of those custom properties. 95 96### Status: 97 98The `@apply` proposal has been abandoned in favor of the ::part/::theme [Shadow Parts spec](https://tabatkins.github.io/specs/css-shadow-parts/). Therefore, the ApplyShim library is deprecated and provided only for backwards compatibility. Support going forward will be limited to critical bug fixes. 99 100### Known Issues: 101 102* Mixin properties cannot be modified at runtime. 103* Nested mixins are not supported. 104* Shorthand properties are not expanded and may conflict with more explicit properties. Whenever shorthand notations are used in conjunction with their expanded forms in `@apply`, depending in the order of usage of the mixins, properties can be overridden. This means that using both `background-color: green;` and `background: red;` in two separate CSS selectors 105 can result in `background-color: transparent` in the selector that `background: red;` is specified. 106 107 ```css 108 #nonexistent { 109 --my-mixin: { 110 background: red; 111 } 112 } 113 ``` 114 with an element style definition of 115 ```css 116 :host { 117 display: block; 118 background-color: green; 119 @apply(--my-mixin); 120 } 121 ``` 122 results in the background being `transparent`, as an empty `background` definition replaces 123 the `@apply` definition. 124 125 For this reason, we recommend avoiding shorthand properties. 126 127### Example: 128 129Here we define a block called `--mixin` at the document level, and apply that block to `my-element` somewhere in the page. 130 131```css 132html { 133 --mixin: { 134 border: 2px solid black; 135 background-color: green; 136 } 137} 138 139my-element { 140 border: 1px dotted orange; 141 @apply --mixin; 142} 143``` 144 145becomes: 146 147```css 148html { 149 --mixin_-_border: 2px solid black; 150 --mixin_-_background-color: green; 151} 152 153my-element { 154 border: var(--mixin_-_border, 1px dotted orange); 155 background-color: var(--mixin_-_background-color); 156} 157``` 158 159## About CustomStyleInterface 160 161CustomStyleInterface provides API to process `<style>` elements that are not inside of 162ShadowRoots, and simulate upper-boundary style scoping for ShadyDOM. 163 164To add document-level styles to ShadyCSS, one can call `CustomStyleInterface.addCustomStyle(styleElement)` or `CustomStyleInterface.addCustomStyle({getStyle: () => styleElement})` 165 166An example usage of the document-level styling api can be found in `examples/document-style-lib.js`, and another example that uses a custom element wrapper can be found in `examples/custom-style-element.js` 167 168### Example: 169 170```html 171<style class="document-style"> 172html { 173 --content-color: brown; 174} 175</style> 176<my-element>This text will be brown!</my-element> 177<script> 178CustomStyleInterface.addCustomStyle(document.querySelector('style.document-style')); 179</script> 180``` 181 182Another example with a wrapper `<custom-style>` element 183 184```html 185<custom-style> 186 <style> 187 html { 188 --content-color: brown; 189 } 190 </style> 191</custom-style> 192<script> 193class CustomStyle extends HTMLElement { 194 constructor() { 195 CustomStyleInterface.addCustomStyle(this); 196 } 197 getStyle() { 198 return this.querySelector('style'); 199 } 200} 201</script> 202<my-element>This this text will be brown!</my-element> 203``` 204 205Another example with a function that produces style elements 206 207```html 208<my-element>This this text will be brown!</my-element> 209<script> 210CustomStyleInterface.addCustomStyle({ 211 getStyle() { 212 const s = document.createElement('style'); 213 s.textContent = 'html{ --content-color: brown }'; 214 return s; 215 } 216}); 217</script> 218``` 219 220## Usage 221 222To use ShadyCSS: 223 2241. First, call `ShadyCSS.prepareTemplate(template, name)` on a 225`<template>` element that will be imported into a `shadowRoot`. 226 2272. When the element instance is connected, call `ShadyCSS.styleElement(element)` 228 2293. Create and stamp the element's shadowRoot 230 2314. Whenever dynamic updates are required, call `ShadyCSS.styleSubtree(element)`. 232 2335. If a styling change is made that may affect the whole document, call 234`ShadyCSS.styleDocument()`. 235 236The following example uses ShadyCSS and ShadyDOM to define a custom element. 237 238```html 239<template id="myElementTemplate"> 240 <style> 241 :host { 242 display: block; 243 padding: 8px; 244 } 245 246 #content { 247 background-color: var(--content-color); 248 } 249 250 .slot-container ::slotted(*) { 251 border: 1px solid steelblue; 252 margin: 4px; 253 } 254 </style> 255 <div id="content">Content</div> 256 <div class="slot-container"> 257 <slot></slot> 258 </div> 259</template> 260<script> 261 // Use polyfill only in browsers that lack native Shadow DOM. 262 window.ShadyCSS && ShadyCSS.prepareTemplate(myElementTemplate, 'my-element'); 263 264 class MyElement extends HTMLElement { 265 connectedCallback() { 266 window.ShadyCSS && ShadyCSS.styleElement(this); 267 if (!this.shadowRoot) { 268 this.attachShadow({mode: 'open'}); 269 this.shadowRoot.appendChild( 270 document.importNode(myElementTemplate.content, true)); 271 } 272 } 273 } 274 275 customElements.define('my-element', MyElement); 276</script> 277``` 278 279## Type Extension elements 280 281ShadyCSS can also be used with type extension elements by supplying the base 282element name to `prepareTemplate` as a third argument. 283 284### Example 285 286```html 287<template id="myElementTemplate"> 288 <style> 289 :host { 290 display: block; 291 padding: 8px; 292 } 293 294 #content { 295 background-color: var(--content-color); 296 } 297 298 .slot-container ::slotted(*) { 299 border: 1px solid steelblue; 300 margin: 4px; 301 } 302 </style> 303 <div id="content">Content</div> 304 <div class="slot-container"> 305 <slot></slot> 306 </div> 307</template> 308<script> 309 window.ShadyCSS && ShadyCSS.prepareTemplate(myElementTemplate, 'my-element', 'div'); 310 311 class MyElement extends HTMLDivElement { 312 connectedCallback() { 313 window.ShadyCSS && ShadyCSS.styleElement(this); 314 if (!this.shadowRoot) { 315 this.attachShadow({mode: 'open'}); 316 this.shadowRoot.appendChild( 317 document.importNode(myElementTemplate.content, true)); 318 } 319 } 320 } 321 322 customElements.define('my-element', MyElement, {extends: 'div'}); 323</script> 324``` 325 326## Imperative values for Custom properties 327 328To set the value of a CSS Custom Property imperatively, `ShadyCSS.styleSubtree` 329and `ShadyCSS.styleDocument` support an additional argument of an object mapping 330variable name to value. 331 332When using ApplyShim, defining new mixins or new values for current mixins imperatively is not 333supported. 334 335### Example 336```html 337<my-element id="a">Text</my-element> 338<my-element>Text</my-element> 339<script> 340let el = document.querySelector('my-element#a'); 341// Set the color of all my-element instances to 'green' 342ShadyCSS.styleDocument({'--content-color' : 'green'}); 343// Set the color my-element#a's text to 'red' 344ShadyCSS.styleSubtree(el, {'--content-color' : 'red'}); 345</script> 346``` 347 348## Limitations 349 350### Selector scoping 351 352To use the `::slotted` pseudo-element, you must select it as a descendant of some context element. 353```css 354/* Bad */ 355::slotted() {} 356 357/* Good */ 358.context ::slotted() {} 359``` 360 361Since ShadyCSS removes all `<slot>` elements, you cannot select them directly or use any other selectors along with the `::slotted` pseudo-element selector. 362```html 363<!-- Bad --> 364<style> 365 .foo .bar::slotted(*) {} 366</style> 367<span class="foo"> 368 <slot class="bar"></slot> 369</span> 370``` 371 372```html 373<!-- Good --> 374<style> 375 .foo ::slotted(*) {} 376</style> 377<span class="foo"> 378 <slot></slot> 379</span> 380``` 381 382### Custom properties and `@apply` 383 384Dynamic changes are not automatically applied. If elements change such that they 385conditionally match selectors they did not previously, `ShadyCSS.styleDocument()` 386must be called. 387 388For a given element's shadowRoot, only 1 value is allowed per custom properties. 389Properties cannot change from parent to child as they can under native custom 390properties; they can only change when a shadowRoot boundary is crossed. 391 392To receive a custom property, an element must directly match a selector that 393defines the property in its host's stylesheet. 394 395### `<custom-style>` Flash of unstyled content 396 397If `ShadyCSS.applyStyle` is never called, `<custom-style>` elements will process 398after HTML Imports have loaded, after the document loads, or after the next paint. 399This means that there may be a flash of unstyled content on the first load. 400 401### Mixins do not cascade throught `<slot>` 402 403Crawling the DOM and updating styles is very expensive, and we found that trying to 404update mixins through `<slot>` insertion points to be too expensive to justify for both 405polyfilled CSS Mixins and polyfilled CSS Custom Properties. 406 407### External stylesheets not currently supported 408 409External stylesheets loaded via `<link rel="stylesheet">` within a shadow root or 410`@import` syntax inside a shadow root's stylesheet are not currently shimmed by 411the polyfill. This is mainly due to the fact that shimming them would require 412a fetch of the stylesheet text that is async cannot be easily coordinated with 413the upgrade timing of custom elements using them, making it impossible to avoid 414"flash of unstyled content" when running on polyfill. 415 416### Document level styling is not scoped by default 417 418ShadyCSS mimics the behavior of shadow dom, but it is not able to prevent document 419level styling to affect elements inside a shady dom. Global styles defined in 420`index.html` or any styles not processed by ShadyCSS will affect all elements on the page. 421 422To scope document level styling, the style must be wrapped in the `<custom-style>` element 423found in Polymer, or use the `CustomStyleInterface` library to modify document level styles. 424 425### Dynamically created styles are not supported 426 427ShadyCSS works by processing a template for a given custom element class. Only the style 428elements present in that template will be scoped for the custom element's ShadowRoot. 429