renderer.js 7.4 KB

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