fix: give no id to the level 1 heading
This commit is contained in:
parent
2f5cb15f21
commit
935bf3958f
2 changed files with 25 additions and 3 deletions
|
|
@ -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
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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, `<h1 id=`) {
|
||||
t.Errorf("html %q gives the h1 an id", html)
|
||||
}
|
||||
if !strings.Contains(html, `<h2 id="services">`) {
|
||||
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")
|
||||
|
|
|
|||
Loading…
Reference in a new issue