refactor(import/markdown): change renderer instead of applying an uglifier

This commit is contained in:
Elian Doran 2025-03-15 21:07:02 +02:00
parent 36fa0af706
commit 30593eeeac
No known key found for this signature in database

View File

@ -1,36 +1,49 @@
"use strict";
import { parse, Renderer, type Tokens } from "marked";
import { minify as minifyHtml } from "html-minifier";
class CustomMarkdownRenderer extends Renderer {
heading(data: Tokens.Heading): string {
return super.heading(data).trimEnd();
}
paragraph(data: Tokens.Paragraph): string {
return super.paragraph(data).trimEnd();
}
code({ text, lang, escaped }: Tokens.Code): string {
if (!text) {
return "";
}
const ckEditorLanguage = getNormalizedMimeFromMarkdownLanguage(lang);
return `<pre><code class="language-${ckEditorLanguage}">${text}</code></pre>`;
}
blockquote({ tokens }: Tokens.Blockquote): string {
const body = renderer.parser.parse(tokens);
const admonitionMatch = /^<p>\[\!([A-Z]+)\]/.exec(body);
if (Array.isArray(admonitionMatch) && admonitionMatch.length === 2) {
const type = admonitionMatch[1].toLowerCase();
if (ADMONITION_TYPE_MAPPINGS[type]) {
const bodyWithoutHeader = body
.replace(/^<p>\[\!([A-Z]+)\]/, "<p>")
.replace(/^<p><\/p>/, ""); // Having a heading will generate an empty paragraph that we need to remove.
return `<aside class="admonition ${type}">\n${bodyWithoutHeader}</aside>\n`;
}
}
return `<blockquote>\n${body}</blockquote>\n`;
}
}
// Keep renderer code up to date with https://github.com/markedjs/marked/blob/master/src/Renderer.ts.
const renderer = new Renderer({ async: false });
renderer.code = ({ text, lang, escaped }: Tokens.Code) => {
if (!text) {
return "";
}
const ckEditorLanguage = getNormalizedMimeFromMarkdownLanguage(lang);
return `<pre><code class="language-${ckEditorLanguage}">${text}</code></pre>`;
};
renderer.blockquote = ({ tokens }: Tokens.Blockquote) => {
const body = renderer.parser.parse(tokens);
const admonitionMatch = /^<p>\[\!([A-Z]+)\]/.exec(body);
if (Array.isArray(admonitionMatch) && admonitionMatch.length === 2) {
const type = admonitionMatch[1].toLowerCase();
if (ADMONITION_TYPE_MAPPINGS[type]) {
const bodyWithoutHeader = body
.replace(/^<p>\[\!([A-Z]+)\]/, "<p>")
.replace(/^<p><\/p>/, ""); // Having a heading will generate an empty paragraph that we need to remove.
return `<aside class="admonition ${type}">\n${bodyWithoutHeader}</aside>\n`;
}
}
return `<blockquote>\n${body}</blockquote>\n`;
};
const renderer = new CustomMarkdownRenderer({ async: false });
import htmlSanitizer from "../html_sanitizer.js";
import importUtils from "./utils.js";
@ -46,9 +59,6 @@ function renderToHtml(content: string, title: string) {
// h1 handling needs to come before sanitization
html = importUtils.handleH1(html, title);
html = htmlSanitizer.sanitize(html);
html = minifyHtml(html, {
collapseWhitespace: true
});
return html;
}