elements.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. "use strict";
  2. /**
  3. * @license
  4. * Copyright Google LLC All Rights Reserved.
  5. *
  6. * Use of this source code is governed by an MIT-style license that can be
  7. * found in the LICENSE file at https://angular.io/license
  8. */
  9. Object.defineProperty(exports, "__esModule", { value: true });
  10. const parse5_1 = require("parse5");
  11. /**
  12. * Parses a HTML fragment and traverses all AST nodes in order find elements that
  13. * include the specified attribute.
  14. */
  15. function findElementsWithAttribute(html, attributeName) {
  16. const document = parse5_1.parseFragment(html, { sourceCodeLocationInfo: true });
  17. const elements = [];
  18. const visitNodes = nodes => {
  19. nodes.forEach(node => {
  20. if (node.childNodes) {
  21. visitNodes(node.childNodes);
  22. }
  23. if (node.attrs && node.attrs.some(attr => attr.name === attributeName.toLowerCase())) {
  24. elements.push(node);
  25. }
  26. });
  27. };
  28. visitNodes(document.childNodes);
  29. return elements;
  30. }
  31. exports.findElementsWithAttribute = findElementsWithAttribute;
  32. /**
  33. * Finds elements with explicit tag names that also contain the specified attribute. Returns the
  34. * attribute start offset based on the specified HTML.
  35. */
  36. function findAttributeOnElementWithTag(html, name, tagNames) {
  37. return findElementsWithAttribute(html, name)
  38. .filter(element => tagNames.includes(element.tagName))
  39. .map(element => getStartOffsetOfAttribute(element, name));
  40. }
  41. exports.findAttributeOnElementWithTag = findAttributeOnElementWithTag;
  42. /**
  43. * Finds elements that contain the given attribute and contain at least one of the other
  44. * specified attributes. Returns the primary attribute's start offset based on the specified HTML.
  45. */
  46. function findAttributeOnElementWithAttrs(html, name, attrs) {
  47. return findElementsWithAttribute(html, name)
  48. .filter(element => attrs.some(attr => hasElementAttribute(element, attr)))
  49. .map(element => getStartOffsetOfAttribute(element, name));
  50. }
  51. exports.findAttributeOnElementWithAttrs = findAttributeOnElementWithAttrs;
  52. /** Shorthand function that checks if the specified element contains the given attribute. */
  53. function hasElementAttribute(element, attributeName) {
  54. return element.attrs && element.attrs.some(attr => attr.name === attributeName.toLowerCase());
  55. }
  56. /** Gets the start offset of the given attribute from a Parse5 element. */
  57. function getStartOffsetOfAttribute(element, attributeName) {
  58. return element.sourceCodeLocation.attrs[attributeName.toLowerCase()].startOffset;
  59. }
  60. exports.getStartOffsetOfAttribute = getStartOffsetOfAttribute;
  61. //# sourceMappingURL=elements.js.map