Skip to content

Commit

Permalink
tocss: Simplify the hugo:vars type handling
Browse files Browse the repository at this point in the history
Instead of maintaing a list of all CSS units and functions this commit:

* Uses 3 regexps to detect typed CSS values (e.g. `24px`)
* These regexps may have some false positives -- e.g. strings that needs to be quoted.
* For that rare case, you can mark the string with e.g. `"32xxx" | css.Quoted`

Updates gohugoio#10632
  • Loading branch information
bep committed Feb 22, 2023
1 parent 5ae57fd commit b872d71
Show file tree
Hide file tree
Showing 9 changed files with 183 additions and 59 deletions.
17 changes: 17 additions & 0 deletions common/types/css/csstypes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Copyright 2023 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package css

// QuotedString is a string that needs to be quoted in CSS.
type QuotedString string
2 changes: 1 addition & 1 deletion resources/resource_transformers/tocss/dartsass/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ type Options struct {
// Vars will be available in 'hugo:vars', e.g:
// @use "hugo:vars";
// $color: vars.$color;
Vars map[string]string
Vars map[string]any
}

func decodeOptions(m map[string]any) (opts Options, err error) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,8 @@ color_hsl = "hsl(0, 0%, 100%)"
dimension = "24px"
percentage = "10%"
flex = "5fr"
name = "Hugo"
url = "https://gohugo.io"
-- assets/scss/main.scss --
@use "hugo:vars";
@use "sass:meta";
Expand All @@ -397,8 +399,12 @@ flex = "5fr"
@debug meta.type-of(vars.$dimension);
@debug meta.type-of(vars.$percentage);
@debug meta.type-of(vars.$flex);
@debug meta.type-of(vars.$name);
@debug meta.type-of(vars.$url);
@debug meta.type-of(vars.$not_a_unit);
-- layouts/index.html --
{{ $vars := site.Params.sassvars}}
{{ $vars = merge $vars (dict "not_a_unit" ("32xxx" | css.Quoted))}}
{{ $cssOpts := (dict "transpiler" "dartsass" "vars" $vars ) }}
{{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }}
T1: {{ $r.Content }}
Expand All @@ -418,5 +424,8 @@ T1: {{ $r.Content }}
b.AssertLogMatches(`INFO.*Dart Sass: .*assets.*main.scss:6:0: number`)
b.AssertLogMatches(`INFO.*Dart Sass: .*assets.*main.scss:7:0: number`)
b.AssertLogMatches(`INFO.*Dart Sass: .*assets.*main.scss:8:0: number`)
b.AssertLogMatches(`INFO.*Dart Sass: .*assets.*main.scss:9:0: string`)
b.AssertLogMatches(`INFO.*Dart Sass: .*assets.*main.scss:10:0: string`)
b.AssertLogMatches(`INFO.*Dart Sass: .*assets.*main.scss:11:0: string`)

}
72 changes: 37 additions & 35 deletions resources/resource_transformers/tocss/internal/sass/cssValues.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,65 +15,67 @@ package sass

type cssValue struct {
prefix []string
sufix []string
suffix []string
}

