You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

323 lines
9.2 KiB

  1. 'use strict'
  2. const md = require('markdown-it')
  3. const mdEmoji = require('markdown-it-emoji')
  4. const mdTaskLists = require('markdown-it-task-lists')
  5. const mdAbbr = require('markdown-it-abbr')
  6. const mdAnchor = require('markdown-it-anchor')
  7. const mdFootnote = require('markdown-it-footnote')
  8. const mdExternalLinks = require('markdown-it-external-links')
  9. const mdExpandTabs = require('markdown-it-expand-tabs')
  10. const mdAttrs = require('markdown-it-attrs')
  11. const hljs = require('highlight.js')
  12. const cheerio = require('cheerio')
  13. const _ = require('lodash')
  14. const mdRemove = require('remove-markdown')
  15. // Load plugins
  16. var mkdown = md({
  17. html: true,
  18. linkify: true,
  19. typography: true,
  20. highlight (str, lang) {
  21. if (lang && hljs.getLanguage(lang)) {
  22. try {
  23. return '<pre class="hljs"><code>' + hljs.highlight(lang, str, true).value + '</code></pre>'
  24. } catch (err) {
  25. return '<pre><code>' + str + '</code></pre>'
  26. }
  27. }
  28. return '<pre><code>' + str + '</code></pre>'
  29. }
  30. })
  31. .use(mdEmoji)
  32. .use(mdTaskLists)
  33. .use(mdAbbr)
  34. .use(mdAnchor, {
  35. slugify: _.kebabCase,
  36. permalink: true,
  37. permalinkClass: 'toc-anchor icon-anchor',
  38. permalinkSymbol: '',
  39. permalinkBefore: true
  40. })
  41. .use(mdFootnote)
  42. .use(mdExternalLinks, {
  43. externalClassName: 'external-link',
  44. internalClassName: 'internal-link'
  45. })
  46. .use(mdExpandTabs, {
  47. tabWidth: 4
  48. })
  49. .use(mdAttrs)
  50. // Rendering rules
  51. mkdown.renderer.rules.emoji = function (token, idx) {
  52. return '<i class="twa twa-' + _.replace(token[idx].markup, /_/g, '-') + '"></i>'
  53. }
  54. // Video rules
  55. const videoRules = [
  56. {
  57. selector: 'a.youtube',
  58. regexp: new RegExp(/(?:(?:youtu\.be\/|v\/|vi\/|u\/\w\/|embed\/)|(?:(?:watch)?\?v(?:i)?=|&v(?:i)?=))([^#&?]*).*/i),
  59. output: '<iframe width="640" height="360" src="https://www.youtube.com/embed/{0}?rel=0" frameborder="0" allowfullscreen></iframe>'
  60. },
  61. {
  62. selector: 'a.vimeo',
  63. regexp: new RegExp(/vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/(?:[^/]*)\/videos\/|album\/(?:\d+)\/video\/|)(\d+)(?:$|\/|\?)/i),
  64. output: '<iframe src="https://player.vimeo.com/video/{0}" width="640" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>'
  65. },
  66. {
  67. selector: 'a.dailymotion',
  68. regexp: new RegExp(/(?:dailymotion\.com(?:\/embed)?(?:\/video|\/hub)|dai\.ly)\/([0-9a-z]+)(?:[-_0-9a-zA-Z]+(?:#video=)?([a-z0-9]+)?)?/i),
  69. output: '<iframe width="640" height="360" src="//www.dailymotion.com/embed/video/{0}?endscreen-enable=false" frameborder="0" allowfullscreen></iframe>'
  70. },
  71. {
  72. selector: 'a.video',
  73. regexp: false,
  74. output: '<video width="640" height="360" controls preload="metadata"><source src="{0}" type="video/mp4"></video>'
  75. }
  76. ]
  77. /**
  78. * Parse markdown content and build TOC tree
  79. *
  80. * @param {(Function|string)} content Markdown content
  81. * @return {Array} TOC tree
  82. */
  83. const parseTree = (content) => {
  84. let tokens = md().parse(content, {})
  85. let tocArray = []
  86. // -> Extract headings and their respective levels
  87. for (let i = 0; i < tokens.length; i++) {
  88. if (tokens[i].type !== 'heading_close') {
  89. continue
  90. }
  91. const heading = tokens[i - 1]
  92. const headingclose = tokens[i]
  93. if (heading.type === 'inline') {
  94. let content = ''
  95. let anchor = ''
  96. if (heading.children && heading.children[0].type === 'link_open') {
  97. content = heading.children[1].content
  98. anchor = _.kebabCase(content)
  99. } else {
  100. content = heading.content
  101. anchor = _.kebabCase(heading.children.reduce((acc, t) => acc + t.content, ''))
  102. }
  103. tocArray.push({
  104. content,
  105. anchor,
  106. level: +headingclose.tag.substr(1, 1)
  107. })
  108. }
  109. }
  110. // -> Exclude levels deeper than 2
  111. _.remove(tocArray, (n) => { return n.level > 2 })
  112. // -> Build tree from flat array
  113. return _.reduce(tocArray, (tree, v) => {
  114. let treeLength = tree.length - 1
  115. if (v.level < 2) {
  116. tree.push({
  117. content: v.content,
  118. anchor: v.anchor,
  119. nodes: []
  120. })
  121. } else {
  122. let lastNodeLevel = 1
  123. let GetNodePath = (startPos) => {
  124. lastNodeLevel++
  125. if (_.isEmpty(startPos)) {
  126. startPos = 'nodes'
  127. }
  128. if (lastNodeLevel === v.level) {
  129. return startPos
  130. } else {
  131. return GetNodePath(startPos + '[' + (_.at(tree[treeLength], startPos).length - 1) + '].nodes')
  132. }
  133. }
  134. let lastNodePath = GetNodePath()
  135. let lastNode = _.get(tree[treeLength], lastNodePath)
  136. if (lastNode) {
  137. lastNode.push({
  138. content: v.content,
  139. anchor: v.anchor,
  140. nodes: []
  141. })
  142. _.set(tree[treeLength], lastNodePath, lastNode)
  143. }
  144. }
  145. return tree
  146. }, [])
  147. }
  148. /**
  149. * Parse markdown content to HTML
  150. *
  151. * @param {String} content Markdown content
  152. * @return {String} HTML formatted content
  153. */
  154. const parseContent = (content) => {
  155. let output = mkdown.render(content)
  156. let cr = cheerio.load(output)
  157. if (cr.root().children().length < 1) {
  158. return ''
  159. }
  160. // -> Check for empty first element
  161. let firstElm = cr.root().children().first()[0]
  162. if (firstElm.type === 'tag' && firstElm.name === 'p') {
  163. let firstElmChildren = firstElm.children
  164. if (firstElmChildren.length < 1) {
  165. firstElm.remove()
  166. } else if (firstElmChildren.length === 1 && firstElmChildren[0].type === 'tag' && firstElmChildren[0].name === 'img') {
  167. cr(firstElm).addClass('is-gapless')
  168. }
  169. }
  170. // -> Remove links in headers
  171. cr('h1 > a:not(.toc-anchor), h2 > a:not(.toc-anchor), h3 > a:not(.toc-anchor)').each((i, elm) => {
  172. let txtLink = cr(elm).text()
  173. cr(elm).replaceWith(txtLink)
  174. })
  175. // -> Re-attach blockquote styling classes to their parents
  176. cr.root().children('blockquote').each((i, elm) => {
  177. if (cr(elm).children().length > 0) {
  178. let bqLastChild = cr(elm).children().last()[0]
  179. let bqLastChildClasses = cr(bqLastChild).attr('class')
  180. if (bqLastChildClasses && bqLastChildClasses.length > 0) {
  181. cr(bqLastChild).removeAttr('class')
  182. cr(elm).addClass(bqLastChildClasses)
  183. }
  184. }
  185. })
  186. // -> Enclose content below headers
  187. cr('h2').each((i, elm) => {
  188. let subH2Content = cr(elm).nextUntil('h1, h2')
  189. cr(elm).after('<div class="indent-h2"></div>')
  190. let subH2Container = cr(elm).next('.indent-h2')
  191. _.forEach(subH2Content, (ch) => {
  192. cr(subH2Container).append(ch)
  193. })
  194. })
  195. cr('h3').each((i, elm) => {
  196. let subH3Content = cr(elm).nextUntil('h1, h2, h3')
  197. cr(elm).after('<div class="indent-h3"></div>')
  198. let subH3Container = cr(elm).next('.indent-h3')
  199. _.forEach(subH3Content, (ch) => {
  200. cr(subH3Container).append(ch)
  201. })
  202. })
  203. // Replace video links with embeds
  204. _.forEach(videoRules, (vrule) => {
  205. cr(vrule.selector).each((i, elm) => {
  206. let originLink = cr(elm).attr('href')
  207. if (vrule.regexp) {
  208. let vidMatches = originLink.match(vrule.regexp)
  209. if ((vidMatches && _.isArray(vidMatches))) {
  210. vidMatches = _.filter(vidMatches, (f) => {
  211. return f && _.isString(f)
  212. })
  213. originLink = _.last(vidMatches)
  214. }
  215. }
  216. let processedLink = _.replace(vrule.output, '{0}', originLink)
  217. cr(elm).replaceWith(processedLink)
  218. })
  219. })
  220. // Apply align-center to parent
  221. cr('img.align-center').each((i, elm) => {
  222. cr(elm).parent().addClass('align-center')
  223. cr(elm).removeClass('align-center')
  224. })
  225. output = cr.html()
  226. return output
  227. }
  228. /**
  229. * Parse meta-data tags from content
  230. *
  231. * @param {String} content Markdown content
  232. * @return {Object} Properties found in the content and their values
  233. */
  234. const parseMeta = (content) => {
  235. let commentMeta = new RegExp('<!-- ?([a-zA-Z]+):(.*)-->', 'g')
  236. let results = {}
  237. let match
  238. while ((match = commentMeta.exec(content)) !== null) {
  239. results[_.toLower(match[1])] = _.trim(match[2])
  240. }
  241. return results
  242. }
  243. module.exports = {
  244. /**
  245. * Parse content and return all data
  246. *
  247. * @param {String} content Markdown-formatted content
  248. * @return {Object} Object containing meta, html and tree data
  249. */
  250. parse (content) {
  251. return {
  252. meta: parseMeta(content),
  253. html: parseContent(content),
  254. tree: parseTree(content)
  255. }
  256. },
  257. parseContent,
  258. parseMeta,
  259. parseTree,
  260. /**
  261. * Strips non-text elements from Markdown content
  262. *
  263. * @param {String} content Markdown-formatted content
  264. * @return {String} Text-only version
  265. */
  266. removeMarkdown (content) {
  267. return mdRemove(_.chain(content)
  268. .replace(/<!-- ?([a-zA-Z]+):(.*)-->/g, '')
  269. .replace(/```[^`]+```/g, '')
  270. .replace(/`[^`]+`/g, '')
  271. .replace(new RegExp('(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?', 'g'), '')
  272. .replace(/\r?\n|\r/g, ' ')
  273. .deburr()
  274. .toLower()
  275. .replace(/(\b([^a-z]+)\b)/g, ' ')
  276. .replace(/[^a-z]+/g, ' ')
  277. .replace(/(\b(\w{1,2})\b(\W|$))/g, '')
  278. .replace(/\s\s+/g, ' ')
  279. .value()
  280. )
  281. }
  282. }