gfm-converters.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. 'use strict'
  2. function cell (content, node) {
  3. var index = Array.prototype.indexOf.call(node.parentNode.childNodes, node)
  4. var prefix = ' '
  5. if (index === 0) prefix = '| '
  6. return prefix + content + ' |'
  7. }
  8. var highlightRegEx = /highlight highlight-(\S+)/
  9. module.exports = [
  10. {
  11. filter: 'br',
  12. replacement: function () {
  13. return '\n'
  14. }
  15. },
  16. {
  17. filter: ['del', 's', 'strike'],
  18. replacement: function (content) {
  19. return '~~' + content + '~~'
  20. }
  21. },
  22. {
  23. filter: function (node) {
  24. return node.type === 'checkbox' && node.parentNode.nodeName === 'LI'
  25. },
  26. replacement: function (content, node) {
  27. return (node.checked ? '[x]' : '[ ]') + ' '
  28. }
  29. },
  30. {
  31. filter: ['th', 'td'],
  32. replacement: function (content, node) {
  33. return cell(content, node)
  34. }
  35. },
  36. {
  37. filter: 'tr',
  38. replacement: function (content, node) {
  39. var borderCells = ''
  40. var alignMap = { left: ':--', right: '--:', center: ':-:' }
  41. if (node.parentNode.nodeName === 'THEAD') {
  42. for (var i = 0; i < node.childNodes.length; i++) {
  43. var align = node.childNodes[i].attributes.align
  44. var border = '---'
  45. if (align) border = alignMap[align.value] || border
  46. borderCells += cell(border, node.childNodes[i])
  47. }
  48. }
  49. return '\n' + content + (borderCells ? '\n' + borderCells : '')
  50. }
  51. },
  52. {
  53. filter: 'table',
  54. replacement: function (content) {
  55. return '\n\n' + content + '\n\n'
  56. }
  57. },
  58. {
  59. filter: ['thead', 'tbody', 'tfoot'],
  60. replacement: function (content) {
  61. return content
  62. }
  63. },
  64. // Fenced code blocks
  65. {
  66. filter: function (node) {
  67. return node.nodeName === 'PRE' &&
  68. node.firstChild &&
  69. node.firstChild.nodeName === 'CODE'
  70. },
  71. replacement: function (content, node) {
  72. return '\n\n```\n' + node.firstChild.textContent + '\n```\n\n'
  73. }
  74. },
  75. // Syntax-highlighted code blocks
  76. {
  77. filter: function (node) {
  78. return node.nodeName === 'PRE' &&
  79. node.parentNode.nodeName === 'DIV' &&
  80. highlightRegEx.test(node.parentNode.className)
  81. },
  82. replacement: function (content, node) {
  83. var language = node.parentNode.className.match(highlightRegEx)[1]
  84. return '\n\n```' + language + '\n' + node.textContent + '\n```\n\n'
  85. }
  86. },
  87. {
  88. filter: function (node) {
  89. return node.nodeName === 'DIV' &&
  90. highlightRegEx.test(node.className)
  91. },
  92. replacement: function (content) {
  93. return '\n\n' + content + '\n\n'
  94. }
  95. }
  96. ]