Debian Codegraph @

resources/resource_transformers/tocss/sass/helpers.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 sass
15
16 import (
17 "fmt"
18 "maps"
19 "regexp"
20 "sort"
21 "strings"
22
23 "github.com/gohugoio/hugo/common/hmaps"
24 "github.com/gohugoio/hugo/common/hreflect"
25 "github.com/gohugoio/hugo/common/hstrings"
26 "github.com/gohugoio/hugo/common/types/css"
27 )
28
29 const (
30 HugoVarsNamespace = "hugo:vars"
31 // Transpiler implementation can be controlled from the client by
32 // setting the 'transpiler' option.
33 // Default is currently 'libsass', but that may change.
34 TranspilerDart = "dartsass"
35 TranspilerLibSass = "libsass"
36 )
37
38 // HugoVarsSubPath returns the slash-separated sub-path of a "hugo:vars" URL,
39 // e.g. "hugo:vars" -> "" and "hugo:vars/mobile" -> "mobile". The second return
40 // is false if url is not in the "hugo:vars" namespace.
41 func HugoVarsSubPath(url string) (string, bool) {
42 if url == HugoVarsNamespace {
43 return "", true
44 }
45 if rest, ok := strings.CutPrefix(url, HugoVarsNamespace+"/"); ok {
46 return rest, true
47 }
48 return "", false
49 }
50
51 // PrepareVars lowercases all keys for any map value recursively and returns a clone if modified.
52 func PrepareVars(vars map[string]any) map[string]any {
53 if vars == nil {
54 return nil
55 }
56
57 // Lowercase all keys for map values recursively, so that they can be accessed case-insensitively from the stylesheet.
58 var isCloned bool
59 for k, v := range vars {
60 if hstrings.HasUppercase(k) && hreflect.IsMap(v) {
61 if !isCloned {
62 vars = maps.Clone(vars)
63 }
64 delete(vars, k)
65 vars[strings.ToLower(k)] = PrepareVars(hmaps.ToStringMap(v))
66 isCloned = true
67 }
68 }
69 return vars
70 }
71
72 // ResolveVars returns the entries of vars at the given slash-separated path.
73 // Nested map entries are excluded from the result, so only scalar/typed values remain.
74 // An empty path returns the top-level scalars.
75 func ResolveVars(vars map[string]any, path string) map[string]any {
76 if vars == nil {
77 return nil
78 }
79 if path == "" || path == "/" {
80 return removeMaps(vars)
81 }
82 vv, err := hmaps.GetNestedParam(path, "/", vars)
83 if err != nil {
84 return nil
85 }
86
87 return removeMaps(hmaps.ToStringMap(vv))
88 }
89
90 func removeMaps(m map[string]any) map[string]any {
91 if m == nil {
92 return nil
93 }
94 res := make(map[string]any)
95 for k, v := range m {
96 if hreflect.IsMap(v) {
97 continue
98 }
99 res[k] = v
100 }
101 return res
102 }
103
104 func CreateVarsStyleSheet(transpiler string, vars map[string]any) string {
105 if vars == nil {
106 return ""
107 }
108 var varsStylesheet string
109
110 var varsSlice []string
111 for k, v := range vars {
112 if hreflect.IsMap(v) {
113 // Nested vars are exposed via "hugo:vars/<name>" namespaces, skip here.
114 continue
115 }
116 var prefix string
117 if !strings.HasPrefix(k, "$") {
118 prefix = "$"
119 }
120
121 switch v.(type) {
122 case css.QuotedString:
123 // Marked by the user as a string that needs to be quoted.
124 varsSlice = append(varsSlice, fmt.Sprintf("%s%s: %q;", prefix, k, v))
125 default:
126 if isTypedCSSValue(v) {
127 // E.g. 24px, 1.5rem, 10%, hsl(0, 0%, 100%), calc(24px + 36px), #fff, #ffffff.
128 varsSlice = append(varsSlice, fmt.Sprintf("%s%s: %v;", prefix, k, v))
129 } else {
130 // unquote will preserve quotes around URLs etc. if needed.
131 if transpiler == TranspilerDart {
132 varsSlice = append(varsSlice, fmt.Sprintf("%s%s: string.unquote(%q);", prefix, k, v))
133 } else {
134 varsSlice = append(varsSlice, fmt.Sprintf("%s%s: unquote(%q);", prefix, k, v))
135 }
136 }
137 }
138 }
139 sort.Strings(varsSlice)
140
141 if transpiler == TranspilerDart {
142 varsStylesheet = `@use "sass:string";` + "\n" + strings.Join(varsSlice, "\n")
143 } else {
144 varsStylesheet = strings.Join(varsSlice, "\n")
145 }
146
147 return varsStylesheet
148 }
149
150 var (
151 isCSSColor = regexp.MustCompile(`^#[0-9a-fA-F]{3,6}$`)
152 isCSSFunc = regexp.MustCompile(`^([a-zA-Z-]+)\(`)
153 isCSSUnit = regexp.MustCompile(`^([0-9]+)(\.[0-9]+)?([a-zA-Z-%]+)$`)
154 )
155
156 // isTypedCSSValue returns true if the given string is a CSS value that
157 // we should preserve the type of, as in: Not wrap it in quotes.
158 func isTypedCSSValue(v any) bool {
159 switch s := v.(type) {
160 case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, css.UnquotedString:
161 return true
162 case string:
163 if isCSSColor.MatchString(s) {
164 return true
165 }
166 if isCSSFunc.MatchString(s) {
167 return true
168 }
169 if isCSSUnit.MatchString(s) {
170 return true
171 }
172
173 }
174
175 return false
176 }