about summary refs log tree commit diff stats
path: root/attr
diff options
context:
space:
mode:
authorMarkus Wüstenberg2020-09-18 14:44:47 +0200
committerGitHub2020-09-18 14:44:47 +0200
commitf7812a9f06d2b97f413b6b33deecba170e05d184 (patch)
tree1e3759401854f0d4dd1fefb1dc89f16e46d0e4e9 /attr
parentf9d584c9889276000171046bcc2e32177514f552 (diff)
downloadgomponents-f7812a9f06d2b97f413b6b33deecba170e05d184.tar.lz
gomponents-f7812a9f06d2b97f413b6b33deecba170e05d184.tar.zst
gomponents-f7812a9f06d2b97f413b6b33deecba170e05d184.zip
Add package attr with attribute helpers (#7)
Diffstat (limited to 'attr')
-rw-r--r--attr/attributes.go33
-rw-r--r--attr/attributes_test.go31
2 files changed, 64 insertions, 0 deletions
diff --git a/attr/attributes.go b/attr/attributes.go
new file mode 100644
index 0000000..7ab27e4
--- /dev/null
+++ b/attr/attributes.go
@@ -0,0 +1,33 @@
+// Package attr provides shortcuts and helpers to common HTML attributes.
+// See https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes for a list of attributes.
+package attr
+
+import (
+	"sort"
+	"strings"
+
+	g "github.com/maragudk/gomponents"
+)
+
+// ID returns an attribute with name "id" and the given value.
+func ID(v string) g.Node {
+	return g.Attr("id", v)
+}
+
+// Class returns an attribute with name "class" and the given value.
+func Class(v string) g.Node {
+	return g.Attr("class", v)
+}
+
+// Classes returns an attribute with name "class" and the value being a sorted, space-separated string of all the keys,
+// for which the corresponding value is true.
+func Classes(cs map[string]bool) g.Node {
+	var included []string
+	for c, include := range cs {
+		if include {
+			included = append(included, c)
+		}
+	}
+	sort.Strings(included)
+	return g.Attr("class", strings.Join(included, " "))
+}
diff --git a/attr/attributes_test.go b/attr/attributes_test.go
new file mode 100644
index 0000000..0ad8c4e
--- /dev/null
+++ b/attr/attributes_test.go
@@ -0,0 +1,31 @@
+package attr_test
+
+import (
+	"testing"
+
+	"github.com/maragudk/gomponents/assert"
+	"github.com/maragudk/gomponents/attr"
+)
+
+func TestID(t *testing.T) {
+	t.Run("given a value, returns id=value", func(t *testing.T) {
+		assert.Equal(t, ` id="hat"`, attr.ID("hat"))
+	})
+}
+
+func TestClass(t *testing.T) {
+	t.Run("given a value, returns class=value", func(t *testing.T) {
+		assert.Equal(t, ` class="hat"`, attr.Class("hat"))
+	})
+}
+
+func TestClasses(t *testing.T) {
+	t.Run("given a map, returns sorted keys from the map with value true", func(t *testing.T) {
+		assert.Equal(t, ` class="boheme-hat hat partyhat"`, attr.Classes(map[string]bool{
+			"boheme-hat": true,
+			"hat":        true,
+			"partyhat":   true,
+			"turtlehat":  false,
+		}))
+	})
+}