2024-03-27 22:26:13 -04:00
|
|
|
// Copyright 2024 The Gitea Authors. All rights reserved.
|
|
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
|
|
|
|
package markdown
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"code.gitea.io/gitea/modules/container"
|
|
|
|
"code.gitea.io/gitea/modules/markup/common"
|
2024-06-13 21:26:33 -04:00
|
|
|
"code.gitea.io/gitea/modules/util"
|
2024-03-27 22:26:13 -04:00
|
|
|
|
|
|
|
"github.com/yuin/goldmark/ast"
|
|
|
|
)
|
|
|
|
|
|
|
|
type prefixedIDs struct {
|
|
|
|
values container.Set[string]
|
|
|
|
}
|
|
|
|
|
|
|
|
// Generate generates a new element id.
|
|
|
|
func (p *prefixedIDs) Generate(value []byte, kind ast.NodeKind) []byte {
|
|
|
|
dft := []byte("id")
|
|
|
|
if kind == ast.KindHeading {
|
|
|
|
dft = []byte("heading")
|
|
|
|
}
|
|
|
|
return p.GenerateWithDefault(value, dft)
|
|
|
|
}
|
|
|
|
|
|
|
|
// GenerateWithDefault generates a new element id.
|
|
|
|
func (p *prefixedIDs) GenerateWithDefault(value, dft []byte) []byte {
|
|
|
|
result := common.CleanValue(value)
|
|
|
|
if len(result) == 0 {
|
|
|
|
result = dft
|
|
|
|
}
|
|
|
|
if !bytes.HasPrefix(result, []byte("user-content-")) {
|
|
|
|
result = append([]byte("user-content-"), result...)
|
|
|
|
}
|
2024-06-13 21:26:33 -04:00
|
|
|
if p.values.Add(util.UnsafeBytesToString(result)) {
|
2024-03-27 22:26:13 -04:00
|
|
|
return result
|
|
|
|
}
|
|
|
|
for i := 1; ; i++ {
|
|
|
|
newResult := fmt.Sprintf("%s-%d", result, i)
|
|
|
|
if p.values.Add(newResult) {
|
|
|
|
return []byte(newResult)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Put puts a given element id to the used ids table.
|
|
|
|
func (p *prefixedIDs) Put(value []byte) {
|
2024-06-13 21:26:33 -04:00
|
|
|
p.values.Add(util.UnsafeBytesToString(value))
|
2024-03-27 22:26:13 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func newPrefixedIDs() *prefixedIDs {
|
|
|
|
return &prefixedIDs{
|
|
|
|
values: make(container.Set[string]),
|
|
|
|
}
|
|
|
|
}
|