Browse Source

Simplify lowest common ancestor code.

pull/3253/head
Dariusz Komosinski 7 years ago
parent
commit
b1ec049054
  1. 22
      src/Avalonia.Visuals/VisualTree/VisualExtensions.cs
  2. 20
      tests/Avalonia.Visuals.UnitTests/VisualExtensionsTests.cs

22
src/Avalonia.Visuals/VisualTree/VisualExtensions.cs

@ -78,20 +78,12 @@ namespace Avalonia.VisualTree
return null;
}
IVisual GoUpwards(ref IVisual node, int count, IVisual parentCandidate)
void GoUpwards(ref IVisual node, int count)
{
for (int i = 0; i < count; ++i)
{
node = node.VisualParent;
// Other node can be our ancestor so we might find it early on.
if (node == parentCandidate)
{
return node;
}
}
return null;
}
// We want to find lowest node first, then make sure that both nodes are at the same height.
@ -99,13 +91,13 @@ namespace Avalonia.VisualTree
var firstHeight = CalculateDistanceFromRoot(visual);
var secondHeight = CalculateDistanceFromRoot(target);
IVisual found = firstHeight > secondHeight ?
GoUpwards(ref visual, firstHeight - secondHeight, target) :
GoUpwards(ref target, secondHeight - firstHeight, target);
if (found != null)
if (firstHeight > secondHeight)
{
GoUpwards(ref visual, firstHeight - secondHeight);
}
else
{
return found;
GoUpwards(ref target, secondHeight - firstHeight);
}
if (visual == target)

20
tests/Avalonia.Visuals.UnitTests/VisualExtensionsTests.cs

@ -85,6 +85,26 @@ namespace Avalonia.Visuals.UnitTests
Assert.Equal(target, root.FindDescendantOfType<Button>());
}
[Fact]
public void FindCommonVisualAncestor_First_Is_Parent_Of_Second()
{
Control left, right;
var root = new TestRoot
{
Child = left = new Decorator
{
Child = right = new Decorator()
}
};
var ancestor = left.FindCommonVisualAncestor(right);
Assert.Equal(left, ancestor);
ancestor = right.FindCommonVisualAncestor(left);
Assert.Equal(left, ancestor);
}
[Fact]
public void FindCommonVisualAncestor_Two_Subtrees_Uniform_Height()
{

Loading…
Cancel
Save