index.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict'
  2. var visit = require('unist-util-visit')
  3. module.exports = compact
  4. // Make an mdast tree compact by merging adjacent text nodes.
  5. function compact(tree, commonmark) {
  6. visit(tree, visitor)
  7. return tree
  8. function visitor(child, index, parent) {
  9. var siblings = parent ? parent.children : []
  10. var prev = index && siblings[index - 1]
  11. if (
  12. prev &&
  13. child.type === prev.type &&
  14. mergeable(prev, commonmark) &&
  15. mergeable(child, commonmark)
  16. ) {
  17. if (child.value) {
  18. prev.value += child.value
  19. }
  20. if (child.children) {
  21. prev.children = prev.children.concat(child.children)
  22. }
  23. siblings.splice(index, 1)
  24. if (prev.position && child.position) {
  25. prev.position.end = child.position.end
  26. }
  27. return index
  28. }
  29. }
  30. }
  31. function mergeable(node, commonmark) {
  32. var start
  33. var end
  34. if (node.type === 'text') {
  35. if (!node.position) {
  36. return true
  37. }
  38. start = node.position.start
  39. end = node.position.end
  40. // Only merge nodes which occupy the same size as their `value`.
  41. return (
  42. start.line !== end.line || end.column - start.column === node.value.length
  43. )
  44. }
  45. return commonmark && node.type === 'blockquote'
  46. }