44 lines
1.0 KiB
Go
44 lines
1.0 KiB
Go
package report
|
|
|
|
import (
|
|
"fmt"
|
|
"html/template"
|
|
"regexp"
|
|
"strconv"
|
|
)
|
|
|
|
// OffsetHTags offsets all <h1>-<h6> tags in the HTML by the given amount.
|
|
// If the resulting heading level exceeds 6, it is capped at 6.
|
|
func offsetHTags(amount int, html template.HTML) template.HTML {
|
|
// Regular expression to match opening and closing h tags, e.g., <h1> or </h2>
|
|
re := regexp.MustCompile(`(?i)<(/?)h([1-6])(\s[^>]*)?>`)
|
|
|
|
// Replace all matches
|
|
result := re.ReplaceAllStringFunc(string(html), func(tag string) string {
|
|
matches := re.FindStringSubmatch(tag)
|
|
if len(matches) < 4 {
|
|
return tag
|
|
}
|
|
|
|
closingSlash := matches[1] // "/" if closing tag
|
|
levelStr := matches[2] // heading level
|
|
attrs := matches[3] // attributes like ' class="foo"'
|
|
|
|
level, err := strconv.Atoi(levelStr)
|
|
if err != nil {
|
|
return tag
|
|
}
|
|
|
|
newLevel := level + amount
|
|
if newLevel < 1 {
|
|
newLevel = 1
|
|
} else if newLevel > 6 {
|
|
newLevel = 6
|
|
}
|
|
|
|
return fmt.Sprintf("<%sh%d%s>", closingSlash, newLevel, attrs)
|
|
})
|
|
|
|
return template.HTML(result)
|
|
}
|