Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support custom renderers #80

Merged
merged 1 commit into from
Oct 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export { CSS, KATEX_CSS, Marked };

Marked.marked.use(gfmHeadingId());

class Renderer extends Marked.Renderer {
export class Renderer extends Marked.Renderer {
allowMath: boolean;

constructor(options: Marked.marked.MarkedOptions & RenderOptions = {}) {
Expand Down Expand Up @@ -104,6 +104,7 @@ export interface RenderOptions {
allowIframes?: boolean;
allowMath?: boolean;
disableHtmlSanitization?: boolean;
renderer?: Renderer;
}

export function render(markdown: string, opts: RenderOptions = {}): string {
Expand All @@ -117,7 +118,7 @@ export function render(markdown: string, opts: RenderOptions = {}): string {
baseUrl: opts.baseUrl,
gfm: true,
mangle: false,
renderer: new Renderer(opts),
renderer: opts.renderer ? opts.renderer : new Renderer(opts),
};

const html = opts.inline
Expand Down
19 changes: 18 additions & 1 deletion test/test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { assertEquals } from "https://deno.land/std@0.178.0/testing/asserts.ts";
import { DOMParser } from "https://deno.land/x/deno_dom@v0.1.35-alpha/deno-dom-wasm.ts";
import { render } from "../mod.ts";
import { render, Renderer } from "../mod.ts";

Deno.test("Basic markdown", async () => {
const markdown = await Deno.readTextFile("./test/fixtures/basic.md");
Expand Down Expand Up @@ -79,3 +79,20 @@ Deno.test(
assertEquals(html, expected);
},
);

Deno.test(
"custom renderer",
() => {
const markdown = `# hello world`;
const expected = `<h1 id="custom-renderer">hello world</h1>`;

class CustomRenderer extends Renderer {
heading(text: string, level: 1 | 2 | 3 | 4 | 5 | 6): string {
return `<h${level} id="custom-renderer">${text}</h${level}>`;
}
}

const html = render(markdown, { renderer: new CustomRenderer({}) });
assertEquals(html, expected);
},
);