UNPKG

es5-lit-html

Version:
96 lines (76 loc) 2.98 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HTMLTemplate = void 0; var _template = require("./template"); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var markerRegex = /{{(.*?)}}/; var HTMLTemplate = function HTMLTemplate(element) { _classCallCheck(this, HTMLTemplate); this.parts = []; this.element = element; var index = -1; var partIndex = 0; var nodesToRemove = []; var walker = document.createTreeWalker(element.content, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT); while (walker.nextNode()) { index++; var node = walker.currentNode; if (node.nodeType === 1 /* Node.ELEMENT_NODE */ ) { if (node.hasAttributes()) { var attributes = Array.from(node.attributes); for (var i = 0; i < attributes.length; i++) { var attr = attributes[i]; var result = attr.value.split(markerRegex); console.log('result', result); var attributeStrings = result.filter(function (_, i) { return i % 2 === 0; }); // const exprStrings = result.filter((_, i) => i % 2 === 1); console.log('attributeStrings', attributeStrings); if (attributeStrings.length > 0) { this.parts.push({ type: 'attribute', index: index, name: name, strings: attributeStrings }); node.removeAttribute(attr.name); partIndex += attributeStrings.length - 1; } } } } else if (node.nodeType === 3 /* Node.TEXT_NODE */ ) { var data = node.data; var parent = node.parentNode; var _result = data.split(markerRegex); var strings = _result.filter(function (_, i) { return i % 2 === 0; }); if (strings.length > 0) { var lastIndex = strings.length - 1; // Generate a new text node for each literal section // These nodes are also used as the markers for node parts for (var _i = 0; _i < lastIndex; _i++) { parent.insertBefore(strings[_i] === '' ? (0, _template.createMarker)() : document.createTextNode(strings[_i]), node); this.parts.push({ type: 'node', index: ++index }); } // If there's no text, we must insert a comment to mark our place. // Else, we can trust it will stick around after cloning. if (strings[lastIndex] === '') { parent.insertBefore((0, _template.createMarker)(), node); nodesToRemove.push(node); } else { node.data = strings[lastIndex]; } // We have a part for each match found partIndex += lastIndex; } } } }; exports.HTMLTemplate = HTMLTemplate;