Skip to content

Instantly share code, notes, and snippets.

@mattlenz
Last active November 21, 2020 19:26
Show Gist options
  • Save mattlenz/78154ed23c9318df587126dc7fed1293 to your computer and use it in GitHub Desktop.
Save mattlenz/78154ed23c9318df587126dc7fed1293 to your computer and use it in GitHub Desktop.
Kirbytext JS parser
const md = require('markdown-it')({
html: true,
linkify: true,
typographer: true,
breaks: true,
})
.use(require('markdown-it-deflist'))
.use(require('markdown-it-footnote'))
function kirbytext(text, page) {
if(!text) return ''
let html = text
const pattern = /\((\w+)\:[^\)]*\)/
function parseKirbytag(kirbytag) {
const tag = kirbytag.match(/^\((\w+)\:/)[1]
const stripped = kirbytag.replace(/^\(/, '').replace(/\)$/, '')
const values = stripped.split(/\w+\: /).slice(1).map(v => v.trim())
const keys = stripped.match(/(\w+)\: /g).map(m => m.replace(/\: $/, ''))
const attrs = keys.reduce((acc, key, i) => {
acc[key] = values[i]
return acc
}, {})
if(tag === 'link') {
attrs.link = `${attrs.link}`
}
return {
tag, attrs
}
}
function nextKirbytag() {
const matches = html.match(pattern)
if(matches && matches.length) {
const match = matches[0]
let replacement = ''
const { tag, attrs } = parseKirbytag(match)
if(tag === 'link') {
replacement = `<a href="${attrs.link}">${attrs.text}</a>`
}
if(tag === 'image') {
replacement = `<figure${attrs.class ? ` class="${attrs.class}"` : ''}><img src="${attrs.image}" />${attrs.caption ? `<figcaption>${attrs.caption}</figcaption>` : ''}</figure>`
}
html = html.replace(pattern, replacement)
nextKirbytag()
}
return html
}
nextKirbytag()
return html
}
function postprocess(html) {
function fixFnRef(html) {
return html.replace(/\>\[(\d)\]\<\/a\>/, '>$1</a>')
}
return fixFnRef(html)
}
function markdown(text, page) {
return postprocess(md.render(kirbytext(text, page)))
}
mocule.exports = (text, page) => markdown(text, page)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment