2019-09-30 20:56:32 +02:00
|
|
|
"use strict";
|
|
|
|
|
2024-07-18 21:37:45 +03:00
|
|
|
import TurndownService from "turndown";
|
|
|
|
import turndownPluginGfm from "joplin-turndown-plugin-gfm";
|
2019-09-30 20:56:32 +02:00
|
|
|
|
2024-02-19 21:59:40 +02:00
|
|
|
let instance: TurndownService | null = null;
|
2019-09-30 20:56:32 +02:00
|
|
|
|
2024-02-19 21:59:40 +02:00
|
|
|
function toMarkdown(content: string) {
|
2019-09-30 20:56:32 +02:00
|
|
|
if (instance === null) {
|
2022-07-06 21:31:11 +02:00
|
|
|
instance = new TurndownService({ codeBlockStyle: 'fenced' });
|
2024-12-17 23:35:08 +02:00
|
|
|
instance.addRule('fencedCodeBlock', {
|
|
|
|
filter: function (node, options) {
|
|
|
|
return (
|
|
|
|
options.codeBlockStyle === 'fenced' &&
|
|
|
|
node.nodeName === 'PRE' &&
|
|
|
|
node.firstChild !== null &&
|
|
|
|
node.firstChild.nodeName === 'CODE'
|
|
|
|
)
|
|
|
|
},
|
|
|
|
|
|
|
|
replacement: function (content, node, options) {
|
|
|
|
if (!node.firstChild || !("getAttribute" in node.firstChild) || typeof node.firstChild.getAttribute !== "function") {
|
|
|
|
return content;
|
|
|
|
}
|
|
|
|
|
|
|
|
var className = node.firstChild.getAttribute('class') || ''
|
|
|
|
var language = (className.match(/language-(\S+)/) || [null, ''])[1];
|
|
|
|
language = rewriteLanguageTag(language);
|
|
|
|
|
|
|
|
return (
|
|
|
|
'\n\n' + options.fence + language + '\n' +
|
|
|
|
node.firstChild.textContent +
|
|
|
|
'\n' + options.fence + '\n\n'
|
|
|
|
)
|
|
|
|
}
|
|
|
|
})
|
2019-09-30 20:56:32 +02:00
|
|
|
instance.use(turndownPluginGfm.gfm);
|
|
|
|
}
|
|
|
|
|
|
|
|
return instance.turndown(content);
|
|
|
|
}
|
|
|
|
|
2024-12-17 23:35:08 +02:00
|
|
|
function rewriteLanguageTag(source: string) {
|
2024-12-17 23:40:39 +02:00
|
|
|
if (source === "text-x-trilium-auto") {
|
|
|
|
return "";
|
|
|
|
}
|
|
|
|
|
2024-12-17 23:35:08 +02:00
|
|
|
return source
|
|
|
|
.split("-")
|
|
|
|
.at(-1);
|
|
|
|
}
|
|
|
|
|
2024-07-18 21:42:44 +03:00
|
|
|
export default {
|
2019-09-30 20:56:32 +02:00
|
|
|
toMarkdown
|
2021-02-20 20:10:45 +01:00
|
|
|
};
|