Skip to content

Commit

Permalink
feat: support custom renderers
Browse files Browse the repository at this point in the history
  • Loading branch information
marvinhagemeister committed Oct 12, 2023
1 parent 9a41d36 commit cd98fec
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
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/[email protected]/testing/asserts.ts";
import { DOMParser } from "https://deno.land/x/[email protected]/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);
},
);

0 comments on commit cd98fec

Please sign in to comment.