@webcomponents/custom-elements
Version:
HTML Custom Elements Polyfill
77 lines (65 loc) • 2.13 kB
JavaScript
import CustomElementInternals from '../../CustomElementInternals.js';
import * as Utilities from '../../Utilities.js';
/**
* @typedef {{
* prepend: !function(...(!Node|string)),
* append: !function(...(!Node|string)),
* }}
*/
let ParentNodeNativeMethods;
/**
* @param {!CustomElementInternals} internals
* @param {!Object} destination
* @param {!ParentNodeNativeMethods} builtIn
*/
export default function(internals, destination, builtIn) {
/**
* @param {!function(...(!Node|string))} builtInMethod
* @return {!function(...(!Node|string))}
*/
function appendPrependPatch(builtInMethod) {
return function(...nodes) {
/**
* A copy of `nodes`, with any DocumentFragment replaced by its children.
* @type {!Array<!Node>}
*/
const flattenedNodes = [];
/**
* Elements in `nodes` that were connected before this call.
* @type {!Array<!Node>}
*/
const connectedElements = [];
for (var i = 0; i < nodes.length; i++) {
const node = nodes[i];
if (node instanceof Element && Utilities.isConnected(node)) {
connectedElements.push(node);
}
if (node instanceof DocumentFragment) {
for (let child = node.firstChild; child; child = child.nextSibling) {
flattenedNodes.push(child);
}
} else {
flattenedNodes.push(node);
}
}
builtInMethod.apply(this, nodes);
for (let i = 0; i < connectedElements.length; i++) {
internals.disconnectTree(connectedElements[i]);
}
if (Utilities.isConnected(this)) {
for (let i = 0; i < flattenedNodes.length; i++) {
const node = flattenedNodes[i];
if (node instanceof Element) {
internals.connectTree(node);
}
}
}
};
}
if (builtIn.prepend !== undefined) {
Utilities.setPropertyUnchecked(destination, 'prepend', appendPrependPatch(builtIn.prepend));
}
if (builtIn.append !== undefined) {
Utilities.setPropertyUnchecked(destination, 'append', appendPrependPatch(builtIn.append));
}
};