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.

92 lines
2.5 KiB

  1. const _ = require('lodash')
  2. const cheerio = require('cheerio')
  3. /* global WIKI */
  4. module.exports = async (pageId) => {
  5. WIKI.logger.info(`Rendering page ID ${pageId}...`)
  6. try {
  7. WIKI.models = require('../core/db').init()
  8. const page = await WIKI.models.pages.getPageFromDb(pageId)
  9. if (!page) {
  10. throw new Error('Invalid Page Id')
  11. }
  12. await WIKI.models.renderers.fetchDefinitions()
  13. const pipeline = await WIKI.models.renderers.getRenderingPipeline(page.contentType)
  14. let output = page.content
  15. if (_.isEmpty(page.content)) {
  16. await WIKI.models.knex.destroy()
  17. WIKI.logger.warn(`Failed to render page ID ${pageId} because content was empty: [ FAILED ]`)
  18. }
  19. for (let core of pipeline) {
  20. const renderer = require(`../modules/rendering/${_.kebabCase(core.key)}/renderer.js`)
  21. output = await renderer.render.call({
  22. config: core.config,
  23. children: core.children,
  24. page: page,
  25. input: output
  26. })
  27. }
  28. // Parse TOC
  29. const $ = cheerio.load(output)
  30. let isStrict = $('h1').length > 0 // <- Allows for documents using H2 as top level
  31. let toc = { root: [] }
  32. $('h1,h2,h3,h4,h5,h6').each((idx, el) => {
  33. const depth = _.toSafeInteger(el.name.substring(1)) - (isStrict ? 1 : 2)
  34. let leafPathError = false
  35. const leafPath = _.reduce(_.times(depth), (curPath, curIdx) => {
  36. if (_.has(toc, curPath)) {
  37. const lastLeafIdx = _.get(toc, curPath).length - 1
  38. if (lastLeafIdx >= 0) {
  39. curPath = `${curPath}[${lastLeafIdx}].children`
  40. } else {
  41. leafPathError = true
  42. }
  43. }
  44. return curPath
  45. }, 'root')
  46. if (leafPathError) { return }
  47. const leafSlug = $('.toc-anchor', el).first().attr('href')
  48. $('.toc-anchor', el).remove()
  49. _.get(toc, leafPath).push({
  50. title: _.trim($(el).text()),
  51. anchor: leafSlug,
  52. children: []
  53. })
  54. })
  55. // Save to DB
  56. await WIKI.models.pages.query()
  57. .patch({
  58. render: output,
  59. toc: JSON.stringify(toc.root)
  60. })
  61. .where('id', pageId)
  62. // Save to cache
  63. await WIKI.models.pages.savePageToCache({
  64. ...page,
  65. render: output,
  66. toc: JSON.stringify(toc.root)
  67. })
  68. await WIKI.models.knex.destroy()
  69. WIKI.logger.info(`Rendering page ID ${pageId}: [ COMPLETED ]`)
  70. } catch (err) {
  71. WIKI.logger.error(`Rendering page ID ${pageId}: [ FAILED ]`)
  72. WIKI.logger.error(err.message)
  73. }
  74. }