diff --git a/packages/docusaurus-utils/src/__tests__/markdownUtils.test.ts b/packages/docusaurus-utils/src/__tests__/markdownUtils.test.ts index a81e8cfff103..d4304974eb20 100644 --- a/packages/docusaurus-utils/src/__tests__/markdownUtils.test.ts +++ b/packages/docusaurus-utils/src/__tests__/markdownUtils.test.ts @@ -47,6 +47,28 @@ describe('createExcerpt', () => { ); }); + it('creates excerpt for regular content with regular title containing #', () => { + expect( + createExcerpt(dedent` + + # C# Programming Guide + + This paragraph should become the description. + `), + ).toBe('This paragraph should become the description.'); + }); + + it('creates excerpt for regular content with regular title containing # and trailing hash', () => { + expect( + createExcerpt(dedent` + + # F# Programming Guide # + + This paragraph should become the description. + `), + ).toBe('This paragraph should become the description.'); + }); + it('creates excerpt for regular content with alternate title', () => { expect( createExcerpt(dedent` @@ -65,6 +87,18 @@ describe('createExcerpt', () => { ); }); + it('creates excerpt for content starting with html comments', () => { + expect( + createExcerpt(dedent` + + + Page text here, lorem ipsum etc etc etc + `), + ).toBe('Page text here, lorem ipsum etc etc etc'); + }); + it('creates excerpt for content with h2 heading', () => { expect( createExcerpt(dedent` diff --git a/packages/docusaurus-utils/src/markdownUtils.ts b/packages/docusaurus-utils/src/markdownUtils.ts index 216d0122e7ad..e0312e9dca08 100644 --- a/packages/docusaurus-utils/src/markdownUtils.ts +++ b/packages/docusaurus-utils/src/markdownUtils.ts @@ -93,6 +93,7 @@ export function createExcerpt(fileString: string): string | undefined { let inCode = false; let inImport = false; let inHTML = false; + let inHTMLComment = false; let lastCodeFence = ''; for (const fileLine of fileLines) { @@ -112,6 +113,26 @@ export function createExcerpt(fileString: string): string | undefined { continue; } + // Ignore HTML comments entirely when building excerpts. + if (inHTMLComment) { + if (fileLine.includes('-->')) { + inHTMLComment = false; + } + continue; + } + if (/^\s*')) { + inHTMLComment = true; + } + continue; + } + + // Skip level-1 ATX headings entirely so inline `#` characters like `C#` + // don't leave behind a partial heading fragment in the excerpt. + if (/^\s*#(?!#)\s/.test(fileLine)) { + continue; + } + // Skip code block line. if (fileLine.trim().startsWith('```')) { const codeFence = fileLine.trim().match(/^`+/)![0]!;