From c97605aca761985ac45adfe19365801ec2682657 Mon Sep 17 00:00:00 2001
From: Markus Wüstenberg
Date: Thu, 19 Sep 2024 17:03:08 +0200
Subject: Make Groups renderable (#181)
This change makes the result of `Group` renderable directly, instead of
panicking, with the important caveat that root-level attributes are
_ignored_. I don't think this will give problems in practice, as the
main use case for rendering `Group` is basically to return root-level
elements to the client using something like HTMX.
I tried adding a `Fragment`, but it was weird and confusing having two
functions (`Group` and `Fragment`) do essentially the same thing, the
only difference being whether the argument was a slice of `Node`s or
varargs.
Fixes #162---
gomponents_test.go | 49 +++++++++++++++++++++++++++----------------------
1 file changed, 27 insertions(+), 22 deletions(-)
(limited to 'gomponents_test.go')
diff --git a/gomponents_test.go b/gomponents_test.go
index c0ae7a7..f3e81b0 100644
--- a/gomponents_test.go
+++ b/gomponents_test.go
@@ -234,35 +234,40 @@ func TestGroup(t *testing.T) {
assert.Equal(t, `
![]()
`, e)
})
- t.Run("panics on direct render", func(t *testing.T) {
- e := g.Group(nil)
- panicked := false
- defer func() {
- if err := recover(); err != nil {
- panicked = true
- }
- }()
- _ = e.Render(nil)
- if !panicked {
- t.FailNow()
- }
+ t.Run("ignores attributes at the first level", func(t *testing.T) {
+ children := []g.Node{g.Attr("class", "hat"), g.El("div"), g.El("span")}
+ e := g.Group(children)
+ assert.Equal(t, "", e)
})
- t.Run("panics on direct string", func(t *testing.T) {
- e := g.Group(nil).(fmt.Stringer)
- panicked := false
- defer func() {
- if err := recover(); err != nil {
- panicked = true
- }
- }()
- _ = e.String()
- if !panicked {
+ t.Run("does not ignore attributes at the second level", func(t *testing.T) {
+ children := []g.Node{g.El("div", g.Attr("class", "hat")), g.El("span")}
+ e := g.Group(children)
+ assert.Equal(t, ``, e)
+ })
+
+ t.Run("can render a group child node including attributes", func(t *testing.T) {
+ children := []g.Node{g.Attr("id", "hat"), g.El("div"), g.El("span")}
+ e := g.El("div", g.Group(children))
+ assert.Equal(t, ``, e)
+ })
+
+ t.Run("implements fmt.Stringer", func(t *testing.T) {
+ children := []g.Node{g.El("div"), g.El("span")}
+ e := g.Group(children)
+ if e, ok := e.(fmt.Stringer); !ok || e.String() != "" {
t.FailNow()
}
})
}
+func ExampleGroup() {
+ children := []g.Node{g.El("div"), g.El("span")}
+ e := g.Group(children)
+ _ = e.Render(os.Stdout)
+ // Output:
+}
+
func TestIf(t *testing.T) {
t.Run("returns node if condition is true", func(t *testing.T) {
n := g.El("div", g.If(true, g.El("span")))
--
cgit 1.4.1