Skip to content

Commit

Permalink
Add None Node for Noop Rendering
Browse files Browse the repository at this point in the history
  • Loading branch information
chasefleming committed Nov 22, 2023
1 parent b910289 commit cde6252
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 0 deletions.
13 changes: 13 additions & 0 deletions elem.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,19 @@ type Node interface {
Render() string
}

// NoneNode represents a node that renders nothing.
type NoneNode struct{}

// RenderTo for NoneNode does nothing.
func (n NoneNode) RenderTo(builder *strings.Builder) {
// Intentionally left blank to render nothing
}

// Render for NoneNode returns an empty string.
func (n NoneNode) Render() string {
return ""
}

type TextNode string

func (t TextNode) RenderTo(builder *strings.Builder) {
Expand Down
5 changes: 5 additions & 0 deletions elements.go
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,11 @@ func Source(attrs attrs.Props, children ...Node) *Element {

// ========== Other ==========

// None creates a NoneNode, representing a no-operation in rendering.
func None() NoneNode {
return NoneNode{}
}

// Raw takes html content and returns a RawNode.
func Raw(html string) RawNode {
return RawNode(html)
Expand Down
13 changes: 13 additions & 0 deletions elements_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -509,6 +509,19 @@ func TestVideoWithSourceElementsAndFallbackText(t *testing.T) {

// ========== Other ==========

func TestNone(t *testing.T) {
el := None()
expected := ""

assert.Equal(t, expected, el.Render(), "None should render an empty string")
}

func TestNoneInDiv(t *testing.T) {
expected := `<div></div>`
actual := Div(nil, None()).Render()
assert.Equal(t, expected, actual)
}

func TestRaw(t *testing.T) {
rawHTML := `<div class="test"><p>Test paragraph</p></div>`
el := Raw(rawHTML)
Expand Down
10 changes: 10 additions & 0 deletions utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@ func TestIf(t *testing.T) {
assert.Equal(t, falseElement.Render(), resultFalse.Render())
}

func TestIfUsingNone(t *testing.T) {
trueElement := Div(nil, Text("True Condition"))

resultWithNone := If[Node](true, trueElement, None())
assert.Equal(t, trueElement.Render(), resultWithNone.Render(), "If should render the true element when the condition is true")

resultWithNoneFalse := If[Node](false, trueElement, None())
assert.Equal(t, "", resultWithNoneFalse.Render(), "If should render nothing (empty string) when the condition is false and None is used")
}

func TestTransformEach(t *testing.T) {
items := []string{"Item 1", "Item 2", "Item 3"}

Expand Down

0 comments on commit cde6252

Please sign in to comment.