container-flow.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**
  2. * @import {State} from 'mdast-util-to-markdown'
  3. * @import {FlowChildren, FlowParents, TrackFields} from '../types.js'
  4. */
  5. /**
  6. * @param {FlowParents} parent
  7. * Parent of flow nodes.
  8. * @param {State} state
  9. * Info passed around about the current state.
  10. * @param {TrackFields} info
  11. * Info on where we are in the document we are generating.
  12. * @returns {string}
  13. * Serialized children, joined by (blank) lines.
  14. */
  15. export function containerFlow(parent, state, info) {
  16. const indexStack = state.indexStack
  17. const children = parent.children || []
  18. const tracker = state.createTracker(info)
  19. /** @type {Array<string>} */
  20. const results = []
  21. let index = -1
  22. indexStack.push(-1)
  23. while (++index < children.length) {
  24. const child = children[index]
  25. indexStack[indexStack.length - 1] = index
  26. results.push(
  27. tracker.move(
  28. state.handle(child, parent, state, {
  29. before: '\n',
  30. after: '\n',
  31. ...tracker.current()
  32. })
  33. )
  34. )
  35. if (child.type !== 'list') {
  36. state.bulletLastUsed = undefined
  37. }
  38. if (index < children.length - 1) {
  39. results.push(
  40. tracker.move(between(child, children[index + 1], parent, state))
  41. )
  42. }
  43. }
  44. indexStack.pop()
  45. return results.join('')
  46. }
  47. /**
  48. * @param {FlowChildren} left
  49. * @param {FlowChildren} right
  50. * @param {FlowParents} parent
  51. * @param {State} state
  52. * @returns {string}
  53. */
  54. function between(left, right, parent, state) {
  55. let index = state.join.length
  56. while (index--) {
  57. const result = state.join[index](left, right, parent, state)
  58. if (result === true || result === 1) {
  59. break
  60. }
  61. if (typeof result === 'number') {
  62. return '\n'.repeat(1 + result)
  63. }
  64. if (result === false) {
  65. return '\n\n<!---->\n\n'
  66. }
  67. }
  68. return '\n\n'
  69. }