Instantly share code, notes, and snippets.

Embed
What would you like to do?
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