/** * @license * Copyright 2026 Google LLC * SPDX-License-Identifier: Apache-2.0 */ (() => { // Only process the polyfill if needed if ('htmlFor' in HTMLTemplateElement.prototype) return; console.log('Loading templates for polyfill...'); // Helper function to actually insert the content and cleanup the // processing instructions const replaceContentWithTemplate = ( type: string, templateNode: HTMLTemplateElement, startNode: Node, endNode: Node | null = null, target: HTMLElement ): void => { // Handle streaming parser. // If the document is still loading and either the template or the // processing instruction is the last element has siblings then it may be // incomplete. Return early and rely on the mutation observer and DCL // checks to reprocess later. if ( target.parentNode instanceof Document && document.readyState === 'loading' && (!templateNode.nextElementSibling || !(startNode as HTMLElement).nextElementSibling || (endNode && !(endNode as HTMLElement).nextElementSibling)) ) { return; } if (type !== 'marker') { // Remove every sibling after the startNode until the endNode. // If we don't have an end node, then we'll remove all siblings. let current = startNode.nextSibling; while (current) { if (current === endNode) { current.remove(); break; } const next = current.nextSibling; current.remove(); current = next; } } // Now actually replace the node (startNode as HTMLElement).replaceWith( templateNode.content.cloneNode(true) ); // Finally remove the template templateNode.remove(); }; const processTemplate = (template: HTMLTemplateElement) => { if ( !template || template.hasAttribute('data-no-patch') || !template.parentElement ) return; const name = template.getAttribute('for'); if (!name) return; // If the template is in the body then it has access to the whole document // including the const parent = template.parentElement === document.body ? document.documentElement : template.parentElement; // We use a TreeWalker instead of regular query selectors to // handle comments and processing instructions const walker = document.createTreeWalker( parent, // Processing Instructions usually are comments in non-supporting // browser, but we also handle the case of actual Processing // Instructions in case browsers ever introduce them for other // reasons without shipping