renderer.js 7.3 KB

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