Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/heading-ids-no-duplicates.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/markdown-satteri': patch
---

Fixes headings being listed twice in a page's `headings` metadata when an integration (such as Starlight) assigns heading IDs with its own heading pass before adding anchor links
5 changes: 4 additions & 1 deletion packages/markdown/satteri/src/satteri-processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,8 @@ export function makeFragmentNode(html: string): HastNode {

export function createHeadingIdsPlugin(): HastPluginDefinition {
const slugger = new Slugger();
// Collect headings in a separate array so we can make this idempotent
const headings: MarkdownHeading[] = [];
return {
name: 'heading-ids',
element: {
Expand All @@ -130,7 +132,8 @@ export function createHeadingIdsPlugin(): HastPluginDefinition {
const existingId = node.properties?.id;
const slug = typeof existingId === 'string' ? existingId : slugger.slug(text);
const depth = Number.parseInt(node.tagName[1], 10);
astro?.headings.push({ depth, slug, text });
headings.push({ depth, slug, text });
if (astro) astro.headings = headings;
if (typeof existingId !== 'string') {
ctx.setProperty(node, 'id', slug);
}
Expand Down
11 changes: 11 additions & 0 deletions packages/markdown/satteri/test/markdown.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,17 @@ describe('satteri markdown', () => {
assert.equal(seenId, 'hello-world');
});

it('does not duplicate headings when `satteriHeadingIdsPlugin()` runs as a user plugin too', async () => {
const processor = await createSatteriMarkdownProcessor({
hastPlugins: [satteriHeadingIdsPlugin()],
});
const { metadata } = await processor.render('## Some text\n\n## Some text');
assert.deepEqual(metadata.headings, [
{ depth: 2, slug: 'some-text', text: 'Some text' },
{ depth: 2, slug: 'some-text-1', text: 'Some text' },
]);
});

it('respects heading IDs set by a user hast plugin in both DOM and `headings`', async () => {
const setIdPlugin: HastPluginDefinition = {
name: 'set-heading-id',
Expand Down
Loading