MCPcopy Index your code
hub / github.com/ampproject/amphtml / createShadowRootPolyfill

Function createShadowRootPolyfill

src/shadow-embed.js:102–151  ·  view source on GitHub ↗

* Shadow root polyfill. * @param {!Element} hostElement * @return {!ShadowRoot}

(hostElement)

Source from the content-addressed store, hash-verified

100 * @return {!ShadowRoot}
101 */
102function createShadowRootPolyfill(hostElement) {
103 const doc = hostElement.ownerDocument;
104
105 // Host CSS polyfill.
106 hostElement.classList.add('i-amphtml-shadow-host-polyfill');
107 const hostStyle = doc.createElement('style');
108 hostStyle.textContent =
109 '.i-amphtml-shadow-host-polyfill>:not(i-amphtml-shadow-root)' +
110 '{display:none!important}';
111 hostElement.appendChild(hostStyle);
112
113 // Shadow root.
114 const shadowRoot /** @type {!ShadowRoot} */ =
115 // Cast to ShadowRoot even though it is an Element
116 // TODO(@dvoytenko) Consider to switch to a type union instead.
117 /** @type {?} */ (doc.createElement('i-amphtml-shadow-root'));
118 hostElement.appendChild(shadowRoot);
119 hostElement.__AMP_SHADOW_ROOT = shadowRoot;
120 Object.defineProperty(hostElement, 'shadowRoot', {
121 enumerable: true,
122 configurable: true,
123 value: shadowRoot,
124 });
125
126 // API: https://www.w3.org/TR/shadow-dom/#the-shadowroot-interface
127
128 shadowRoot.host = hostElement;
129
130 // `getElementById` is resolved via `querySelector('#id')`.
131 shadowRoot.getElementById = function (id) {
132 const escapedId = escapeCssSelectorIdent(id);
133 return /** @type {?HTMLElement} */ (
134 shadowRoot./*OK*/ querySelector(`#${escapedId}`)
135 );
136 };
137
138 // The styleSheets property should have a list of local styles.
139 Object.defineProperty(shadowRoot, 'styleSheets', {
140 get: () => {
141 if (!doc.styleSheets) {
142 return [];
143 }
144 return toArray(doc.styleSheets).filter((styleSheet) =>
145 shadowRoot.contains(styleSheet.ownerNode)
146 );
147 },
148 });
149
150 return shadowRoot;
151}
152
153/**
154 * Imports a body into a shadow root with the workaround for a polyfill case.

Callers 1

createShadowRootFunction · 0.85

Calls 5

escapeCssSelectorIdentFunction · 0.90
toArrayFunction · 0.90
addMethod · 0.45
filterMethod · 0.45
containsMethod · 0.45

Tested by

no test coverage detected