mirror of
https://github.com/TriliumNext/Notes.git
synced 2025-07-30 03:32:26 +08:00
feat(export/md): rewrite language tag to a more common syntax
This commit is contained in:
parent
ba95caaf6d
commit
eee21f3741
24
spec/services/export/md.spec.ts
Normal file
24
spec/services/export/md.spec.ts
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
import markdownExportService from "../../../src/services/export/md.js";
|
||||||
|
import { trimIndentation } from "../../support/utils.js";
|
||||||
|
|
||||||
|
describe("Markdown export", () => {
|
||||||
|
it("trims language tag for code blocks", () => {
|
||||||
|
const html = trimIndentation`\
|
||||||
|
<p>A diff:</p>
|
||||||
|
<pre><code class="language-text-x-diff">Hello
|
||||||
|
-world
|
||||||
|
+worldy
|
||||||
|
</code></pre>`;
|
||||||
|
const expected = trimIndentation`\
|
||||||
|
A diff:
|
||||||
|
|
||||||
|
\`\`\`diff
|
||||||
|
Hello
|
||||||
|
-world
|
||||||
|
+worldy
|
||||||
|
|
||||||
|
\`\`\``;
|
||||||
|
|
||||||
|
expect(markdownExportService.toMarkdown(html)).toBe(expected);
|
||||||
|
});
|
||||||
|
});
|
@ -8,12 +8,44 @@ let instance: TurndownService | null = null;
|
|||||||
function toMarkdown(content: string) {
|
function toMarkdown(content: string) {
|
||||||
if (instance === null) {
|
if (instance === null) {
|
||||||
instance = new TurndownService({ codeBlockStyle: 'fenced' });
|
instance = new TurndownService({ codeBlockStyle: 'fenced' });
|
||||||
|
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'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
})
|
||||||
instance.use(turndownPluginGfm.gfm);
|
instance.use(turndownPluginGfm.gfm);
|
||||||
}
|
}
|
||||||
|
|
||||||
return instance.turndown(content);
|
return instance.turndown(content);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function rewriteLanguageTag(source: string) {
|
||||||
|
return source
|
||||||
|
.split("-")
|
||||||
|
.at(-1);
|
||||||
|
}
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
toMarkdown
|
toMarkdown
|
||||||
};
|
};
|
||||||
|
Loading…
x
Reference in New Issue
Block a user