2
0
Эх сурвалжийг харах

Added GetChildren and GetParent

tznind 4 жил өмнө
parent
commit
2bd3f76553

+ 24 - 0
Terminal.Gui/Views/TreeView.cs

@@ -165,6 +165,30 @@ namespace Terminal.Gui {
 				SetNeedsDisplay();
 		}
 
+		/// <summary>
+		/// Returns the currently expanded children of the passed object.  Returns an empty collection if the branch is not exposed or not expanded
+		/// </summary>
+		/// <param name="o">An object in the tree</param>
+		/// <returns></returns>
+		public IEnumerable<object> GetChildren (object o)
+		{
+			var branch = ObjectToBranch(o);
+
+			if(branch == null || !branch.IsExpanded)
+				return new object[0];
+
+			return branch.ChildBranches?.Values?.Select(b=>b.Model)?.ToArray() ?? new object[0];
+		}
+		/// <summary>
+		/// Returns the parent object of <paramref name="o"/> in the tree.  Returns null if the object is not exposed in the tree
+		/// </summary>
+		/// <param name="o">An object in the tree</param>
+		/// <returns></returns>
+		public object GetParent (object o)
+		{
+			return ObjectToBranch(o)?.Parent?.Model;
+		}
+
 		/// <summary>
 		/// Returns the string representation of model objects hosted in the tree.  Default implementation is to call <see cref="object.ToString"/>
 		/// </summary>

+ 46 - 0
UnitTests/TreeViewTests.cs

@@ -167,5 +167,51 @@ namespace UnitTests {
 			// The old selection was c1 which is now gone so selection should default to the parent of that branch (the factory)
 			Assert.Equal(f,tree.SelectedObject);
 		}
+		[Fact]
+		public void GetParent_ReturnsParentOnlyWhenExpanded()
+		{
+			var tree = CreateTree(out Factory f, out Car c1, out Car c2);
+			
+			Assert.Null(tree.GetParent(f));
+			Assert.Null(tree.GetParent(c1));
+			Assert.Null(tree.GetParent(c2));
+
+			// now when we expand the factory we discover the cars
+			tree.Expand(f);
+			
+			Assert.Null(tree.GetParent(f));
+			Assert.Equal(f,tree.GetParent(c1));
+			Assert.Equal(f,tree.GetParent(c2));
+
+			tree.Collapse(f);
+
+			Assert.Null(tree.GetParent(f));
+			Assert.Null(tree.GetParent(c1));
+			Assert.Null(tree.GetParent(c2));
+		}
+
+		[Fact]
+		public void GetChildren_ReturnsChildrenOnlyWhenExpanded()
+		{
+			var tree = CreateTree(out Factory f, out Car c1, out Car c2);
+			
+			Assert.Empty(tree.GetChildren(f));
+			Assert.Empty(tree.GetChildren(c1));
+			Assert.Empty(tree.GetChildren(c2));
+
+			// now when we expand the factory we discover the cars
+			tree.Expand(f);
+			
+			Assert.Contains(c1,tree.GetChildren(f));
+			Assert.Contains(c2,tree.GetChildren(f));
+			Assert.Empty(tree.GetChildren(c1));
+			Assert.Empty(tree.GetChildren(c2));
+
+			tree.Collapse(f);
+
+			Assert.Empty(tree.GetChildren(f));
+			Assert.Empty(tree.GetChildren(c1));
+			Assert.Empty(tree.GetChildren(c2));
+		}
 	}
 }