You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

toc.go 1.2 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package markdown
  5. import (
  6. "fmt"
  7. "net/url"
  8. "github.com/unknwon/i18n"
  9. "github.com/yuin/goldmark/ast"
  10. )
  11. func createTOCNode(toc []Header, lang string) ast.Node {
  12. details := NewDetails()
  13. summary := NewSummary()
  14. summary.AppendChild(summary, ast.NewString([]byte(i18n.Tr(lang, "toc"))))
  15. details.AppendChild(details, summary)
  16. ul := ast.NewList('-')
  17. details.AppendChild(details, ul)
  18. currentLevel := 6
  19. for _, header := range toc {
  20. if header.Level < currentLevel {
  21. currentLevel = header.Level
  22. }
  23. }
  24. for _, header := range toc {
  25. for currentLevel > header.Level {
  26. ul = ul.Parent().(*ast.List)
  27. currentLevel--
  28. }
  29. for currentLevel < header.Level {
  30. newL := ast.NewList('-')
  31. ul.AppendChild(ul, newL)
  32. currentLevel++
  33. ul = newL
  34. }
  35. li := ast.NewListItem(currentLevel * 2)
  36. a := ast.NewLink()
  37. a.Destination = []byte(fmt.Sprintf("#%s", url.PathEscape(header.ID)))
  38. a.AppendChild(a, ast.NewString([]byte(header.Text)))
  39. li.AppendChild(li, a)
  40. ul.AppendChild(ul, li)
  41. }
  42. return details
  43. }