renderer.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. const _ = require('lodash')
  2. const cheerio = require('cheerio')
  3. const uslug = require('uslug')
  4. const pageHelper = require('../../../helpers/page')
  5. const URL = require('url').URL
  6. /* global WIKI */
  7. module.exports = {
  8. async render() {
  9. const $ = cheerio.load(this.input, {
  10. decodeEntities: false
  11. })
  12. if ($.root().children().length < 1) {
  13. return ''
  14. }
  15. // --------------------------------
  16. // STEP: PRE
  17. // --------------------------------
  18. for (let child of _.reject(this.children, ['step', 'post'])) {
  19. const renderer = require(`../${_.kebabCase(child.key)}/renderer.js`)
  20. renderer.init($, child.config)
  21. }
  22. // --------------------------------
  23. // Detect internal / external links
  24. // --------------------------------
  25. let internalRefs = []
  26. const reservedPrefixes = /^\/[a-z]\//i
  27. const exactReservedPaths = /^\/[a-z]$/i
  28. const isHostSet = WIKI.config.host.length > 7 && WIKI.config.host !== 'http://'
  29. if (!isHostSet) {
  30. WIKI.logger.warn('Host is not set. You must set the Site Host under General in the Administration Area!')
  31. }
  32. $('a').each((i, elm) => {
  33. let href = $(elm).attr('href')
  34. // -> Ignore empty / anchor links, e-mail addresses, and telephone numbers
  35. if (!href || href.length < 1 || href.indexOf('#') === 0 ||
  36. href.indexOf('mailto:') === 0 || href.indexOf('tel:') === 0) {
  37. return
  38. }
  39. // -> Strip host from local links
  40. if (isHostSet && href.indexOf(WIKI.config.host) === 0) {
  41. href = href.replace(WIKI.config.host, '')
  42. }
  43. // -> Assign local / external tag
  44. if (href.indexOf('://') < 0) {
  45. // -> Remove trailing slash
  46. if (_.endsWith('/')) {
  47. href = href.slice(0, -1)
  48. }
  49. // -> Check for system prefix
  50. if (reservedPrefixes.test(href) || exactReservedPaths.test(href)) {
  51. $(elm).addClass(`is-system-link`)
  52. } else if (href.indexOf('.') >= 0) {
  53. $(elm).addClass(`is-asset-link`)
  54. } else {
  55. let pagePath = null
  56. // -> Add locale prefix if using namespacing
  57. if (WIKI.config.lang.namespacing) {
  58. // -> Reformat paths
  59. if (href.indexOf('/') !== 0) {
  60. if (this.config.absoluteLinks) {
  61. href = `/${this.page.localeCode}/${href}`
  62. } else {
  63. href = (this.page.path === 'home') ? `/${this.page.localeCode}/${href}` : `/${this.page.localeCode}/${this.page.path}/${href}`
  64. }
  65. } else if (href.charAt(3) !== '/') {
  66. href = `/${this.page.localeCode}${href}`
  67. }
  68. try {
  69. const parsedUrl = new URL(`http://x${href}`)
  70. pagePath = pageHelper.parsePath(parsedUrl.pathname)
  71. } catch (err) {
  72. return
  73. }
  74. } else {
  75. // -> Reformat paths
  76. if (href.indexOf('/') !== 0) {
  77. if (this.config.absoluteLinks) {
  78. href = `/${href}`
  79. } else {
  80. href = (this.page.path === 'home') ? `/${href}` : `/${this.page.path}/${href}`
  81. }
  82. }
  83. try {
  84. const parsedUrl = new URL(`http://x${href}`)
  85. pagePath = pageHelper.parsePath(parsedUrl.pathname)
  86. } catch (err) {
  87. return
  88. }
  89. }
  90. // -> Save internal references
  91. internalRefs.push({
  92. localeCode: pagePath.locale,
  93. path: pagePath.path
  94. })
  95. $(elm).addClass(`is-internal-link`)
  96. }
  97. } else {
  98. $(elm).addClass(`is-external-link`)
  99. }
  100. // -> Update element
  101. $(elm).attr('href', href)
  102. })
  103. // --------------------------------
  104. // Detect internal link states
  105. // --------------------------------
  106. const pastLinks = await this.page.$relatedQuery('links')
  107. if (internalRefs.length > 0) {
  108. // -> Find matching pages
  109. const results = await WIKI.models.pages.query().column('id', 'path', 'localeCode').where(builder => {
  110. internalRefs.forEach((ref, idx) => {
  111. if (idx < 1) {
  112. builder.where(ref)
  113. } else {
  114. builder.orWhere(ref)
  115. }
  116. })
  117. })
  118. // -> Apply tag to internal links for found pages
  119. $('a.is-internal-link').each((i, elm) => {
  120. const href = $(elm).attr('href')
  121. let hrefObj = {}
  122. try {
  123. const parsedUrl = new URL(`http://x${href}`)
  124. hrefObj = pageHelper.parsePath(parsedUrl.pathname)
  125. } catch (err) {
  126. return
  127. }
  128. if (_.some(results, r => {
  129. return r.localeCode === hrefObj.locale && r.path === hrefObj.path
  130. })) {
  131. $(elm).addClass(`is-valid-page`)
  132. } else {
  133. $(elm).addClass(`is-invalid-page`)
  134. }
  135. })
  136. // -> Add missing links
  137. const missingLinks = _.differenceWith(internalRefs, pastLinks, (nLink, pLink) => {
  138. return nLink.localeCode === pLink.localeCode && nLink.path === pLink.path
  139. })
  140. if (missingLinks.length > 0) {
  141. if (WIKI.config.db.type === 'postgres') {
  142. await WIKI.models.pageLinks.query().insert(missingLinks.map(lnk => ({
  143. pageId: this.page.id,
  144. path: lnk.path,
  145. localeCode: lnk.localeCode
  146. })))
  147. } else {
  148. for (const lnk of missingLinks) {
  149. await WIKI.models.pageLinks.query().insert({
  150. pageId: this.page.id,
  151. path: lnk.path,
  152. localeCode: lnk.localeCode
  153. })
  154. }
  155. }
  156. }
  157. }
  158. // -> Remove outdated links
  159. if (pastLinks) {
  160. const outdatedLinks = _.differenceWith(pastLinks, internalRefs, (nLink, pLink) => {
  161. return nLink.localeCode === pLink.localeCode && nLink.path === pLink.path
  162. })
  163. if (outdatedLinks.length > 0) {
  164. await WIKI.models.pageLinks.query().delete().whereIn('id', _.map(outdatedLinks, 'id'))
  165. }
  166. }
  167. // --------------------------------
  168. // Add header handles
  169. // --------------------------------
  170. let headers = []
  171. $('h1,h2,h3,h4,h5,h6').each((i, elm) => {
  172. if ($(elm).attr('id')) {
  173. return
  174. }
  175. let headerSlug = uslug($(elm).text())
  176. // -> Cannot start with a number (CSS selector limitation)
  177. if (headerSlug.match(/^\d/)) {
  178. headerSlug = `h-${headerSlug}`
  179. }
  180. // -> Make sure header is unique
  181. if (headers.indexOf(headerSlug) >= 0) {
  182. let isUnique = false
  183. let hIdx = 1
  184. while (!isUnique) {
  185. const headerSlugTry = `${headerSlug}-${hIdx}`
  186. if (headers.indexOf(headerSlugTry) < 0) {
  187. isUnique = true
  188. headerSlug = headerSlugTry
  189. }
  190. hIdx++
  191. }
  192. }
  193. // -> Add anchor
  194. $(elm).attr('id', headerSlug).addClass('toc-header')
  195. $(elm).prepend(`<a class="toc-anchor" href="#${headerSlug}">&#xB6;</a> `)
  196. headers.push(headerSlug)
  197. })
  198. let output = $.html('body').replace('<body>', '').replace('</body>', '')
  199. // --------------------------------
  200. // STEP: POST
  201. // --------------------------------
  202. for (let child of _.sortBy(_.filter(this.children, ['step', 'post']), ['order'])) {
  203. const renderer = require(`../${_.kebabCase(child.key)}/renderer.js`)
  204. output = await renderer.init(output, child.config)
  205. }
  206. return output
  207. }
  208. }