@gramio/format
Version:
Library for formatting text for Telegram Bot API
96 lines (92 loc) • 3.02 kB
JavaScript
;
var marked = require('marked');
var index = require('../index.cjs');
function processToken(token) {
if (token.type === "blockquote") {
const tokenBlockquote = token;
return index.blockquote(index.join(tokenBlockquote.tokens, processToken, ""));
}
if (token.type === "strong" || token.type === "heading") {
const tokenStrong = token;
return index.bold(index.join(tokenStrong.tokens, processToken, ""));
}
if (token.type === "em") {
const tokenEm = token;
return index.italic(index.join(tokenEm.tokens, processToken, ""));
}
if (token.type === "link" || token.type === "image") {
const tokenLink = token;
return index.link(index.join(tokenLink.tokens, processToken, ""), tokenLink.href);
}
if (token.type === "del") {
const tokenDel = token;
return index.strikethrough(index.join(tokenDel.tokens, processToken, ""));
}
if (token.type === "list") {
const tokenList = token;
return processListToken(tokenList);
}
if (token.type === "codespan") {
const tokenCodespan = token;
return index.code(tokenCodespan.text);
}
if (token.type === "code") {
const tokenCode = token;
return index.pre(tokenCode.text, tokenCode.lang);
}
if (token.type === "text") {
const tokenText = token;
return tokenText.tokens ? index.join(tokenText.tokens, processToken, "") : index.formatSaveIndents`${tokenText.text}`;
}
if (token.type === "paragraph") {
const tokenParagraph = token;
return index.join(tokenParagraph.tokens, processToken, "");
}
return index.formatSaveIndents`${"text" in token ? token.text : token.raw}`;
}
function processListToken(tokenList) {
const isOrdered = tokenList.ordered;
const startNumber = isOrdered && typeof tokenList.start === "number" ? tokenList.start : 1;
return index.join(
tokenList.items,
(item, itemIndex) => {
const bulletOrNumber = isOrdered ? startNumber + itemIndex : "-";
return index.join(
item.tokens,
(subToken, subTokenIndex) => {
if (subTokenIndex === 0) {
return index.format`${bulletOrNumber}${isOrdered ? "." : ""} ${processToken(subToken)}`;
}
if (subToken.type === "list") {
return index.format`\n${processToken(subToken)}`;
}
return processToken(subToken);
},
""
);
},
"\n"
);
}
function workaroundForHeading(tokens) {
const result = [];
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
result.push(token);
if (token.type === "heading") {
const nextLines = token.raw.match(/\n/g);
if (nextLines?.length) {
result.push({
type: "space",
raw: "\n".repeat(nextLines.length)
});
}
}
}
return result;
}
function markdownToFormattable(markdown) {
const tokens = workaroundForHeading(marked.lexer(markdown));
return index.join(tokens, processToken, "");
}
exports.markdownToFormattable = markdownToFormattable;