From 3d25f6e43179f9dfab88b22525a2fde004b54bb7 Mon Sep 17 00:00:00 2001 From: Antoine BERNIER Date: Sat, 24 Aug 2024 21:15:00 +0200 Subject: [PATCH] fix: remove duplicated content in search results --- src/components/mdx/Toc/rehypeToc.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/components/mdx/Toc/rehypeToc.ts b/src/components/mdx/Toc/rehypeToc.ts index 0fa4780b..b52d7ba4 100644 --- a/src/components/mdx/Toc/rehypeToc.ts +++ b/src/components/mdx/Toc/rehypeToc.ts @@ -25,6 +25,9 @@ const slugify = (title: string) => title.toLowerCase().replace(/\s+|-+/g, '-') /** * Generates a table of contents from page headings. */ + +const isHeading = (node: Node) => /^h[1-6]$/.test(node.tagName) + export const rehypeToc = (target: DocToC[] = [], url: string, page: string) => { return () => (root: Node) => { const previous: Record = {} @@ -32,7 +35,7 @@ export const rehypeToc = (target: DocToC[] = [], url: string, page: string) => { for (let i = 0; i < root.children.length; i++) { const node = root.children[i] - if (node.type === 'element' && /^h[1-4]$/.test(node.tagName)) { + if (isHeading(node)) { const level = parseInt(node.tagName[1]) const title = toString(node) @@ -45,9 +48,9 @@ export const rehypeToc = (target: DocToC[] = [], url: string, page: string) => { let siblingIndex = i + 1 const content: string[] = [] - let sibling: Node | undefined = root.children[siblingIndex] + let sibling: Node = root.children[siblingIndex] while (sibling) { - if (RegExp(`^h${level}$`).test(sibling.tagName)) break // stop at the next (same-level) heading + if (isHeading(sibling)) break // stop at the next heading content.push(toString(sibling)) sibling = root.children[siblingIndex++]