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.

78 lines
2.1 KiB

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