transforms.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. var _ = require("underscore");
  2. exports.paragraph = paragraph;
  3. exports.run = run;
  4. exports._elements = elements;
  5. exports.getDescendantsOfType = getDescendantsOfType;
  6. exports.getDescendants = getDescendants;
  7. function paragraph(transform) {
  8. return elementsOfType("paragraph", transform);
  9. }
  10. function run(transform) {
  11. return elementsOfType("run", transform);
  12. }
  13. function elementsOfType(elementType, transform) {
  14. return elements(function(element) {
  15. if (element.type === elementType) {
  16. return transform(element);
  17. } else {
  18. return element;
  19. }
  20. });
  21. }
  22. function elements(transform) {
  23. return function transformElement(element) {
  24. if (element.children) {
  25. var children = _.map(element.children, transformElement);
  26. element = _.extend(element, {children: children});
  27. }
  28. return transform(element);
  29. };
  30. }
  31. function getDescendantsOfType(element, type) {
  32. return getDescendants(element).filter(function(descendant) {
  33. return descendant.type === type;
  34. });
  35. }
  36. function getDescendants(element) {
  37. var descendants = [];
  38. visitDescendants(element, function(descendant) {
  39. descendants.push(descendant);
  40. });
  41. return descendants;
  42. }
  43. function visitDescendants(element, visit) {
  44. if (element.children) {
  45. element.children.forEach(function(child) {
  46. visitDescendants(child, visit);
  47. visit(child);
  48. });
  49. }
  50. }