@awesome-fe/translate
Version:
Translation utils
93 lines • 4.09 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MarkdownExporter = void 0;
const exporter_1 = require("./exporter");
const unistVisit = require("unist-util-visit");
const markdown_1 = require("../dom/unified/markdown");
const common_1 = require("../dom/common");
class MarkdownExporter extends exporter_1.Exporter {
exportContent(content, options) {
switch (options.format) {
case 'auto':
case 'markdown':
return markdown_1.markdown.stringify(this.buildMarkdownDom(content, options.mono));
case 'html':
return markdown_1.markdown.toHtml(this.buildMarkdownDom(content, options.mono));
default:
return;
}
}
buildMarkdownDom(content, mono) {
const dom = markdown_1.markdown.parse(content);
unistVisit(dom, 'text', (node) => {
node.value = node.value.replace(/\n/g, ' ');
});
if (mono) {
this.removeOriginals(dom);
}
return dom;
}
removeOriginals(dom) {
// 从翻译对中移除原文
dom.children = dom.children.filter((node, index) => {
const next = dom.children[index + 1];
// 如果是段落、标题、表行,要判断是否包含
switch (node.type) {
case 'paragraph':
case 'heading':
case 'tableRow':
// 如果是最后一个,一定包含
if (!next) {
return true;
}
// 翻译对一定是成对出现的,如果类型不一样,就一定不是翻译对
if (node.type !== next.type) {
return true;
}
// 如果本段是中文或下段不是中文,则保留本段
const text = markdown_1.markdown.stringify({ ...node, type: 'root' });
const nextText = markdown_1.markdown.stringify({ ...next, type: 'root' });
return (0, common_1.containsChinese)(text) || !(0, common_1.containsChinese)(nextText);
case 'blockquote':
case 'table':
case 'list':
case 'listItem':
// 这几个类型递归处理
this.removeOriginals(node);
return true;
case 'code':
// 所有连续的两行代码,如果在注释前的内容都完全一样,并且第一行注释不包含中文,而第二行注释包含中文,则保留第二行
const code = node;
switch (code.lang) {
case 'console':
case 'text':
return true;
case 'html':
case 'xml':
case 'svg':
code.value = code.value.replace(/^(.*)<!--(?!.*\p{sc=Han}).*-->\n(\1<!--(?=.*\p{sc=Han}).*-->)$/gum, '$2');
return true;
case 'toml':
case 'shell':
case 'sh':
case 'bash':
case 'python':
case 'ruby':
case 'perl':
case 'php':
code.value = code.value.replace(/^(.*)#(?!.*\p{sc=Han}).*\n(\1#(?=.*\p{sc=Han}).*)$/gum, '$2');
return true;
default:
code.value = code.value.replace(/^(.*)\/\/(?!.*\p{sc=Han}).*\n(\1\/\/(?=.*\p{sc=Han}).*)$/gum, '$2');
return true;
}
default:
// 否则,一定包含
return true;
}
});
return dom;
}
}
exports.MarkdownExporter = MarkdownExporter;
//# sourceMappingURL=markdown-exporter.js.map