Files
mantra.press/lib/markdown-producer/index.js

105 lines
3.2 KiB
JavaScript

const e = require('express');
const Token = require('markdown-it/lib/token');
const md = require("markdown-it")().disable(['link'])
const produceTranslatedChapterOutput = (translationChapter) => {
// TODO: Check that translationChapter has all the required fields...
return md.parse(
translationChapter.chapter.originalText
).map(token => {
if (token.content) {
const translationChunk = translationChapter.translationChunks.find(tc => {
return tc.text == token.content
})
if (translationChunk && translationChunk.translation) {
token.content = translationChunk.translation.text
if (token.children.length == 1) {
token.children[0].content = translationChunk.translation.text
} else {
const newChild = new Token(
"text"
)
newChild.content = translationChunk.translation.text
token.children = [
newChild
]
}
}
}
return token
})
}
module.exports.produceMarkdownString = (translationChapter) => {
const tokens = produceTranslatedChapterOutput(translationChapter)
return tokens.reduce(
(accumulator, token, index) => {
if (token.type == "list_item_close") {
return accumulator
}
if (token.type == "ordered_list_open" || token.type == "bullet_list_open") {
return accumulator
}
if (token.type == "bullet_list_close" || token.type == "ordered_list_close") {
return accumulator + "\n"
}
if (token.type == "paragraph_close") {
if (token.level == 0) {
return accumulator + "\n\n"
} else {
return accumulator + "\n"
}
}
if (token.type == "blockquote_open") {
return accumulator + `${token.info}${token.markup} `
}
if (token.type == "blockquote_close") {
// Only if the next token is a blockquote?
if (tokens.length > (index+1) && tokens.at(index+1).type == "blockquote_open") {
return accumulator + `${token.info}${token.markup}\n`
} else {
return accumulator + `\n`
}
}
if (token.type == "list_item_open") {
return accumulator + `${token.info}${token.markup} `
}
if (token.type == "inline") {
return accumulator + token.content
}
if (token.type == "heading_open") {
return `${accumulator}${token.markup} `
}
if (token.type == "heading_close") {
return `${accumulator}\n`
}
return accumulator + token.markup
},
""
)
}
module.exports.produceHtml = (translationChapter) => {
const tokens = produceTranslatedChapterOutput(translationChapter)
return md.renderer.render(
tokens,
{}
)
}