54 lines
1.8 KiB
JavaScript
54 lines
1.8 KiB
JavaScript
|
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'
|
||
|
const externalMarkdown = externalMarkdownFile.replace(/^%%-\n[\S\s]*-%%\n/, "")
|
||
|
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)
|
||
|
}
|