Skip to content

Commit 51fc9e6

Browse files
committed
Fix: fix duplicate slugs rendered for markdown components
1 parent ec9c086 commit 51fc9e6

2 files changed

Lines changed: 18 additions & 3 deletions

File tree

packages/site-kit/src/lib/markdown/renderer.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,7 @@ export async function render_content_markdown(
329329
twoslashBanner?: TwoslashBanner
330330
) {
331331
const headings: string[] = [];
332+
const seen_slugs = new Map<string, number>();
332333
const { check = true, references } = options ?? {};
333334

334335
interface CodeBlockFile {
@@ -600,7 +601,11 @@ export async function render_content_markdown(
600601

601602
headings[depth - 1] = slugify(text);
602603
headings.length = depth;
603-
const slug = headings.filter(Boolean).join('-');
604+
let slug = headings.filter(Boolean).join('-');
605+
606+
const count = seen_slugs.get(slug) ?? 0;
607+
seen_slugs.set(slug, count + 1);
608+
if (count > 0) slug = `${slug}-${count}`;
604609

605610
return `<h${depth} id="${slug}"><span>${html}</span><a href="#${slug}" class="permalink" aria-label="permalink"></a></h${depth}>`;
606611
},

packages/site-kit/src/lib/server/content/index.ts

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,13 @@ export async function create_index(
3030
'<code>$1</code>'
3131
);
3232

33+
const seen_slugs = new Map<string, number>();
34+
const dedupe = (slug: string) => {
35+
const count = seen_slugs.get(slug) ?? 0;
36+
seen_slugs.set(slug, count + 1);
37+
return count > 0 ? `${slug}-${count}` : slug;
38+
};
39+
3340
const sections = Array.from(body.matchAll(/^#{2,3}\s+(.*)$/gm)).reduce((arr, match) => {
3441
if (is_in_code_block(body, match.index || 0)) return arr;
3542
const title = match[1];
@@ -43,10 +50,13 @@ export async function create_index(
4350
if (match[0].startsWith('###')) {
4451
const section = arr.at(-1);
4552
if (section) {
46-
section.subsections.push({ slug: `${section.slug}-${slug}`, title: displayed_title });
53+
section.subsections.push({
54+
slug: dedupe(`${section.slug}-${slug}`),
55+
title: displayed_title
56+
});
4757
}
4858
} else {
49-
arr.push({ slug, title: displayed_title, subsections: [] });
59+
arr.push({ slug: dedupe(slug), title: displayed_title, subsections: [] });
5060
}
5161

5262
return arr;

0 commit comments

Comments
 (0)