Skip to content

Commit

Permalink
Updates Declarative Shadow DOM polyfill to apply recursively.
Browse files Browse the repository at this point in the history
Without this, only top-level DSD nodes would get applied. This allows us to nest one DSD node under another.
  • Loading branch information
dgp1130 committed Sep 4, 2023
1 parent 945ce12 commit 719cb36
Showing 1 changed file with 19 additions and 14 deletions.
33 changes: 19 additions & 14 deletions packages/declarative_shadow_dom/declarative_shadow_dom_polyfill.mts
Original file line number Diff line number Diff line change
@@ -1,23 +1,28 @@
/**
* @fileoverview Polyfills declarative shadow DOM by searching for templates
* which match its attributes and attaching them as real shadow roots.
*
*
* Shamelessly stolen from: https://web.dev/declarative-shadow-dom/#polyfill and
* adapted for TypeScript.
*/

const templates = document.querySelectorAll('template[shadowrootmode]') as
NodeListOf<HTMLTemplateElement>;
for (const template of Array.from(templates)) {
const mode = template.getAttribute('shadowrootmode');
if (mode !== 'open' && mode !== 'closed') {
console.error(
`Found declarative shadow root with invalid mode: ${mode}.`);
continue;
}
function applyDsdNodes(root: Element | ShadowRoot): void {
const templates = root.querySelectorAll('template[shadowrootmode]') as
NodeListOf<HTMLTemplateElement>;
for (const template of Array.from(templates)) {
const mode = template.getAttribute('shadowrootmode');
if (mode !== 'open' && mode !== 'closed') {
console.error(
`Found declarative shadow root with invalid mode: ${mode}.`);
continue;
}

const parent = template.parentNode as Element;
const shadowRoot = parent.attachShadow({ mode });
shadowRoot.appendChild(template.content);
template.remove();
const parent = template.parentNode as Element;
const shadowRoot = parent.attachShadow({ mode });
shadowRoot.appendChild(template.content);
template.remove();
applyDsdNodes(shadowRoot);
}
}

applyDsdNodes(document.documentElement);

0 comments on commit 719cb36

Please sign in to comment.