var (
cssValues = cssValue{
// https://developer.mozilla.org/en-US/docs/Web/CSS/color_value
prefix: []string{
"#",
"rgb(",
"attr(",
"calc(",
"clamp(",
"hsl(",
"hwb(",
"lch(",
"lab(",
"calc(",
"min(",
"lch(",
"max(",
"min(",
"minmax(",
"clamp(",
"attr(",
"rgb(",
},
sufix: []string{
"em",
"ex",
// https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Values_and_Units#dimensions
suffix: []string{
"%",
"cap",
"ch",
"ic",
"rem",
"lh",
"rlh",
"vw",
"vh",
"vi",
"vb",
"vmin",
"vmax",
"cqw",
"cm",
"cqb",
"cqh",
"cqi",
"cqb",
"cqmin",
"cqmax",
"cm",
"mm",
"Q",
"cqmin",
"cqw",
"deg",
"dpcm",
"dpi",
"dppx",
"em",
"ex",
"fr",
"grad",
"ic",
"in",
"lh",
"mm",
"ms",
"pc",
"pt",
"px",
"deg",
"grad",
"Q",
"rad",
"turn",
"rem",
"rlh",
"s",
"ms",
"fr",
"dpi",
"dpcm",
"dppx",
"turn",
"vb",
"vh",
"vi",
"vmax",
"vmin",
"vw",
"x",
"%",
},
}
)
62 changes: 40 additions & 22 deletions resources/resource_transformers/tocss/internal/sass/helpers.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2022 The Hugo Authors. All rights reserved.
// Copyright 2023 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -15,15 +15,19 @@ package sass

import (
"fmt"
"regexp"
"sort"
"strings"

"github.com/gohugoio/hugo/common/types/css"
"github.com/spf13/cast"
)

const (
HugoVarsNamespace = "hugo:vars"
)

func CreateVarsStyleSheet(vars map[string]string) string {
func CreateVarsStyleSheet(vars map[string]any) string {
if vars == nil {
return ""
}
Expand All @@ -35,35 +39,49 @@ func CreateVarsStyleSheet(vars map[string]string) string {
if !strings.HasPrefix(k, "$") {
prefix = "$"
}
// These variables can be a combination of Sass identifiers (e.g. sans-serif), which
// should not be quoted, and URLs et, which should be quoted.
// unquote() is knowing what to do with each.
// Use quoteVar() to check if the variables should be quoted or not.
if quoteVar(v) {
varsSlice = append(varsSlice, fmt.Sprintf("%s%s: unquote(%q);", prefix, k, v))
} else {
varsSlice = append(varsSlice, fmt.Sprintf("%s%s: %s;", prefix, k, v))

switch v.(type) {
case css.QuotedString:
// Marked by the user as a string that needs to be quoted.
varsSlice = append(varsSlice, fmt.Sprintf("%s%s: %q;", prefix, k, v))
default:
s := cast.ToString(v)
if isTypedCSSValue(s) {
// E.g. 24px, 1.5rem, 10%, hsl(0, 0%, 100%), calc(24px + 36px), #fff, #ffffff.
varsSlice = append(varsSlice, fmt.Sprintf("%s%s: %s;", prefix, k, s))
} else {
// unquote will preserve quotes around URLs etc. if needed.
varsSlice = append(varsSlice, fmt.Sprintf("%s%s: unquote(%q);", prefix, k, s))
}
}

}
sort.Strings(varsSlice)
varsStylesheet = strings.Join(varsSlice, "\n")

fmt.Println(varsStylesheet)

return varsStylesheet

}

func quoteVar(v string) bool {
v = strings.Trim(v, "\"")
for _, p := range cssValues.prefix {
if strings.HasPrefix(v, p) {
return false
}
var (
isCSSColor = regexp.MustCompile(`^#[0-9a-fA-F]{3,6}$`)
isCSSFunc = regexp.MustCompile(`^([a-zA-Z-]+)\(`)
isCSSUnit = regexp.MustCompile(`^([0-9]+)(\.[0-9]+)?([a-zA-Z-%]+)$`)
)

// isTypedCSSValue returns true if the given string is a CSS value that
// we should preserve the type of, as in: Not wrap it in quotes.
func isTypedCSSValue(s string) bool {
if isCSSColor.MatchString(s) {
return true
}
for _, s := range cssValues.sufix {
if strings.HasSuffix(v, s) {
return false
}
if isCSSFunc.MatchString(s) {
return true
}

return true
if isCSSUnit.MatchString(s) {
return true
}
return false
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright 2023 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package sass

import (
"testing"

qt "github.com/frankban/quicktest"
)

func TestIsUnquotedCSSValue(t *testing.T) {
c := qt.New(t)

for _, test := range []struct {
in string
out bool
}{
{"24px", true},
{"1.5rem", true},
{"10%", true},
{"hsl(0, 0%, 100%)", true},
{"calc(24px + 36px)", true},
{"24xxx", true}, // a false positive.
{"#fff", true},
{"#ffffff", true},
{"#ffffffff", false},
} {
c.Assert(isTypedCSSValue(test.in), qt.Equals, test.out)
}

}
2 changes: 1 addition & 1 deletion resources/resource_transformers/tocss/scss/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ type Options struct {

// Vars will be available in 'hugo:vars', e.g:
// @import "hugo:vars";
Vars map[string]string
Vars map[string]any
}

func DecodeOptions(m map[string]any) (opts Options, err error) {
Expand Down
35 changes: 35 additions & 0 deletions tpl/css/css.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package css

import (
"github.com/gohugoio/hugo/common/types/css"
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/tpl/internal"
"github.com/spf13/cast"
)

const name = "css"

// Namespace provides template functions for the "css" namespace.
type Namespace struct {
}

// Quoted returns a string that needs to be quoted in CSS.
func (ns *Namespace) Quoted(v any) css.QuotedString {
s := cast.ToString(v)
return css.QuotedString(s)
}

func init() {
f := func(d *deps.Deps) *internal.TemplateFuncsNamespace {
ctx := &Namespace{}

ns := &internal.TemplateFuncsNamespace{
Name: name,
Context: func(args ...any) (any, error) { return ctx, nil },
}

return ns
}

internal.AddTemplateFuncsNamespace(f)
}
1 change: 1 addition & 0 deletions tpl/tplimpl/template_funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import (
_ "github.com/gohugoio/hugo/tpl/collections"
_ "github.com/gohugoio/hugo/tpl/compare"
_ "github.com/gohugoio/hugo/tpl/crypto"
_ "github.com/gohugoio/hugo/tpl/css"
_ "github.com/gohugoio/hugo/tpl/data"
_ "github.com/gohugoio/hugo/tpl/debug"
_ "github.com/gohugoio/hugo/tpl/diagrams"
Expand Down

0 comments on commit b872d71

Please sign in to comment.