Files
zhdiary/plugins/custom-render/plugin.js
T
2019-08-14 08:40:35 +07:00

57 lines
1.4 KiB
JavaScript

const pug = require("pug");
const showdown = require("showdown");
const h = require("hyperscript");
class Markdown {
constructor() {
this.converter = new showdown.Converter({
parseImgDimensions: true
});
this.converter.setFlavor("github");
this.converter.addExtension({
type: "lang",
filter(text) {
const rowRegex = /(?:(?:^|\r?\n)(?:\| )?(?:(?:.* \| )+.+)*(?:.* \| )+.+(?: \|)?(?:$|\r?\n))+/m;
text = text.replace(rowRegex, (p0) => {
return h("table.table", p0.trim().split("\n").map((pi) => {
pi = pi.trim().replace(/^|/, "").replace(/|$/, "")
return h("tr", pi.split(" | ").map((x) => x.trim()).map((qi) => {
return h("td", qi);
}))
})).outerHTML;
});
return text;
}
})
}
md2html(md) {
return this.converter.makeHtml(md);
}
}
const md = new Markdown();
module.exports = {
Markdown,
apply() {
cogear.on("preload.page.parse", (page) => {
if (page.format === ".pug") {
page.__content = pug.compile(page.__content || "", {
filters: {
markdown: (text) => {
return md.md2html(text)
}
}
})()
page.format = ".html";
} else if (page.format === ".md") {
page.__content = md.md2html(page.__content || "")
page.format = ".html";
}
})
}
}