renderer.js 7.0 KB

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