closed-shadowroot

by sperske

HTML

<open-shadow data-popup="ClosedSettings" text="I have an open shadow root">
  <div>Inside open element</div>
</open-shadow>
<closed-shadow data-popup="ClosedSettings" text="I have a closed shadow root">
  <div>Inside closed element</div>
</closed-shadow>

CSS

open-shadow {
  display: block;
  border: 1px solid green;
  width: 90%;
  margin-left: 8px;
}
closed-shadow {
  display: block;
  border: 1px solid red;
  width: 90%;
  margin-left: 8px;
}

JavaScript

customElements.define('open-shadow',
  class extends HTMLElement {
    constructor() {
      super();

      let pElem = document.createElement('p');
      pElem.textContent = this.getAttribute('text');

      let shadowRoot = this.attachShadow({
        mode: 'open'
      });
      shadowRoot.appendChild(pElem);
      [...this.childNodes].forEach(childNode => {
        shadowRoot.appendChild(childNode);
      });
    }
  });

customElements.define('closed-shadow',
  class extends HTMLElement {
    constructor() {
      super();

      let pElem = document.createElement('p');
      pElem.textContent = this.getAttribute('text');

      let shadowRoot = this.attachShadow({
        mode: 'closed'
      });
      shadowRoot.appendChild(pElem);
      [...this.childNodes].forEach(childNode => {
        shadowRoot.appendChild(childNode);
      });
    }
  });

function logPath(path) {
  const log = path.map(p => `${p.nodeName}${(p.dataset?.popup ? '['+p.dataset?.popup+']' : '')}`);
  return log;
}

document.querySelector('html').addEventListener('click', function(e) {
  let target = e.target;
  const path = [];
  while (target.parentElement) {
    path.push(target);
    target = target.parentElement;
  }
  console.log(logPath(e.composedPath()), logPath(path));
});