Skip to content

Commit

Permalink
Fix: don't reuse GithubSlugger across different Renderers (#97)
Browse files Browse the repository at this point in the history
  • Loading branch information
littledivy authored Jan 25, 2024
1 parent b9f7352 commit 65c0a74
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
6 changes: 3 additions & 3 deletions mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,24 @@ export { CSS, KATEX_CSS, Marked };
Marked.marked.use(markedAlert());
Marked.marked.use(gfmHeadingId());

const slugger = new GitHubSlugger();

export class Renderer extends Marked.Renderer {
allowMath: boolean;
baseUrl: string | undefined;
#slugger: GitHubSlugger;

constructor(options: Marked.MarkedOptions & RenderOptions = {}) {
super(options);
this.baseUrl = options.baseUrl;
this.allowMath = options.allowMath ?? false;
this.#slugger = new GitHubSlugger();
}

heading(
text: string,
level: 1 | 2 | 3 | 4 | 5 | 6,
raw: string,
): string {
const slug = slugger.slug(raw);
const slug = this.#slugger.slug(raw);
return `<h${level} id="${slug}"><a class="anchor" aria-hidden="true" tabindex="-1" href="#${slug}"><svg class="octicon octicon-link" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z"></path></svg></a>${text}</h${level}>`;
}

Expand Down
9 changes: 9 additions & 0 deletions test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -283,3 +283,12 @@ Deno.test("expect console warning from invalid math", () => {

console.warn = originalWarn;
});

Deno.test("render github-slugger not reused", function () {
for (let i = 0; i < 2; i++) {
const html = render("## Hello");
const expected =
`<h2 id="hello"><a class="anchor" aria-hidden="true" tabindex="-1" href="#hello"><svg class="octicon octicon-link" viewbox="0 0 16 16" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z"></path></svg></a>Hello</h2>`;
assertEquals(html, expected);
}
});

0 comments on commit 65c0a74

Please sign in to comment.