renderer.js 8.33 KB
Newer Older
1 2
const _ = require('lodash')
const cheerio = require('cheerio')
3
const uslug = require('uslug')
4 5
const pageHelper = require('../../../helpers/page')
const URL = require('url').URL
6

Nick's avatar
Nick committed
7 8
/* global WIKI */

9 10
module.exports = {
  async render() {
11
    const $ = cheerio.load(this.input, {
12
      decodeEntities: true
13
    })
14 15 16 17 18

    if ($.root().children().length < 1) {
      return ''
    }

19 20 21 22 23
    // --------------------------------
    // STEP: PRE
    // --------------------------------

    for (let child of _.reject(this.children, ['step', 'post'])) {
24 25 26 27
      const renderer = require(`../${_.kebabCase(child.key)}/renderer.js`)
      renderer.init($, child.config)
    }

Nick's avatar
Nick committed
28 29 30 31 32
    // --------------------------------
    // Detect internal / external links
    // --------------------------------

    let internalRefs = []
33 34
    const reservedPrefixes = /^\/[a-z]\//i
    const exactReservedPaths = /^\/[a-z]$/i
Nick's avatar
Nick committed
35 36 37 38 39 40 41 42 43

    const isHostSet = WIKI.config.host.length > 7 && WIKI.config.host !== 'http://'
    if (!isHostSet) {
      WIKI.logger.warn('Host is not set. You must set the Site Host under General in the Administration Area!')
    }

    $('a').each((i, elm) => {
      let href = $(elm).attr('href')

44 45 46
      // -> Ignore empty / anchor links, e-mail addresses, and telephone numbers
      if (!href || href.length < 1 || href.indexOf('#') === 0 ||
        href.indexOf('mailto:') === 0 || href.indexOf('tel:') === 0) {
Nick's avatar
Nick committed
47 48 49 50
        return
      }

      // -> Strip host from local links
51 52
      if (isHostSet && href.indexOf(WIKI.config.host) === 0) {
        href = href.replace(WIKI.config.host, '')
Nick's avatar
Nick committed
53 54 55 56 57 58 59 60 61 62
      }

      // -> Assign local / external tag
      if (href.indexOf('://') < 0) {
        // -> Remove trailing slash
        if (_.endsWith('/')) {
          href = href.slice(0, -1)
        }

        // -> Check for system prefix
63 64 65 66 67
        if (reservedPrefixes.test(href) || exactReservedPaths.test(href)) {
          $(elm).addClass(`is-system-link`)
        } else if (href.indexOf('.') >= 0) {
          $(elm).addClass(`is-asset-link`)
        } else {
68 69 70 71 72 73
          let pagePath = null

          // -> Add locale prefix if using namespacing
          if (WIKI.config.lang.namespacing) {
            // -> Reformat paths
            if (href.indexOf('/') !== 0) {
74 75 76 77 78
              if (this.config.absoluteLinks) {
                href = `/${this.page.localeCode}/${href}`
              } else {
                href = (this.page.path === 'home') ? `/${this.page.localeCode}/${href}` : `/${this.page.localeCode}/${this.page.path}/${href}`
              }
79 80 81 82 83 84 85 86 87 88 89 90 91
            } else if (href.charAt(3) !== '/') {
              href = `/${this.page.localeCode}${href}`
            }

            try {
              const parsedUrl = new URL(`http://x${href}`)
              pagePath = pageHelper.parsePath(parsedUrl.pathname)
            } catch (err) {
              return
            }
          } else {
            // -> Reformat paths
            if (href.indexOf('/') !== 0) {
92 93 94 95 96
              if (this.config.absoluteLinks) {
                href = `/${href}`
              } else {
                href = (this.page.path === 'home') ? `/${href}` : `/${this.page.path}/${href}`
              }
97 98 99 100 101 102 103 104
            }

            try {
              const parsedUrl = new URL(`http://x${href}`)
              pagePath = pageHelper.parsePath(parsedUrl.pathname)
            } catch (err) {
              return
            }
Nick's avatar
Nick committed
105 106 107
          }
          // -> Save internal references
          internalRefs.push({
108 109
            localeCode: pagePath.locale,
            path: pagePath.path
Nick's avatar
Nick committed
110
          })
111 112

          $(elm).addClass(`is-internal-link`)
Nick's avatar
Nick committed
113 114 115
        }
      } else {
        $(elm).addClass(`is-external-link`)
116 117
        if (this.config.openExternalLinkNewTab) {
          $(elm).attr('target', '_blank')
118
          $(elm).attr('rel', this.config.relAttributeExternalLink)
119
        }
Nick's avatar
Nick committed
120 121 122 123 124 125 126 127 128 129
      }

      // -> Update element
      $(elm).attr('href', href)
    })

    // --------------------------------
    // Detect internal link states
    // --------------------------------

Nick's avatar
Nick committed
130 131
    const pastLinks = await this.page.$relatedQuery('links')

Nick's avatar
Nick committed
132 133
    if (internalRefs.length > 0) {
      // -> Find matching pages
Nick's avatar
Nick committed
134
      const results = await WIKI.models.pages.query().column('id', 'path', 'localeCode').where(builder => {
Nick's avatar
Nick committed
135 136 137 138 139 140 141 142 143 144 145 146
        internalRefs.forEach((ref, idx) => {
          if (idx < 1) {
            builder.where(ref)
          } else {
            builder.orWhere(ref)
          }
        })
      })

      // -> Apply tag to internal links for found pages
      $('a.is-internal-link').each((i, elm) => {
        const href = $(elm).attr('href')
147 148 149 150 151 152
        let hrefObj = {}
        try {
          const parsedUrl = new URL(`http://x${href}`)
          hrefObj = pageHelper.parsePath(parsedUrl.pathname)
        } catch (err) {
          return
Nick's avatar
Nick committed
153 154
        }
        if (_.some(results, r => {
155
          return r.localeCode === hrefObj.locale && r.path === hrefObj.path
Nick's avatar
Nick committed
156 157 158 159 160 161
        })) {
          $(elm).addClass(`is-valid-page`)
        } else {
          $(elm).addClass(`is-invalid-page`)
        }
      })
Nick's avatar
Nick committed
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193

      // -> Add missing links
      const missingLinks = _.differenceWith(internalRefs, pastLinks, (nLink, pLink) => {
        return nLink.localeCode === pLink.localeCode && nLink.path === pLink.path
      })
      if (missingLinks.length > 0) {
        if (WIKI.config.db.type === 'postgres') {
          await WIKI.models.pageLinks.query().insert(missingLinks.map(lnk => ({
            pageId: this.page.id,
            path: lnk.path,
            localeCode: lnk.localeCode
          })))
        } else {
          for (const lnk of missingLinks) {
            await WIKI.models.pageLinks.query().insert({
              pageId: this.page.id,
              path: lnk.path,
              localeCode: lnk.localeCode
            })
          }
        }
      }
    }

    // -> Remove outdated links
    if (pastLinks) {
      const outdatedLinks = _.differenceWith(pastLinks, internalRefs, (nLink, pLink) => {
        return nLink.localeCode === pLink.localeCode && nLink.path === pLink.path
      })
      if (outdatedLinks.length > 0) {
        await WIKI.models.pageLinks.query().delete().whereIn('id', _.map(outdatedLinks, 'id'))
      }
Nick's avatar
Nick committed
194 195
    }

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
    // --------------------------------
    // Add header handles
    // --------------------------------

    let headers = []
    $('h1,h2,h3,h4,h5,h6').each((i, elm) => {
      if ($(elm).attr('id')) {
        return
      }
      let headerSlug = uslug($(elm).text())

      // -> Cannot start with a number (CSS selector limitation)
      if (headerSlug.match(/^\d/)) {
        headerSlug = `h-${headerSlug}`
      }

      // -> Make sure header is unique
      if (headers.indexOf(headerSlug) >= 0) {
        let isUnique = false
        let hIdx = 1
        while (!isUnique) {
          const headerSlugTry = `${headerSlug}-${hIdx}`
          if (headers.indexOf(headerSlugTry) < 0) {
            isUnique = true
            headerSlug = headerSlugTry
          }
          hIdx++
        }
      }

      // -> Add anchor
      $(elm).attr('id', headerSlug).addClass('toc-header')
      $(elm).prepend(`<a class="toc-anchor" href="#${headerSlug}">&#xB6;</a> `)

      headers.push(headerSlug)
    })

233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    // --------------------------------
    // Escape mustache expresions
    // --------------------------------

    function iterateMustacheNode (node) {
      const list = $(node).contents().toArray()
      list.forEach(item => {
        if (item.type === 'text') {
          const rawText = $(item).text()
          if (rawText.indexOf('{{') >= 0 && rawText.indexOf('}}') > 1) {
            $(item).parent().attr('v-pre', true)
          }
        } else {
          iterateMustacheNode(item)
        }
      })
    }
    iterateMustacheNode($.root())
251 252 253 254 255

    // --------------------------------
    // STEP: POST
    // --------------------------------

256 257
    let output = decodeEscape($.html('body').replace('<body>', '').replace('</body>', ''))

258
    for (let child of _.sortBy(_.filter(this.children, ['step', 'post']), ['order'])) {
259
      const renderer = require(`../${_.kebabCase(child.key)}/renderer.js`)
260
      output = await renderer.init(output, child.config)
261 262 263
    }

    return output
264 265
  }
}
266 267 268 269 270 271 272 273 274 275 276

function decodeEscape (string) {
  return string.replace(/&#x([0-9a-f]{1,6});/ig, (entity, code) => {
    code = parseInt(code, 16)

    // Don't unescape ASCII characters, assuming they're encoded for a good reason
    if (code < 0x80) return entity

    return String.fromCodePoint(code)
  })
}