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.

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