Skip to content

Commit

Permalink
fix: chapter number increases as the number of marked.parse calls
Browse files Browse the repository at this point in the history
  • Loading branch information
huaichaow committed Feb 8, 2023
1 parent 7149397 commit 4a8559a
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 7 deletions.
21 changes: 14 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,16 @@ export default function markedTableOfContentsExtension(
}
};

function renderToc() {
if (headings) {
tocCache = renderTableOfContent(headings, className) + '\n';
// clear headings for next run, to prevent headings cumulating and memory leak
headings = null;
fixHeadingDepth = null;
numberingHeading = null;
}
}

const tableOfContentsExtension = {
name: 'toc',
level: 'block' as const,
Expand All @@ -63,19 +73,16 @@ export default function markedTableOfContentsExtension(
}
},
renderer() {
if (headings) {
tocCache = renderTableOfContent(headings, className) + '\n';
// clear headings for next run, to prevent headings cumulating and memory leak
headings = null;
fixHeadingDepth = null;
numberingHeading = null;
}
renderToc();
return tocCache;
}
};

const rendererHeadingWithChapterNumber = {
heading(this: Renderer, text: string, level: number, raw: string, slugger: Slugger) {
// fixme: this is to ensure clean of 'headings' when `[toc]' not present in markdown input
renderToc();

const chapterNumber = chapterNumbers.shift();

const id = this.options.headerIds
Expand Down
33 changes: 33 additions & 0 deletions src/test/toc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,4 +90,37 @@ describe('marked-toc-extension', () => {

expect(marked.parse(md)).toEqual(expectedHtml);
});

test('should generate chapter number without toc', () => {
const md = removeLeadingSpaces(`
## l2
### l3
# l1
`);

const expectedHtml = removeLeadingSpaces(`
<h1 id="l2">1 l2</h1>
<h2 id="l3">1.1 l3</h2>
<h1 id="l1">2 l1</h1>
`);

expect(marked.parse(md)).toEqual(expectedHtml);
});

test('should generate the same chapter number without toc when call multiple times', () => {
const md = removeLeadingSpaces(`
## l2
### l3
# l1
`);

const expectedHtml = removeLeadingSpaces(`
<h1 id="l2">1 l2</h1>
<h2 id="l3">1.1 l3</h2>
<h1 id="l1">2 l1</h1>
`);

expect(marked.parse(md)).toEqual(expectedHtml);
expect(marked.parse(md)).toEqual(expectedHtml);
});
});

0 comments on commit 4a8559a

Please sign in to comment.