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.

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