37 lines
1.1 KiB
TypeScript
37 lines
1.1 KiB
TypeScript
import { Marked } from 'marked';
|
|
|
|
const marked = new Marked({ breaks: true, gfm: true });
|
|
|
|
const CODE_OPEN = '';
|
|
const CODE_CLOSE = '';
|
|
|
|
export function processLatex(text: string): string {
|
|
const placeholders: string[] = [];
|
|
const stash = (match: string) => {
|
|
const token = `${CODE_OPEN}${placeholders.length}${CODE_CLOSE}`;
|
|
placeholders.push(match);
|
|
return token;
|
|
};
|
|
|
|
const protectedText = text.replace(/```[\s\S]*?```/g, stash).replace(/`[^`\n]*`/g, stash);
|
|
|
|
const rendered = protectedText
|
|
.replace(/\$\$(.*?)\$\$/gs, (_, tex) => {
|
|
const encoded = encodeURIComponent(tex.trim());
|
|
return `<img src="/service/latex?tex=${encoded}&display=1" alt="LaTeX" class="block my-1 max-h-12" />`;
|
|
})
|
|
.replace(/\$(.+?)\$/g, (_, tex) => {
|
|
const encoded = encodeURIComponent(tex.trim());
|
|
return `<img src="/service/latex?tex=${encoded}" alt="LaTeX" class="inline-block align-middle max-h-4" />`;
|
|
});
|
|
|
|
return rendered.replace(
|
|
new RegExp(`${CODE_OPEN}(\\d+)${CODE_CLOSE}`, 'g'),
|
|
(_, i) => placeholders[Number(i)]
|
|
);
|
|
}
|
|
|
|
export function processContent(text: string): string {
|
|
return marked.parse(processLatex(text)) as string;
|
|
}
|