From 4a8559aad1ee5ab3248fe942d7bef5b9755a1ec6 Mon Sep 17 00:00:00 2001 From: Huaichao Wang Date: Wed, 8 Feb 2023 15:40:05 +0800 Subject: [PATCH] fix: chapter number increases as the number of marked.parse calls --- src/index.ts | 21 ++++++++++++++------- src/test/toc.test.ts | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 7 deletions(-) diff --git a/src/index.ts b/src/index.ts index edd855a..198eff4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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, @@ -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 diff --git a/src/test/toc.test.ts b/src/test/toc.test.ts index 982d7e7..b9c8823 100644 --- a/src/test/toc.test.ts +++ b/src/test/toc.test.ts @@ -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(` +

1 l2

+

1.1 l3

+

2 l1

+ `); + + 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(` +

1 l2

+

1.1 l3

+

2 l1

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