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.

330 lines
9.4 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>' + _.escape(str) + '</code></pre>'
  26. }
  27. }
  28. return '<pre><code>' + _.escape(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 nc-icon-outline location_bookmark-add',
  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. // Non-markdown filter
  82. const textRegex = new RegExp('\\b[a-z0-9-.,' + appdata.regex.cjk + appdata.regex.arabic + ']+\\b', 'g')
  83. /**
  84. * Parse markdown content and build TOC tree
  85. *
  86. * @param {(Function|string)} content Markdown content
  87. * @return {Array} TOC tree
  88. */
  89. const parseTree = (content) => {
  90. content = content.replace(/<!--(.|\t|\n|\r)*?-->/g, '')
  91. let tokens = md().parse(content, {})
  92. let tocArray = []
  93. // -> Extract headings and their respective levels
  94. for (let i = 0; i < tokens.length; i++) {
  95. if (tokens[i].type !== 'heading_close') {
  96. continue
  97. }
  98. const heading = tokens[i - 1]
  99. const headingclose = tokens[i]
  100. if (heading.type === 'inline') {
  101. let content = ''
  102. let anchor = ''
  103. if (heading.children && heading.children.length > 0 && heading.children[0].type === 'link_open') {
  104. content = mdRemove(heading.children[1].content)
  105. anchor = _.kebabCase(content)
  106. } else {
  107. content = mdRemove(heading.content)
  108. anchor = _.kebabCase(heading.children.reduce((acc, t) => acc + t.content, ''))
  109. }
  110. tocArray.push({
  111. content,
  112. anchor,
  113. level: +headingclose.tag.substr(1, 1)
  114. })
  115. }
  116. }
  117. // -> Exclude levels deeper than 2
  118. _.remove(tocArray, (n) => { return n.level > 2 })
  119. // -> Build tree from flat array
  120. return _.reduce(tocArray, (tree, v) => {
  121. let treeLength = tree.length - 1
  122. if (v.level < 2) {
  123. tree.push({
  124. content: v.content,
  125. anchor: v.anchor,
  126. nodes: []
  127. })
  128. } else {
  129. let lastNodeLevel = 1
  130. let GetNodePath = (startPos) => {
  131. lastNodeLevel++
  132. if (_.isEmpty(startPos)) {
  133. startPos = 'nodes'
  134. }
  135. if (lastNodeLevel === v.level) {
  136. return startPos
  137. } else {
  138. return GetNodePath(startPos + '[' + (_.at(tree[treeLength], startPos).length - 1) + '].nodes')
  139. }
  140. }
  141. let lastNodePath = GetNodePath()
  142. let lastNode = _.get(tree[treeLength], lastNodePath)
  143. if (lastNode) {
  144. lastNode.push({
  145. content: v.content,
  146. anchor: v.anchor,
  147. nodes: []
  148. })
  149. _.set(tree[treeLength], lastNodePath, lastNode)
  150. }
  151. }
  152. return tree
  153. }, [])
  154. }
  155. /**
  156. * Parse markdown content to HTML
  157. *
  158. * @param {String} content Markdown content
  159. * @return {String} HTML formatted content
  160. */
  161. const parseContent = (content) => {
  162. let output = mkdown.render(content)
  163. let cr = cheerio.load(output)
  164. if (cr.root().children().length < 1) {
  165. return ''
  166. }
  167. // -> Check for empty first element
  168. let firstElm = cr.root().children().first()[0]
  169. if (firstElm.type === 'tag' && firstElm.name === 'p') {
  170. let firstElmChildren = firstElm.children
  171. if (firstElmChildren.length < 1) {
  172. firstElm.remove()
  173. } else if (firstElmChildren.length === 1 && firstElmChildren[0].type === 'tag' && firstElmChildren[0].name === 'img') {
  174. cr(firstElm).addClass('is-gapless')
  175. }
  176. }
  177. // -> Remove links in headers
  178. cr('h1 > a:not(.toc-anchor), h2 > a:not(.toc-anchor), h3 > a:not(.toc-anchor)').each((i, elm) => {
  179. let txtLink = cr(elm).text()
  180. cr(elm).replaceWith(txtLink)
  181. })
  182. // -> Re-attach blockquote styling classes to their parents
  183. cr('blockquote').each((i, elm) => {
  184. if (cr(elm).children().length > 0) {
  185. let bqLastChild = cr(elm).children().last()[0]
  186. let bqLastChildClasses = cr(bqLastChild).attr('class')
  187. if (bqLastChildClasses && bqLastChildClasses.length > 0) {
  188. cr(bqLastChild).removeAttr('class')
  189. cr(elm).addClass(bqLastChildClasses)
  190. }
  191. }
  192. })
  193. // -> Enclose content below headers
  194. cr('h2').each((i, elm) => {
  195. let subH2Content = cr(elm).nextUntil('h1, h2')
  196. cr(elm).after('<div class="indent-h2"></div>')
  197. let subH2Container = cr(elm).next('.indent-h2')
  198. _.forEach(subH2Content, (ch) => {
  199. cr(subH2Container).append(ch)
  200. })
  201. })
  202. cr('h3').each((i, elm) => {
  203. let subH3Content = cr(elm).nextUntil('h1, h2, h3')
  204. cr(elm).after('<div class="indent-h3"></div>')
  205. let subH3Container = cr(elm).next('.indent-h3')
  206. _.forEach(subH3Content, (ch) => {
  207. cr(subH3Container).append(ch)
  208. })
  209. })
  210. // Replace video links with embeds
  211. _.forEach(videoRules, (vrule) => {
  212. cr(vrule.selector).each((i, elm) => {
  213. let originLink = cr(elm).attr('href')
  214. if (vrule.regexp) {
  215. let vidMatches = originLink.match(vrule.regexp)
  216. if ((vidMatches && _.isArray(vidMatches))) {
  217. vidMatches = _.filter(vidMatches, (f) => {
  218. return f && _.isString(f)
  219. })
  220. originLink = _.last(vidMatches)
  221. }
  222. }
  223. let processedLink = _.replace(vrule.output, '{0}', originLink)
  224. cr(elm).replaceWith(processedLink)
  225. })
  226. })
  227. // Apply align-center to parent
  228. cr('img.align-center').each((i, elm) => {
  229. cr(elm).parent().addClass('align-center')
  230. cr(elm).removeClass('align-center')
  231. })
  232. output = cr.html()
  233. return output
  234. }
  235. /**
  236. * Parse meta-data tags from content
  237. *
  238. * @param {String} content Markdown content
  239. * @return {Object} Properties found in the content and their values
  240. */
  241. const parseMeta = (content) => {
  242. let commentMeta = new RegExp('<!-- ?([a-zA-Z]+):(.*)-->', 'g')
  243. let results = {}
  244. let match
  245. while ((match = commentMeta.exec(content)) !== null) {
  246. results[_.toLower(match[1])] = _.trim(match[2])
  247. }
  248. return results
  249. }
  250. /**
  251. * Strips non-text elements from Markdown content
  252. *
  253. * @param {String} content Markdown-formatted content
  254. * @return {String} Text-only version
  255. */
  256. const removeMarkdown = (content) => {
  257. return _.join(mdRemove(_.chain(content)
  258. .replace(/<!-- ?([a-zA-Z]+):(.*)-->/g, '')
  259. .replace(/```([^`]|`)+?```/g, '')
  260. .replace(/`[^`]+`/g, '')
  261. .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'), '')
  262. .deburr()
  263. .toLower()
  264. .value()
  265. ).replace(/\r?\n|\r/g, ' ').match(textRegex), ' ')
  266. }
  267. module.exports = {
  268. /**
  269. * Parse content and return all data
  270. *
  271. * @param {String} content Markdown-formatted content
  272. * @return {Object} Object containing meta, html and tree data
  273. */
  274. parse(content) {
  275. return {
  276. meta: parseMeta(content),
  277. html: parseContent(content),
  278. tree: parseTree(content)
  279. }
  280. },
  281. parseContent,
  282. parseMeta,
  283. parseTree,
  284. removeMarkdown
  285. }