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, `