table.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * @import {Table} from 'mdast'
  3. * @import {Element} from 'hast'
  4. * @import {State} from '../state.js'
  5. */
  6. import {pointEnd, pointStart} from 'unist-util-position'
  7. /**
  8. * Turn an mdast `table` node into hast.
  9. *
  10. * @param {State} state
  11. * Info passed around.
  12. * @param {Table} node
  13. * mdast node.
  14. * @returns {Element}
  15. * hast node.
  16. */
  17. export function table(state, node) {
  18. const rows = state.all(node)
  19. const firstRow = rows.shift()
  20. /** @type {Array<Element>} */
  21. const tableContent = []
  22. if (firstRow) {
  23. /** @type {Element} */
  24. const head = {
  25. type: 'element',
  26. tagName: 'thead',
  27. properties: {},
  28. children: state.wrap([firstRow], true)
  29. }
  30. state.patch(node.children[0], head)
  31. tableContent.push(head)
  32. }
  33. if (rows.length > 0) {
  34. /** @type {Element} */
  35. const body = {
  36. type: 'element',
  37. tagName: 'tbody',
  38. properties: {},
  39. children: state.wrap(rows, true)
  40. }
  41. const start = pointStart(node.children[1])
  42. const end = pointEnd(node.children[node.children.length - 1])
  43. if (start && end) body.position = {start, end}
  44. tableContent.push(body)
  45. }
  46. /** @type {Element} */
  47. const result = {
  48. type: 'element',
  49. tagName: 'table',
  50. properties: {},
  51. children: state.wrap(tableContent, true)
  52. }
  53. state.patch(node, result)
  54. return state.applyData(node, result)
  55. }