html-paths.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. var _ = require("underscore");
  2. var html = require("../html");
  3. exports.topLevelElement = topLevelElement;
  4. exports.elements = elements;
  5. exports.element = element;
  6. function topLevelElement(tagName, attributes) {
  7. return elements([element(tagName, attributes, {fresh: true})]);
  8. }
  9. function elements(elementStyles) {
  10. return new HtmlPath(elementStyles.map(function(elementStyle) {
  11. if (_.isString(elementStyle)) {
  12. return element(elementStyle);
  13. } else {
  14. return elementStyle;
  15. }
  16. }));
  17. }
  18. function HtmlPath(elements) {
  19. this._elements = elements;
  20. }
  21. HtmlPath.prototype.wrap = function wrap(children) {
  22. var result = children();
  23. for (var index = this._elements.length - 1; index >= 0; index--) {
  24. result = this._elements[index].wrapNodes(result);
  25. }
  26. return result;
  27. };
  28. function element(tagName, attributes, options) {
  29. options = options || {};
  30. return new Element(tagName, attributes, options);
  31. }
  32. function Element(tagName, attributes, options) {
  33. var tagNames = {};
  34. if (_.isArray(tagName)) {
  35. tagName.forEach(function(tagName) {
  36. tagNames[tagName] = true;
  37. });
  38. tagName = tagName[0];
  39. } else {
  40. tagNames[tagName] = true;
  41. }
  42. this.tagName = tagName;
  43. this.tagNames = tagNames;
  44. this.attributes = attributes || {};
  45. this.fresh = options.fresh;
  46. this.separator = options.separator;
  47. }
  48. Element.prototype.matchesElement = function(element) {
  49. return this.tagNames[element.tagName] && _.isEqual(this.attributes || {}, element.attributes || {});
  50. };
  51. Element.prototype.wrap = function wrap(generateNodes) {
  52. return this.wrapNodes(generateNodes());
  53. };
  54. Element.prototype.wrapNodes = function wrapNodes(nodes) {
  55. return [html.elementWithTag(this, nodes)];
  56. };
  57. exports.empty = elements([]);
  58. exports.ignore = {
  59. wrap: function() {
  60. return [];
  61. }
  62. };