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.

319 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. // -> Check for empty first element
  158. let firstElm = cr.root().children().first()[0]
  159. if (firstElm.type === 'tag' && firstElm.name === 'p') {
  160. let firstElmChildren = firstElm.children
  161. if (firstElmChildren.length < 1) {
  162. firstElm.remove()
  163. } else if (firstElmChildren.length === 1 && firstElmChildren[0].type === 'tag' && firstElmChildren[0].name === 'img') {
  164. cr(firstElm).addClass('is-gapless')
  165. }
  166. }
  167. // -> Remove links in headers
  168. cr('h1 > a:not(.toc-anchor), h2 > a:not(.toc-anchor), h3 > a:not(.toc-anchor)').each((i, elm) => {
  169. let txtLink = cr(elm).text()
  170. cr(elm).replaceWith(txtLink)
  171. })
  172. // -> Re-attach blockquote styling classes to their parents
  173. cr.root().children('blockquote').each((i, elm) => {
  174. if (cr(elm).children().length > 0) {
  175. let bqLastChild = cr(elm).children().last()[0]
  176. let bqLastChildClasses = cr(bqLastChild).attr('class')
  177. if (bqLastChildClasses && bqLastChildClasses.length > 0) {
  178. cr(bqLastChild).removeAttr('class')
  179. cr(elm).addClass(bqLastChildClasses)
  180. }
  181. }
  182. })
  183. // -> Enclose content below headers
  184. cr('h2').each((i, elm) => {
  185. let subH2Content = cr(elm).nextUntil('h1, h2')
  186. cr(elm).after('<div class="indent-h2"></div>')
  187. let subH2Container = cr(elm).next('.indent-h2')
  188. _.forEach(subH2Content, (ch) => {
  189. cr(subH2Container).append(ch)
  190. })
  191. })
  192. cr('h3').each((i, elm) => {
  193. let subH3Content = cr(elm).nextUntil('h1, h2, h3')
  194. cr(elm).after('<div class="indent-h3"></div>')
  195. let subH3Container = cr(elm).next('.indent-h3')
  196. _.forEach(subH3Content, (ch) => {
  197. cr(subH3Container).append(ch)
  198. })
  199. })
  200. // Replace video links with embeds
  201. _.forEach(videoRules, (vrule) => {
  202. cr(vrule.selector).each((i, elm) => {
  203. let originLink = cr(elm).attr('href')
  204. if (vrule.regexp) {
  205. let vidMatches = originLink.match(vrule.regexp)
  206. if ((vidMatches && _.isArray(vidMatches))) {
  207. vidMatches = _.filter(vidMatches, (f) => {
  208. return f && _.isString(f)
  209. })
  210. originLink = _.last(vidMatches)
  211. }
  212. }
  213. let processedLink = _.replace(vrule.output, '{0}', originLink)
  214. cr(elm).replaceWith(processedLink)
  215. })
  216. })
  217. // Apply align-center to parent
  218. cr('img.align-center').each((i, elm) => {
  219. cr(elm).parent().addClass('align-center')
  220. cr(elm).removeClass('align-center')
  221. })
  222. output = cr.html()
  223. return output
  224. }
  225. /**
  226. * Parse meta-data tags from content
  227. *
  228. * @param {String} content Markdown content
  229. * @return {Object} Properties found in the content and their values
  230. */
  231. const parseMeta = (content) => {
  232. let commentMeta = new RegExp('<!-- ?([a-zA-Z]+):(.*)-->', 'g')
  233. let results = {}
  234. let match
  235. while ((match = commentMeta.exec(content)) !== null) {
  236. results[_.toLower(match[1])] = _.trim(match[2])
  237. }
  238. return results
  239. }
  240. module.exports = {
  241. /**
  242. * Parse content and return all data
  243. *
  244. * @param {String} content Markdown-formatted content
  245. * @return {Object} Object containing meta, html and tree data
  246. */
  247. parse (content) {
  248. return {
  249. meta: parseMeta(content),
  250. html: parseContent(content),
  251. tree: parseTree(content)
  252. }
  253. },
  254. parseContent,
  255. parseMeta,
  256. parseTree,
  257. /**
  258. * Strips non-text elements from Markdown content
  259. *
  260. * @param {String} content Markdown-formatted content
  261. * @return {String} Text-only version
  262. */
  263. removeMarkdown (content) {
  264. return mdRemove(_.chain(content)
  265. .replace(/<!-- ?([a-zA-Z]+):(.*)-->/g, '')
  266. .replace(/```[^`]+```/g, '')
  267. .replace(/`[^`]+`/g, '')
  268. .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'), '')
  269. .replace(/\r?\n|\r/g, ' ')
  270. .deburr()
  271. .toLower()
  272. .replace(/(\b([^a-z]+)\b)/g, ' ')
  273. .replace(/[^a-z]+/g, ' ')
  274. .replace(/(\b(\w{1,2})\b(\W|$))/g, '')
  275. .replace(/\s\s+/g, ' ')
  276. .value()
  277. )
  278. }
  279. }