Skip to content

Commit

Permalink
feat(tree): hide children
Browse files Browse the repository at this point in the history
Signed-off-by: Carlos Alexandro Becker <[email protected]>
  • Loading branch information
caarlos0 committed Dec 10, 2024
1 parent fe12bcb commit 6a2aef2
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
12 changes: 8 additions & 4 deletions tree/tree.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ type Node interface {
Value() string
Children() Children
Hidden() bool
SetHidden(bool)
}

// Leaf is a node without children.
Expand All @@ -46,6 +47,9 @@ type Leaf struct {
hidden bool
}

// SetHidden implements Node.
func (s *Leaf) SetHidden(hidden bool) { s.hidden = hidden }

// Children of a Leaf node are always empty.
func (Leaf) Children() Children {
return NodeChildren(nil)
Expand Down Expand Up @@ -77,6 +81,9 @@ type Tree struct { //nolint:revive
ronce sync.Once
}

// SetHidden implements Node.
func (t *Tree) SetHidden(hidden bool) { t.Hide(hidden) }

// Hidden returns whether this node is hidden.
func (t *Tree) Hidden() bool {
return t.hidden
Expand Down Expand Up @@ -147,7 +154,7 @@ func (t *Tree) Child(children ...any) *Tree {
t.children = t.children.(NodeChildren).Append(item)
case fmt.Stringer:
s := Leaf{value: item.String()}
t.children = t.children.(NodeChildren).Append(s)
t.children = t.children.(NodeChildren).Append(&s)
case string:
s := Leaf{value: item}
t.children = t.children.(NodeChildren).Append(&s)
Expand Down Expand Up @@ -180,9 +187,6 @@ func ensureParent(nodes Children, item *Tree) (*Tree, int) {
parent.Child(item.children.At(i))
}
return parent, j
case Leaf:
item.value = parent.Value()
return item, j
case *Leaf:
item.value = parent.Value()
return item, j
Expand Down
27 changes: 27 additions & 0 deletions tree/tree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -705,6 +705,33 @@ func TestTypes(t *testing.T) {
assertEqual(t, want, tree.String())
}

func TestLeafHidden(t *testing.T) {
tr := tree.New().
Child(
"Foo",
tree.Root("Bar").
Child(
"Qux",
tree.Root("Quux").
Child("This should be hidden").
Hide(true),
"Quuux",
),
"Baz",
)

// Hide Qux.
tr.Children().At(1).Children().At(0).SetHidden(true)

want := `
β”œβ”€β”€ Foo
β”œβ”€β”€ Bar
β”‚ └── Quuux
└── Baz
`
assertEqual(t, want, tr.String())
}

// assertEqual verifies the strings are equal, assuming its terminal output.
func assertEqual(tb testing.TB, want, got string) {
tb.Helper()
Expand Down

0 comments on commit 6a2aef2

Please sign in to comment.