Added TreeView.GetPath method. Resolves #897

This commit is contained in:
Oliver 2023-10-05 22:26:32 +02:00
parent 9bc1d28d88
commit 57ac381f74
2 changed files with 31 additions and 2 deletions

View File

@ -2,7 +2,7 @@
package main package main
import ( import (
"io/ioutil" "os"
"path/filepath" "path/filepath"
"github.com/gdamore/tcell/v2" "github.com/gdamore/tcell/v2"
@ -21,7 +21,7 @@ func main() {
// A helper function which adds the files and directories of the given path // A helper function which adds the files and directories of the given path
// to the given target node. // to the given target node.
add := func(target *tview.TreeNode, path string) { add := func(target *tview.TreeNode, path string) {
files, err := ioutil.ReadDir(path) files, err := os.ReadDir(path)
if err != nil { if err != nil {
panic(err) panic(err)
} }

View File

@ -362,6 +362,35 @@ func (t *TreeView) GetCurrentNode() *TreeNode {
return t.currentNode return t.currentNode
} }
// GetPath returns all nodes located on the path from the root to the given
// node, including the root and the node itself. If there is no root node, nil
// is returned. If there are multiple paths to the node, a random one is chosen
// and returned.
func (t *TreeView) GetPath(node *TreeNode) []*TreeNode {
if t.root == nil {
return nil
}
var f func(current *TreeNode, path []*TreeNode) []*TreeNode
f = func(current *TreeNode, path []*TreeNode) []*TreeNode {
if current == node {
return path
}
for _, child := range current.children {
newPath := make([]*TreeNode, len(path), len(path)+1)
copy(newPath, path)
if p := f(child, append(newPath, child)); p != nil {
return p
}
}
return nil
}
return f(t.root, []*TreeNode{t.root})
}
// SetTopLevel sets the first tree level that is visible with 0 referring to the // SetTopLevel sets the first tree level that is visible with 0 referring to the
// root, 1 to the root's child nodes, and so on. Nodes above the top level are // root, 1 to the root's child nodes, and so on. Nodes above the top level are
// not displayed. // not displayed.