-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Updates Declarative Shadow DOM polyfill to apply recursively.
Without this, only top-level DSD nodes would get applied. This allows us to nest one DSD node under another.
- Loading branch information
Showing
1 changed file
with
19 additions
and
14 deletions.
There are no files selected for viewing
33 changes: 19 additions & 14 deletions
33
packages/declarative_shadow_dom/declarative_shadow_dom_polyfill.mts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |