MCPcopy Create free account
hub / github.com/ampproject/amphtml / installPatches

Function installPatches

src/polyfills/custom-elements.js:536–645  ·  view source on GitHub ↗

* Patches the DOM APIs to support synchronous Custom Elements. * @param {!Window} win * @param {!Registry} registry

(win, registry)

Source from the content-addressed store, hash-verified

534 * @param {!Registry} registry
535 */
536function installPatches(win, registry) {
537 const {Document, Element, Node, document} = win;
538 const docProto = Document.prototype;
539 const elProto = Element.prototype;
540 const nodeProto = Node.prototype;
541 const {createElement, importNode} = docProto;
542 const {appendChild, cloneNode, insertBefore, removeChild, replaceChild} =
543 nodeProto;
544
545 // Patch createElement to immediately upgrade the custom element.
546 // This has the added benefit that it avoids the "already created but needs
547 // constructor code run" chicken-and-egg problem.
548 docProto.createElement = function (name) {
549 const def = registry.getByName(name);
550 if (def) {
551 return new def.ctor();
552 }
553 return createElement.apply(this, arguments);
554 };
555
556 // Patch importNode to immediately upgrade custom elements.
557 // TODO(jridgewell): Can fire adoptedCallback for cross doc imports.
558 docProto.importNode = function () {
559 const imported = importNode.apply(this, arguments);
560
561 // Only upgrade elements if the document that the nodes were imported into
562 // is _this_ document. If it's another document, then that document's
563 // element registry must do the upgrade.
564 // Eg, when importing from a <template>, the cloned document fragment
565 // should be upgraded. But importing from document into the <template>
566 // should not.
567 if (imported && this === document) {
568 registry.upgradeSelf(imported);
569 registry.upgrade(imported);
570 }
571 return imported;
572 };
573
574 // Patch appendChild to upgrade custom elements before returning.
575 nodeProto.appendChild = function () {
576 const appended = appendChild.apply(this, arguments);
577 registry.sync();
578 return appended;
579 };
580
581 // Patch insertBefore to upgrade custom elements before returning.
582 nodeProto.insertBefore = function () {
583 const inserted = insertBefore.apply(this, arguments);
584 registry.sync();
585 return inserted;
586 };
587
588 // Patch removeChild to upgrade custom elements before returning.
589 nodeProto.removeChild = function () {
590 const removed = removeChild.apply(this, arguments);
591 registry.sync();
592 return removed;
593 };

Callers 1

observe_Method · 0.85

Calls 5

getByNameMethod · 0.80
applyMethod · 0.80
upgradeSelfMethod · 0.80
syncMethod · 0.80
upgradeMethod · 0.45

Tested by

no test coverage detected