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