Debian Codegraph @

markup/internal/attributes/attributes.go

raw
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package attributes
15
16 import (
17 "fmt"
18 "strconv"
19 "strings"
20 "sync"
21
22 "github.com/gohugoio/hugo/common/hugio"
23 "github.com/spf13/cast"
24 "github.com/yuin/goldmark/ast"
25 "github.com/yuin/goldmark/util"
26 )
27
28 // Markdown attributes used as options by the Chroma highlighter.
29 var chromaHighlightProcessingAttributes = map[string]bool{
30 "anchorLineNos": true,
31 "guessSyntax": true,
32 "hl_Lines": true,
33 "hl_inline": true,
34 "lineAnchors": true,
35 "lineNos": true,
36 "lineNoStart": true,
37 "lineNumbersInTable": true,
38 "noClasses": true,
39 "style": true,
40 "tabWidth": true,
41 }
42
43 func init() {
44 for k, v := range chromaHighlightProcessingAttributes {
45 chromaHighlightProcessingAttributes[strings.ToLower(k)] = v
46 }
47 }
48
49 type AttributesOwnerType int
50
51 const (
52 AttributesOwnerGeneral AttributesOwnerType = iota
53 AttributesOwnerCodeBlockChroma
54 AttributesOwnerCodeBlockCustom
55 )
56
57 func New(astAttributes []ast.Attribute, ownerType AttributesOwnerType) *AttributesHolder {
58 var (
59 attrs []Attribute
60 opts []Attribute
61 )
62 for _, v := range astAttributes {
63 nameLower := strings.ToLower(string(v.Name))
64 if strings.HasPrefix(string(nameLower), "on") {
65 continue
66 }
67 var vv any
68 switch vvv := v.Value.(type) {
69 case bool, float64:
70 vv = vvv
71 case []any:
72 // Highlight line number hlRanges.
73 var hlRanges [][2]int
74 for _, l := range vvv {
75 if ln, ok := l.(float64); ok {
76 hlRanges = append(hlRanges, [2]int{int(ln) - 1, int(ln) - 1})
77 } else if rng, ok := l.([]uint8); ok {
78 slices := strings.Split(string([]byte(rng)), "-")
79 lhs, err := strconv.Atoi(slices[0])
80 if err != nil {
81 continue
82 }
83 rhs := lhs
84 if len(slices) > 1 {
85 rhs, err = strconv.Atoi(slices[1])
86 if err != nil {
87 continue
88 }
89 }
90 hlRanges = append(hlRanges, [2]int{lhs - 1, rhs - 1})
91 }
92 }
93 vv = hlRanges
94 case []byte:
95 // Note that we don't do any HTML escaping here.
96 // We used to do that, but that changed in #9558.
97 // Now it's up to the templates to decide.
98 vv = string(vvv)
99 default:
100 panic(fmt.Sprintf("not implemented: %T", vvv))
101 }
102
103 if ownerType == AttributesOwnerCodeBlockChroma && chromaHighlightProcessingAttributes[nameLower] {
104 attr := Attribute{Name: string(v.Name), Value: vv}
105 opts = append(opts, attr)
106 } else {
107 attr := Attribute{Name: nameLower, Value: vv}
108 attrs = append(attrs, attr)
109 }
110
111 }
112
113 return &AttributesHolder{
114 attributes: attrs,
115 options: opts,
116 }
117 }
118
119 type Attribute struct {
120 Name string
121 Value any
122 }
123
124 func (a Attribute) ValueString() string {
125 return cast.ToString(a.Value)
126 }
127
128 // Empty holds no attributes.
129 var Empty = &AttributesHolder{}
130
131 type AttributesHolder struct {
132 // What we get from Goldmark.
133 attributes []Attribute
134
135 // Attributes considered to be an option (code blocks)
136 options []Attribute
137
138 // What we send to the render hooks.
139 attributesMapInit sync.Once
140 attributesMap map[string]any
141 optionsMapInit sync.Once
142 optionsMap map[string]any
143 }
144
145 type Attributes map[string]any
146
147 func (a *AttributesHolder) Attributes() map[string]any {
148 a.attributesMapInit.Do(func() {
149 a.attributesMap = make(map[string]any)
150 for _, v := range a.attributes {
151 a.attributesMap[v.Name] = v.Value
152 }
153 })
154 return a.attributesMap
155 }
156
157 func (a *AttributesHolder) Options() map[string]any {
158 a.optionsMapInit.Do(func() {
159 a.optionsMap = make(map[string]any)
160 for _, v := range a.options {
161 a.optionsMap[v.Name] = v.Value
162 }
163 })
164 return a.optionsMap
165 }
166
167 func (a *AttributesHolder) AttributesSlice() []Attribute {
168 return a.attributes
169 }
170
171 func (a *AttributesHolder) OptionsSlice() []Attribute {
172 return a.options
173 }
174
175 // RenderASTAttributes writes the AST attributes to the given as attributes to an HTML element.
176 // This is used by the default HTML renderers, e.g. for headings etc. where no hook template could be found.
177 // This performs HTML escaping of string attributes.
178 func RenderASTAttributes(w hugio.FlexiWriter, attributes ...ast.Attribute) {
179 for _, attr := range attributes {
180
181 a := strings.ToLower(string(attr.Name))
182 if strings.HasPrefix(a, "on") {
183 continue
184 }
185
186 _, _ = w.WriteString(" ")
187 _, _ = w.Write(attr.Name)
188 _, _ = w.WriteString(`="`)
189
190 writeAttributeValue(w, attr.Value)
191
192 _ = w.WriteByte('"')
193 }
194 }
195
196 // RenderAttributes Render writes the attributes to the given as attributes to an HTML element.
197 // This is used for the default codeblock rendering.
198 // This performs HTML escaping of string attributes.
199 func RenderAttributes(w hugio.FlexiWriter, skipClass bool, attributes ...Attribute) {
200 for _, attr := range attributes {
201 a := strings.ToLower(string(attr.Name))
202 if skipClass && a == "class" {
203 continue
204 }
205 _, _ = w.WriteString(" ")
206 _, _ = w.WriteString(attr.Name)
207 _, _ = w.WriteString(`="`)
208
209 writeAttributeValue(w, attr.Value)
210
211 _ = w.WriteByte('"')
212 }
213 }
214
215 // writeAttributeValue writes v HTML-escaped as a double-quoted HTML attribute
216 // value. Note that New converts string values from a []byte to a string, so
217 // the string case is the common one and must be escaped too.
218 func writeAttributeValue(w hugio.FlexiWriter, v any) {
219 switch vv := v.(type) {
220 case []byte:
221 _, _ = w.Write(util.EscapeHTML(vv))
222 case string:
223 _, _ = w.Write(util.EscapeHTML([]byte(vv)))
224 default:
225 _, _ = w.Write(util.EscapeHTML([]byte(cast.ToString(vv))))
226 }
227 }