2021-08-06 14:46:16 +02:00
|
|
|
import fs from 'fs'
|
|
|
|
import njk from 'nunjucks'
|
|
|
|
import { JSDOM } from 'jsdom'
|
|
|
|
import { parseExternalContext } from './externalContext.js'
|
|
|
|
|
|
|
|
// Load in config
|
|
|
|
const ConfigFile = fs.readFileSync('./config.json')
|
|
|
|
const Config = JSON.parse(ConfigFile)
|
|
|
|
|
|
|
|
function generateToc(dom) {
|
|
|
|
const tocAnchors = dom.window.document.querySelectorAll(".toc-anchor")
|
|
|
|
let tocLinks = []
|
|
|
|
|
|
|
|
// This basically creates a proper link for the ToC. :)))
|
|
|
|
tocAnchors.forEach(anchor => tocLinks.push(`<a href="#${anchor.name}" class="${anchor.classList[1].replace("-anchor", "")}">${anchor.getAttribute('data-orig-text')}</a>`))
|
|
|
|
|
|
|
|
return tocLinks
|
|
|
|
}
|
|
|
|
|
|
|
|
function generateContext(renderedNjk, externalContext = undefined) {
|
|
|
|
const dom = new JSDOM(renderedNjk)
|
|
|
|
|
|
|
|
return {
|
|
|
|
serverName: Config.serverName,
|
|
|
|
tocLinks: generateToc(dom),
|
|
|
|
externalMeta: externalContext ? parseExternalContext(externalContext) : undefined
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function njkRenderer(path) {
|
|
|
|
const njkFile = fs.readFileSync(path).toString()
|
|
|
|
const renderedNjk = njk.renderString(njkFile)
|
|
|
|
|
|
|
|
const context = generateContext(renderedNjk)
|
|
|
|
|
|
|
|
return njk.renderString(njkFile, context)
|
|
|
|
}
|
|
|
|
|
|
|
|
export function mdRenderer(path) {
|
|
|
|
// Load in the njk template and markdown
|
|
|
|
const njkFile = fs.readFileSync(`${Config.contentDir}/templates/external_md.njk`).toString()
|
|
|
|
const externalMarkdownFile = fs.readFileSync(path).toString()
|
|
|
|
|
|
|
|
// Separate the actual markdown from potential 'externalContext'
|
2021-08-07 10:16:13 +02:00
|
|
|
const externalMarkdown = externalMarkdownFile.replace(/^%%-\n[\S\s]*-%%\n/, "").replace(/```\w*[\s\S]*?```/g, match => match.replace(/ /g, "•"))
|
2021-08-06 14:46:16 +02:00
|
|
|
const externalContext = externalMarkdownFile.match(/^%%-\n[\S\s]*-%%\n/)[0]
|
|
|
|
|
|
|
|
const renderedNjk = njk.renderString(njkFile, { externalMarkdown })
|
|
|
|
|
|
|
|
let context = generateContext(renderedNjk, externalContext)
|
|
|
|
context.externalMarkdown = externalMarkdown
|
|
|
|
|
|
|
|
return njk.renderString(njkFile, context)
|
|
|
|
}
|