Skip to content

Commit

Permalink
Add RenderableGroup to render a group of nodes without a parent element
Browse files Browse the repository at this point in the history
  • Loading branch information
eduardolat committed Aug 11, 2024
1 parent 13a9bf8 commit 7cb43ae
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 0 deletions.
26 changes: 26 additions & 0 deletions internal/web/component/renderable_group.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package component

import (
"bytes"

"github.com/maragudk/gomponents"
)

// RenderableGroup renders a group of nodes without a parent element.
//
// This is because gomponents.Group() cannot be directly rendered and
// needs to be wrapped in a parent element.
func RenderableGroup(children []gomponents.Node) gomponents.Node {
if len(children) == 0 {
return gomponents.Raw("")
}

buf := bytes.Buffer{}
for _, child := range children {
err := child.Render(&buf)
if err != nil {
return gomponents.Raw("Error rendering group")
}
}
return gomponents.Raw(buf.String())
}
70 changes: 70 additions & 0 deletions internal/web/component/renderable_group_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package component

import (
"bytes"
"testing"

"github.com/maragudk/gomponents"
"github.com/maragudk/gomponents/html"
"github.com/stretchr/testify/assert"
)

func TestRenderableGroupRenderer(t *testing.T) {
t.Run("renders a group of string nodes without a parent element", func(t *testing.T) {
gotRenderer := RenderableGroup([]gomponents.Node{
gomponents.Text("foo"),
gomponents.Text("bar"),
})

got := bytes.Buffer{}
err := gotRenderer.Render(&got)
assert.NoError(t, err)

expected := "foobar"

assert.Equal(t, expected, got.String())
})

t.Run("renders a group of tag nodes without a parent element", func(t *testing.T) {
gotRenderer := RenderableGroup([]gomponents.Node{
html.Span(
gomponents.Text("foo"),
),
html.P(
gomponents.Text("bar"),
),
})

got := bytes.Buffer{}
err := gotRenderer.Render(&got)
assert.NoError(t, err)

expected := `<span>foo</span><p>bar</p>`

assert.Equal(t, expected, got.String())
})

t.Run("empty group", func(t *testing.T) {
gotRenderer := RenderableGroup([]gomponents.Node{})

got := bytes.Buffer{}
err := gotRenderer.Render(&got)
assert.NoError(t, err)

expected := ``

assert.Equal(t, expected, got.String())
})

t.Run("nil group", func(t *testing.T) {
gotRenderer := RenderableGroup(nil)

got := bytes.Buffer{}
err := gotRenderer.Render(&got)
assert.NoError(t, err)

expected := ``

assert.Equal(t, expected, got.String())
})
}

0 comments on commit 7cb43ae

Please sign in to comment.