table-row.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /**
  2. * @import {Element, ElementContent, Properties} from 'hast'
  3. * @import {Parents, TableRow} from 'mdast'
  4. * @import {State} from '../state.js'
  5. */
  6. /**
  7. * Turn an mdast `tableRow` node into hast.
  8. *
  9. * @param {State} state
  10. * Info passed around.
  11. * @param {TableRow} node
  12. * mdast node.
  13. * @param {Parents | undefined} parent
  14. * Parent of `node`.
  15. * @returns {Element}
  16. * hast node.
  17. */
  18. export function tableRow(state, node, parent) {
  19. const siblings = parent ? parent.children : undefined
  20. // Generate a body row when without parent.
  21. const rowIndex = siblings ? siblings.indexOf(node) : 1
  22. const tagName = rowIndex === 0 ? 'th' : 'td'
  23. // To do: option to use `style`?
  24. const align = parent && parent.type === 'table' ? parent.align : undefined
  25. const length = align ? align.length : node.children.length
  26. let cellIndex = -1
  27. /** @type {Array<ElementContent>} */
  28. const cells = []
  29. while (++cellIndex < length) {
  30. // Note: can also be undefined.
  31. const cell = node.children[cellIndex]
  32. /** @type {Properties} */
  33. const properties = {}
  34. const alignValue = align ? align[cellIndex] : undefined
  35. if (alignValue) {
  36. properties.align = alignValue
  37. }
  38. /** @type {Element} */
  39. let result = {type: 'element', tagName, properties, children: []}
  40. if (cell) {
  41. result.children = state.all(cell)
  42. state.patch(cell, result)
  43. result = state.applyData(cell, result)
  44. }
  45. cells.push(result)
  46. }
  47. /** @type {Element} */
  48. const result = {
  49. type: 'element',
  50. tagName: 'tr',
  51. properties: {},
  52. children: state.wrap(cells, true)
  53. }
  54. state.patch(node, result)
  55. return state.applyData(node, result)
  56. }