From 935bf3958f5efc062b4e34f916f622bef09e6487 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Sun, 15 Nov 2026 09:48:08 +0100 Subject: [PATCH] fix: give no id to the level 1 heading --- internal/mdx/mdx.go | 10 +++++++--- internal/mdx/mdx_test.go | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/internal/mdx/mdx.go b/internal/mdx/mdx.go index 41ea41b..d01c6a7 100644 --- a/internal/mdx/mdx.go +++ b/internal/mdx/mdx.go @@ -19,7 +19,8 @@ import ( type Heading struct { // Level is 1 for "#", 2 for "##", and so on. Level int - // ID is the anchor identifier given to the heading. + // ID is the anchor identifier given to the heading; a level 1 heading has + // none, because it is the title of the page. ID string // Text is the heading without markup. Text string @@ -43,8 +44,11 @@ func Render(md string) (string, []Heading, error) { return ast.WalkContinue, nil } plain := plainText(h, src) - id := uniqueID(Slug(plain), used) - h.SetAttributeString("id", []byte(id)) + id := "" + if h.Level >= 2 { + id = uniqueID(Slug(plain), used) + h.SetAttributeString("id", []byte(id)) + } headings = append(headings, Heading{Level: h.Level, ID: id, Text: plain}) return ast.WalkSkipChildren, nil }) diff --git a/internal/mdx/mdx_test.go b/internal/mdx/mdx_test.go index a0a58a3..f60f8b6 100644 --- a/internal/mdx/mdx_test.go +++ b/internal/mdx/mdx_test.go @@ -64,6 +64,24 @@ func TestRenderRawHTMLPasses(t *testing.T) { } } +// TestRenderTitleHasNoID checks that a level 1 heading gets no id, so it cannot +// collide with a level 2 heading that has the same words. +func TestRenderTitleHasNoID(t *testing.T) { + html, headings, err := Render("# Services\n\n## Services\n") + if err != nil { + t.Fatal(err) + } + if strings.Contains(html, `

`) { + t.Errorf("html %q lost the id of the h2", html) + } + if len(headings) != 2 || headings[0].ID != "" || headings[1].ID != "services" { + t.Errorf("headings = %+v, want the h1 without id and the h2 as services", headings) + } +} + // TestRenderHeadingTextIsPlain checks that the heading text drops the markup. func TestRenderHeadingTextIsPlain(t *testing.T) { _, headings, err := Render("## Free *your* mind\n")