github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/markup/markdown/toc.go (about)

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