shadycss icon indicating copy to clipboard operation
shadycss copied to clipboard

Support for different shadow roots for the same (native/custom) element name

Open tomalec opened this issue 8 years ago • 1 comments

I figured out how to use ShadyCSS API to polyfill shadow styles for native elements, and to apply different roots for the same tag name: generate a unique id for shadow root and use is attribute: https://jsbin.com/raqilon/7/edit

<div is="shadow-host-1">
    ShadyCSS.prepareTemplate(template, 'shadow-host-1', 'my-element');
    div.attachShadow({mode: 'open'}).appendChild(document.importNode(template.content, true));
    ShadyCSS.styleElement(div);

The problem is that it does not work for custom elements after they are upgraded (works fine before the upgrade) https://jsbin.com/raqilon/edit?html,output

  <script>customElements.define('my-element', class extends HTMLElement{});</script>

  <my-element id="host" is="shadow-host-1">DOM</my-element>
  <template id="shadow">
    <style>
      :host{
        color: lightgreen;
      }
      
      .inner {
        color: darkgreen;
      }
    </style>
    Shadow <slot></slot><div class="inner">fine</div>
  </template>
  <script>
    ShadyCSS.prepareTemplate(shadow, 'shadow-host-1', 'my-element');
    host.attachShadow({mode: 'open'}).appendChild(document.importNode(shadow.content, true));
    ShadyCSS.styleElement(host);
  </script>

Works fine, but if I set shadow root after element is defined it fails to attach correct style scope classes:

  <my-element id="host2" is="shadow-host-2">Works</my-element>
  <template id="shadow2">
    <style>
      .inner {
        color: red;
      }
    </style>
    Polyfill <slot></slot><div class="inner">NOT</div>
  </template>
  <script>
    customElements.whenDefined('my-element').then(()=>{
      ShadyCSS.prepareTemplate(shadow2, 'shadow-host-2', 'my-element');
      host2.attachShadow({mode: 'open'}).appendChild(document.importNode(shadow2.content, true));
      ShadyCSS.styleElement(host2);
    });
  </script>

I would be happy to provide template id to ShadyCSS.styleElement(host2, 'shadow-host-2'); if it would accept it, currently it automatically tries to guess it.

At https://github.com/webcomponents/shadycss/blob/master/src/style-util.js#L252-L271 it ignores the is attribute for custom elements, and uses localName as template identifier.

tomalec avatar Jun 05 '18 15:06 tomalec

This is probably related to #178

TimvdLippe avatar Sep 19 '18 16:09 TimvdLippe