renderer.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. $(elm).attr('target', '_blank')
  100. }
  101. // -> Update element
  102. $(elm).attr('href', href)
  103. })
  104. // --------------------------------
  105. // Detect internal link states
  106. // --------------------------------
  107. const pastLinks = await this.page.$relatedQuery('links')
  108. if (internalRefs.length > 0) {
  109. // -> Find matching pages
  110. const results = await WIKI.models.pages.query().column('id', 'path', 'localeCode').where(builder => {
  111. internalRefs.forEach((ref, idx) => {
  112. if (idx < 1) {
  113. builder.where(ref)
  114. } else {
  115. builder.orWhere(ref)
  116. }
  117. })
  118. })
  119. // -> Apply tag to internal links for found pages
  120. $('a.is-internal-link').each((i, elm) => {
  121. const href = $(elm).attr('href')
  122. let hrefObj = {}
  123. try {
  124. const parsedUrl = new URL(`http://x${href}`)
  125. hrefObj = pageHelper.parsePath(parsedUrl.pathname)
  126. } catch (err) {
  127. return
  128. }
  129. if (_.some(results, r => {
  130. return r.localeCode === hrefObj.locale && r.path === hrefObj.path
  131. })) {
  132. $(elm).addClass(`is-valid-page`)
  133. } else {
  134. $(elm).addClass(`is-invalid-page`)
  135. }
  136. })
  137. // -> Add missing links
  138. const missingLinks = _.differenceWith(internalRefs, pastLinks, (nLink, pLink) => {
  139. return nLink.localeCode === pLink.localeCode && nLink.path === pLink.path
  140. })
  141. if (missingLinks.length > 0) {
  142. if (WIKI.config.db.type === 'postgres') {
  143. await WIKI.models.pageLinks.query().insert(missingLinks.map(lnk => ({
  144. pageId: this.page.id,
  145. path: lnk.path,
  146. localeCode: lnk.localeCode
  147. })))
  148. } else {
  149. for (const lnk of missingLinks) {
  150. await WIKI.models.pageLinks.query().insert({
  151. pageId: this.page.id,
  152. path: lnk.path,
  153. localeCode: lnk.localeCode
  154. })
  155. }
  156. }
  157. }
  158. }
  159. // -> Remove outdated links
  160. if (pastLinks) {
  161. const outdatedLinks = _.differenceWith(pastLinks, internalRefs, (nLink, pLink) => {
  162. return nLink.localeCode === pLink.localeCode && nLink.path === pLink.path
  163. })
  164. if (outdatedLinks.length > 0) {
  165. await WIKI.models.pageLinks.query().delete().whereIn('id', _.map(outdatedLinks, 'id'))
  166. }
  167. }
  168. // --------------------------------
  169. // Add header handles
  170. // --------------------------------
  171. let headers = []
  172. $('h1,h2,h3,h4,h5,h6').each((i, elm) => {
  173. if ($(elm).attr('id')) {
  174. return
  175. }
  176. let headerSlug = uslug($(elm).text())
  177. // -> Cannot start with a number (CSS selector limitation)
  178. if (headerSlug.match(/^\d/)) {
  179. headerSlug = `h-${headerSlug}`
  180. }
  181. // -> Make sure header is unique
  182. if (headers.indexOf(headerSlug) >= 0) {
  183. let isUnique = false
  184. let hIdx = 1
  185. while (!isUnique) {
  186. const headerSlugTry = `${headerSlug}-${hIdx}`
  187. if (headers.indexOf(headerSlugTry) < 0) {
  188. isUnique = true
  189. headerSlug = headerSlugTry
  190. }
  191. hIdx++
  192. }
  193. }
  194. // -> Add anchor
  195. $(elm).attr('id', headerSlug).addClass('toc-header')
  196. $(elm).prepend(`<a class="toc-anchor" href="#${headerSlug}">&#xB6;</a> `)
  197. headers.push(headerSlug)
  198. })
  199. let output = $.html('body').replace('<body>', '').replace('</body>', '')
  200. // --------------------------------
  201. // STEP: POST
  202. // --------------------------------
  203. for (let child of _.sortBy(_.filter(this.children, ['step', 'post']), ['order'])) {
  204. const renderer = require(`../${_.kebabCase(child.key)}/renderer.js`)
  205. output = await renderer.init(output, child.config)
  206. }
  207. return output
  208. }
  209. }