Browse Source

FIrst version of nth-child

pull/6381/head
Max Katz 5 years ago
parent
commit
69fb1c056f
  1. 6
      samples/ControlCatalog/Pages/ListBoxPage.xaml
  2. 19
      src/Avalonia.Controls/ItemsControl.cs
  3. 17
      src/Avalonia.Controls/Panel.cs
  4. 25
      src/Avalonia.Controls/Presenters/ItemsPresenterBase.cs
  5. 27
      src/Avalonia.Controls/Utils/IEnumerableUtils.cs
  6. 134
      src/Avalonia.Styling/Styling/NthChildSelector.cs
  7. 10
      src/Avalonia.Styling/Styling/Selectors.cs
  8. 35
      src/Markup/Avalonia.Markup.Xaml.Loader/CompilerExtensions/Transformers/AvaloniaXamlIlSelectorTransformer.cs
  9. 105
      src/Markup/Avalonia.Markup/Markup/Parsers/SelectorGrammar.cs
  10. 6
      src/Markup/Avalonia.Markup/Markup/Parsers/SelectorParser.cs
  11. 90
      tests/Avalonia.Markup.UnitTests/Parsers/SelectorGrammarTests.cs
  12. 59
      tests/Avalonia.Markup.Xaml.UnitTests/Xaml/StyleTests.cs
  13. 217
      tests/Avalonia.Styling.UnitTests/SelectorTests_NthChild.cs
  14. 217
      tests/Avalonia.Styling.UnitTests/SelectorTests_NthLastChild.cs

6
samples/ControlCatalog/Pages/ListBoxPage.xaml

@ -2,9 +2,15 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="ControlCatalog.Pages.ListBoxPage">
<DockPanel>
<DockPanel.Styles>
<Style Selector="ListBox ListBoxItem:nth-child(2n)">
<Setter Property="Foreground" Value="Blue" />
</Style>
</DockPanel.Styles>
<StackPanel DockPanel.Dock="Top" Margin="4">
<TextBlock Classes="h1">ListBox</TextBlock>
<TextBlock Classes="h2">Hosts a collection of ListBoxItem.</TextBlock>
<TextBlock Classes="h2">Each 2nd item is highlighted</TextBlock>
</StackPanel>
<StackPanel DockPanel.Dock="Right" Margin="4">
<CheckBox IsChecked="{Binding Multiple}">Multiple</CheckBox>

19
src/Avalonia.Controls/ItemsControl.cs

@ -13,6 +13,7 @@ using Avalonia.Controls.Utils;
using Avalonia.Input;
using Avalonia.LogicalTree;
using Avalonia.Metadata;
using Avalonia.Styling;
using Avalonia.VisualTree;
namespace Avalonia.Controls
@ -21,7 +22,7 @@ namespace Avalonia.Controls
/// Displays a collection of items.
/// </summary>
[PseudoClasses(":empty", ":singleitem")]
public class ItemsControl : TemplatedControl, IItemsPresenterHost, ICollectionChangedListener
public class ItemsControl : TemplatedControl, IItemsPresenterHost, ICollectionChangedListener, IChildIndexProvider
{
/// <summary>
/// The default value for the <see cref="ItemsPanel"/> property.
@ -506,5 +507,21 @@ namespace Avalonia.Controls
return null;
}
(int Index, int? TotalCount) IChildIndexProvider.GetChildIndex(ILogical child)
{
if (Presenter is IChildIndexProvider innerProvider)
{
return innerProvider.GetChildIndex(child);
}
if (child is IControl control)
{
var index = ItemContainerGenerator.IndexFromContainer(control);
return (index, ItemCount);
}
return (-1, ItemCount);
}
}
}

17
src/Avalonia.Controls/Panel.cs

@ -2,8 +2,12 @@ using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using Avalonia.Controls.Presenters;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Metadata;
using Avalonia.Styling;
namespace Avalonia.Controls
{
@ -14,7 +18,7 @@ namespace Avalonia.Controls
/// Controls can be added to a <see cref="Panel"/> by adding them to its <see cref="Children"/>
/// collection. All children are layed out to fill the panel.
/// </remarks>
public class Panel : Control, IPanel
public class Panel : Control, IPanel, IChildIndexProvider
{
/// <summary>
/// Defines the <see cref="Background"/> property.
@ -160,5 +164,16 @@ namespace Avalonia.Controls
var panel = control?.VisualParent as TPanel;
panel?.InvalidateMeasure();
}
(int Index, int? TotalCount) IChildIndexProvider.GetChildIndex(ILogical child)
{
if (child is IControl control)
{
var index = Children.IndexOf(control);
return (index, Children.Count);
}
return (-1, Children.Count);
}
}
}

25
src/Avalonia.Controls/Presenters/ItemsPresenterBase.cs

@ -5,6 +5,7 @@ using Avalonia.Collections;
using Avalonia.Controls.Generators;
using Avalonia.Controls.Templates;
using Avalonia.Controls.Utils;
using Avalonia.LogicalTree;
using Avalonia.Styling;
namespace Avalonia.Controls.Presenters
@ -12,7 +13,7 @@ namespace Avalonia.Controls.Presenters
/// <summary>
/// Base class for controls that present items inside an <see cref="ItemsControl"/>.
/// </summary>
public abstract class ItemsPresenterBase : Control, IItemsPresenter, ITemplatedControl
public abstract class ItemsPresenterBase : Control, IItemsPresenter, ITemplatedControl, IChildIndexProvider
{
/// <summary>
/// Defines the <see cref="Items"/> property.
@ -248,5 +249,27 @@ namespace Avalonia.Controls.Presenters
{
(e.NewValue as IItemsPresenterHost)?.RegisterItemsPresenter(this);
}
(int Index, int? TotalCount) IChildIndexProvider.GetChildIndex(ILogical child)
{
int? totalCount = null;
if (Items.TryGetCountFast(out var count))
{
totalCount = count;
}
if (child is IControl control)
{
if (ItemContainerGenerator is { } generator)
{
var index = ItemContainerGenerator.IndexFromContainer(control);
return (index, totalCount);
}
}
return (-1, totalCount);
}
}
}

27
src/Avalonia.Controls/Utils/IEnumerableUtils.cs

@ -12,23 +12,36 @@ namespace Avalonia.Controls.Utils
return items.IndexOf(item) != -1;
}
public static int Count(this IEnumerable items)
public static bool TryGetCountFast(this IEnumerable items, out int count)
{
if (items != null)
{
if (items is ICollection collection)
{
return collection.Count;
count = collection.Count;
return true;
}
else if (items is IReadOnlyCollection<object> readOnly)
{
return readOnly.Count;
}
else
{
return Enumerable.Count(items.Cast<object>());
count = readOnly.Count;
return true;
}
}
count = 0;
return false;
}
public static int Count(this IEnumerable items)
{
if (TryGetCountFast(items, out var count))
{
return count;
}
else if (items != null)
{
return Enumerable.Count(items.Cast<object>());
}
else
{
return 0;

134
src/Avalonia.Styling/Styling/NthChildSelector.cs

@ -0,0 +1,134 @@
#nullable enable
using System;
using System.Text;
using Avalonia.LogicalTree;
namespace Avalonia.Styling
{
public interface IChildIndexProvider
{
(int Index, int? TotalCount) GetChildIndex(ILogical child);
}
public class NthLastChildSelector : NthChildSelector
{
public NthLastChildSelector(Selector? previous, int step, int offset) : base(previous, step, offset, true)
{
}
}
public class NthChildSelector : Selector
{
private const string NthChildSelectorName = "nth-child";
private const string NthLastChildSelectorName = "nth-last-child";
private readonly Selector? _previous;
private readonly bool _reversed;
internal protected NthChildSelector(Selector? previous, int step, int offset, bool reversed)
{
_previous = previous;
Step = step;
Offset = offset;
_reversed = reversed;
}
public NthChildSelector(Selector? previous, int step, int offset)
: this(previous, step, offset, false)
{
}
public override bool InTemplate => _previous?.InTemplate ?? false;
public override bool IsCombinator => false;
public override Type? TargetType => _previous?.TargetType;
public int Step { get; }
public int Offset { get; }
protected override SelectorMatch Evaluate(IStyleable control, bool subscribe)
{
var logical = (ILogical)control;
var controlParent = logical.LogicalParent;
if (controlParent is IChildIndexProvider childIndexProvider)
{
var (index, totalCount) = childIndexProvider.GetChildIndex(logical);
if (index < 0)
{
return SelectorMatch.NeverThisInstance;
}
if (_reversed)
{
if (totalCount is int totalCountValue)
{
index = totalCountValue - index;
}
else
{
return SelectorMatch.NeverThisInstance;
}
}
else
{
// nth child index is 1-based
index += 1;
}
var n = Math.Sign(Step);
var diff = index - Offset;
var match = diff == 0 || (Math.Sign(diff) == n && diff % Step == 0);
return match ? SelectorMatch.AlwaysThisInstance : SelectorMatch.NeverThisInstance;
}
else
{
return SelectorMatch.NeverThisInstance;
}
}
protected override Selector? MovePrevious() => _previous;
public override string ToString()
{
var expectedCapacity = NthLastChildSelectorName.Length + 8;
var stringBuilder = new StringBuilder(_previous?.ToString(), expectedCapacity);
stringBuilder.Append(':');
stringBuilder.Append(_reversed ? NthLastChildSelectorName : NthChildSelectorName);
stringBuilder.Append('(');
var hasStep = false;
if (Step != 0)
{
hasStep = true;
stringBuilder.Append(Step);
stringBuilder.Append('n');
}
if (Offset > 0)
{
if (hasStep)
{
stringBuilder.Append('+');
}
stringBuilder.Append(Offset);
}
else if (Offset < 0)
{
stringBuilder.Append('-');
stringBuilder.Append(-Offset);
}
stringBuilder.Append(')');
return stringBuilder.ToString();
}
}
}

10
src/Avalonia.Styling/Styling/Selectors.cs

@ -123,6 +123,16 @@ namespace Avalonia.Styling
return new NotSelector(previous, argument);
}
public static Selector NthChild(this Selector previous, int step, int offset)
{
return new NthChildSelector(previous, step, offset);
}
public static Selector NthLastChild(this Selector previous, int step, int offset)
{
return new NthLastChildSelector(previous, step, offset);
}
/// <summary>
/// Returns a selector which matches a type.
/// </summary>

35
src/Markup/Avalonia.Markup.Xaml.Loader/CompilerExtensions/Transformers/AvaloniaXamlIlSelectorTransformer.cs

@ -97,6 +97,12 @@ namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers
case SelectorGrammar.NotSyntax not:
result = new XamlIlNotSelector(result, Create(not.Argument, typeResolver));
break;
case SelectorGrammar.NthChildSyntax nth:
result = new XamlIlNthChildSelector(result, nth.Step, nth.Offset, XamlIlNthChildSelector.SelectorType.NthChild);
break;
case SelectorGrammar.NthLastChildSyntax nth:
result = new XamlIlNthChildSelector(result, nth.Step, nth.Offset, XamlIlNthChildSelector.SelectorType.NthLastChild);
break;
case SelectorGrammar.CommaSyntax comma:
if (results == null)
results = new XamlIlOrSelectorNode(node, selectorType);
@ -273,6 +279,35 @@ namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers
}
}
class XamlIlNthChildSelector : XamlIlSelectorNode
{
private readonly int _step;
private readonly int _offset;
private readonly SelectorType _type;
public enum SelectorType
{
NthChild,
NthLastChild
}
public XamlIlNthChildSelector(XamlIlSelectorNode previous, int step, int offset, SelectorType type) : base(previous)
{
_step = step;
_offset = offset;
_type = type;
}
public override IXamlType TargetType => Previous?.TargetType;
protected override void DoEmit(XamlEmitContext<IXamlILEmitter, XamlILNodeEmitResult> context, IXamlILEmitter codeGen)
{
codeGen.Ldc_I4(_step);
codeGen.Ldc_I4(_offset);
EmitCall(context, codeGen,
m => m.Name == _type.ToString() && m.Parameters.Count == 3);
}
}
class XamlIlPropertyEqualsSelector : XamlIlSelectorNode
{
public XamlIlPropertyEqualsSelector(XamlIlSelectorNode previous,

105
src/Markup/Avalonia.Markup/Markup/Parsers/SelectorGrammar.cs

@ -160,11 +160,13 @@ namespace Avalonia.Markup.Parsers
if (identifier.IsEmpty)
{
throw new ExpressionParseException(r.Position, "Expected class name or is selector after ':'.");
throw new ExpressionParseException(r.Position, "Expected class name, is, nth-child or nth-last-child selector after ':'.");
}
const string IsKeyword = "is";
const string NotKeyword = "not";
const string NthChildKeyword = "nth-child";
const string NthLastChildKeyword = "nth-last-child";
if (identifier.SequenceEqual(IsKeyword.AsSpan()) && r.TakeIf('('))
{
@ -181,6 +183,20 @@ namespace Avalonia.Markup.Parsers
var syntax = new NotSyntax { Argument = argument };
return (State.Middle, syntax);
}
if (identifier.SequenceEqual(NthChildKeyword.AsSpan()) && r.TakeIf('('))
{
var (step, offset) = ParseNthChildArguments(ref r);
var syntax = new NthChildSyntax { Step = step, Offset = offset };
return (State.Middle, syntax);
}
if (identifier.SequenceEqual(NthLastChildKeyword.AsSpan()) && r.TakeIf('('))
{
var (step, offset) = ParseNthChildArguments(ref r);
var syntax = new NthLastChildSyntax { Step = step, Offset = offset };
return (State.Middle, syntax);
}
else
{
return (
@ -191,7 +207,6 @@ namespace Avalonia.Markup.Parsers
});
}
}
private static (State, ISyntax?) ParseTraversal(ref CharacterReader r)
{
r.SkipWhitespace();
@ -302,6 +317,70 @@ namespace Avalonia.Markup.Parsers
return syntax;
}
private static (int step, int offset) ParseNthChildArguments(ref CharacterReader r)
{
int step = 0;
int offset = 0;
if (r.Peek == 'o')
{
var constArg = r.TakeUntil(')').ToString().Trim();
if (constArg.Equals("odd", StringComparison.Ordinal))
{
step = 2;
offset = 1;
}
else
{
throw new ExpressionParseException(r.Position, $"Expected nth-child(odd). Actual '{constArg}'.");
}
}
else if (r.Peek == 'e')
{
var constArg = r.TakeUntil(')').ToString().Trim();
if (constArg.Equals("even", StringComparison.Ordinal))
{
step = 2;
offset = 0;
}
else
{
throw new ExpressionParseException(r.Position, $"Expected nth-child(even). Actual '{constArg}'.");
}
}
else
{
var stepOrOffsetSpan = r.TakeWhile(c => c != ')' && c != 'n');
if (!int.TryParse(stepOrOffsetSpan.ToString().Trim(), out var stepOrOffset))
{
throw new ExpressionParseException(r.Position, "Couldn't parse nth-child step or offset value. Integer was expected.");
}
if (r.Peek == ')')
{
step = 0;
offset = stepOrOffset;
}
else
{
step = stepOrOffset;
r.Skip(1); // skip 'n'
var offsetSpan = r.TakeUntil(')').TrimStart();
if (offsetSpan.Length != 0
&& !int.TryParse(offsetSpan.ToString().Trim(), out offset))
{
throw new ExpressionParseException(r.Position, "Couldn't parse nth-child offset value. Integer was expected.");
}
}
}
Expect(ref r, ')');
return (step, offset);
}
private static void Expect(ref CharacterReader r, char c)
{
if (r.End)
@ -419,6 +498,28 @@ namespace Avalonia.Markup.Parsers
}
}
public class NthChildSyntax : ISyntax
{
public int Offset { get; set; }
public int Step { get; set; }
public override bool Equals(object? obj)
{
return (obj is NthChildSyntax nth) && nth.Offset == Offset && nth.Step == Step;
}
}
public class NthLastChildSyntax : ISyntax
{
public int Offset { get; set; }
public int Step { get; set; }
public override bool Equals(object? obj)
{
return (obj is NthLastChildSyntax nth) && nth.Offset == Offset && nth.Step == Step;
}
}
public class CommaSyntax : ISyntax
{
public override bool Equals(object? obj)

6
src/Markup/Avalonia.Markup/Markup/Parsers/SelectorParser.cs

@ -104,6 +104,12 @@ namespace Avalonia.Markup.Parsers
case SelectorGrammar.NotSyntax not:
result = result.Not(x => Create(not.Argument));
break;
case SelectorGrammar.NthChildSyntax nth:
result = result.NthChild(nth.Step, nth.Offset);
break;
case SelectorGrammar.NthLastChildSyntax nth:
result = result.NthLastChild(nth.Step, nth.Offset);
break;
case SelectorGrammar.CommaSyntax comma:
if (results == null)
{

90
tests/Avalonia.Markup.UnitTests/Parsers/SelectorGrammarTests.cs

@ -236,6 +236,96 @@ namespace Avalonia.Markup.UnitTests.Parsers
result);
}
[Fact]
public void OfType_NthChild()
{
var result = SelectorGrammar.Parse("Button:nth-child(2n+1)");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.NthChildSyntax()
{
Step = 2,
Offset = 1
}
},
result);
}
[Fact]
public void OfType_NthChild_Without_Offset()
{
var result = SelectorGrammar.Parse("Button:nth-child(2147483647n)");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.NthChildSyntax()
{
Step = int.MaxValue,
Offset = 0
}
},
result);
}
[Fact]
public void OfType_NthLastChild()
{
var result = SelectorGrammar.Parse("Button:nth-last-child(2n+1)");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.NthLastChildSyntax()
{
Step = 2,
Offset = 1
}
},
result);
}
[Fact]
public void OfType_NthChild_Odd()
{
var result = SelectorGrammar.Parse("Button:nth-child(odd)");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.NthChildSyntax()
{
Step = 2,
Offset = 1
}
},
result);
}
[Fact]
public void OfType_NthChild_Even()
{
var result = SelectorGrammar.Parse("Button:nth-child(even)");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.NthChildSyntax()
{
Step = 2,
Offset = 0
}
},
result);
}
[Fact]
public void Is_Descendent_Not_OfType_Class()
{

59
tests/Avalonia.Markup.Xaml.UnitTests/Xaml/StyleTests.cs

@ -267,6 +267,65 @@ namespace Avalonia.Markup.Xaml.UnitTests.Xaml
}
}
[Fact]
public void Style_Can_Use_NthChild_Selector()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='Border.foo:nth-child(2n+1)'>
<Setter Property='Background' Value='Red'/>
</Style>
</Window.Styles>
<StackPanel>
<Border x:Name='b1' Classes='foo'/>
<Border x:Name='b2' />
</StackPanel>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var b1 = window.FindControl<Border>("b1");
var b2 = window.FindControl<Border>("b2");
Assert.Equal(Colors.Red, ((ISolidColorBrush)b1.Background).Color);
Assert.Null(b2.Background);
}
}
[Fact]
public void Style_Can_Use_NthChild_Selector_After_Reoder()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='Border:nth-child(2n+1)'>
<Setter Property='Background' Value='Red'/>
</Style>
</Window.Styles>
<StackPanel x:Name='parent'>
<Border x:Name='b1' />
<Border x:Name='b2' />
</StackPanel>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var parent = window.FindControl<StackPanel>("parent");
var b1 = window.FindControl<Border>("b1");
var b2 = window.FindControl<Border>("b2");
parent.Children.Remove(b1);
parent.Children.Add(b1);
Assert.Null(b1.Background);
Assert.Equal(Colors.Red, ((ISolidColorBrush)b2.Background).Color);
}
}
[Fact]
public void Style_Can_Use_Or_Selector_1()
{

217
tests/Avalonia.Styling.UnitTests/SelectorTests_NthChild.cs

@ -0,0 +1,217 @@
using Avalonia.Controls;
using Xunit;
namespace Avalonia.Styling.UnitTests
{
public class SelectorTests_NthChild
{
[Theory]
[InlineData(2, 0, ":nth-child(2n)")]
[InlineData(2, 1, ":nth-child(2n+1)")]
[InlineData(1, 0, ":nth-child(1n)")]
[InlineData(4, -1, ":nth-child(4n-1)")]
[InlineData(0, 1, ":nth-child(1)")]
[InlineData(0, -1, ":nth-child(-1)")]
[InlineData(int.MaxValue, int.MinValue + 1, ":nth-child(2147483647n-2147483647)")]
public void Not_Selector_Should_Have_Correct_String_Representation(int step, int offset, string expected)
{
var target = default(Selector).NthChild(step, offset);
Assert.Equal(expected, target.ToString());
}
[Fact]
public void Nth_Child_Match_Control_In_Panel()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthChild(2, 0);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b1).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b2).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b3).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b4).Result);
}
[Fact]
public void Nth_Child_Match_Control_In_Panel_With_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthChild(2, 1);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b1).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b2).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b3).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b4).Result);
}
[Fact]
public void Nth_Child_Match_Control_In_Panel_With_Negative_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthChild(4, -1);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b1).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b2).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b3).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b4).Result);
}
[Fact]
public void Nth_Child_Match_Control_In_Panel_With_Singular_Step()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthChild(1, 2);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b1).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b2).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b3).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b4).Result);
}
[Fact]
public void Nth_Child_Match_Control_In_Panel_With_Singular_Step_With_Negative_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthChild(1, -1);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b1).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b2).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b3).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b4).Result);
}
[Fact]
public void Nth_Child_Match_Control_In_Panel_With_Zero_Step_With_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthChild(0, 2);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b1).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b2).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b3).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b4).Result);
}
[Fact]
public void Nth_Child_Doesnt_Match_Control_In_Panel_With_Zero_Step_With_Negative_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthChild(0, -2);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b1).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b2).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b3).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b4).Result);
}
[Fact]
public void Nth_Child_Match_Control_In_Panel_With_Previous_Selector()
{
Border b1, b2;
Button b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new Control[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Button(),
b4 = new Button()
});
var previous = default(Selector).OfType<Border>();
var target = previous.NthChild(2, 0);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b1).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b2).Result);
Assert.Equal(SelectorMatchResult.NeverThisType, target.Match(b3).Result);
Assert.Equal(SelectorMatchResult.NeverThisType, target.Match(b4).Result);
}
[Fact]
public void Nth_Child_Doesnt_Match_Control_Out_Of_Panel_Parent()
{
Border b1;
var contentControl = new ContentControl();
contentControl.Content = b1 = new Border();
var target = default(Selector).NthChild(1, 0);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b1).Result);
}
[Fact]
public void Returns_Correct_TargetType()
{
var target = new NthChildSelector(default(Selector).OfType<Control1>(), 1, 0);
Assert.Equal(typeof(Control1), target.TargetType);
}
public class Control1 : Control
{
}
}
}

217
tests/Avalonia.Styling.UnitTests/SelectorTests_NthLastChild.cs

@ -0,0 +1,217 @@
using Avalonia.Controls;
using Xunit;
namespace Avalonia.Styling.UnitTests
{
public class SelectorTests_NthLastChild
{
[Theory]
[InlineData(2, 0, ":nth-last-child(2n)")]
[InlineData(2, 1, ":nth-last-child(2n+1)")]
[InlineData(1, 0, ":nth-last-child(1n)")]
[InlineData(4, -1, ":nth-last-child(4n-1)")]
[InlineData(0, 1, ":nth-last-child(1)")]
[InlineData(0, -1, ":nth-last-child(-1)")]
[InlineData(int.MaxValue, int.MinValue + 1, ":nth-last-child(2147483647n-2147483647)")]
public void Not_Selector_Should_Have_Correct_String_Representation(int step, int offset, string expected)
{
var target = default(Selector).NthLastChild(step, offset);
Assert.Equal(expected, target.ToString());
}
[Fact]
public void Nth_Child_Match_Control_In_Panel()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthLastChild(2, 0);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b1).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b2).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b3).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b4).Result);
}
[Fact]
public void Nth_Child_Match_Control_In_Panel_With_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthLastChild(2, 1);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b1).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b2).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b3).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b4).Result);
}
[Fact]
public void Nth_Child_Match_Control_In_Panel_With_Negative_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthLastChild(4, -1);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b1).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b2).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b3).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b4).Result);
}
[Fact]
public void Nth_Child_Match_Control_In_Panel_With_Singular_Step()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthLastChild(1, 2);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b1).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b2).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b3).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b4).Result);
}
[Fact]
public void Nth_Child_Match_Control_In_Panel_With_Singular_Step_With_Negative_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthLastChild(1, -2);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b1).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b2).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b3).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b4).Result);
}
[Fact]
public void Nth_Child_Match_Control_In_Panel_With_Zero_Step_With_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthLastChild(0, 2);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b1).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b2).Result);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b3).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b4).Result);
}
[Fact]
public void Nth_Child_Doesnt_Match_Control_In_Panel_With_Zero_Step_With_Negative_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthLastChild(0, -2);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b1).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b2).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b3).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b4).Result);
}
[Fact]
public void Nth_Child_Match_Control_In_Panel_With_Previous_Selector()
{
Border b1, b2;
Button b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new Control[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Button(),
b4 = new Button()
});
var previous = default(Selector).OfType<Border>();
var target = previous.NthLastChild(2, 0);
Assert.Equal(SelectorMatchResult.AlwaysThisInstance, target.Match(b1).Result);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b2).Result);
Assert.Equal(SelectorMatchResult.NeverThisType, target.Match(b3).Result);
Assert.Equal(SelectorMatchResult.NeverThisType, target.Match(b4).Result);
}
[Fact]
public void Nth_Child_Doesnt_Match_Control_Out_Of_Panel_Parent()
{
Border b1;
var contentControl = new ContentControl();
contentControl.Content = b1 = new Border();
var target = default(Selector).NthLastChild(1, 0);
Assert.Equal(SelectorMatchResult.NeverThisInstance, target.Match(b1).Result);
}
[Fact]
public void Returns_Correct_TargetType()
{
var target = new NthLastChildSelector(default(Selector).OfType<Control1>(), 1, 0);
Assert.Equal(typeof(Control1), target.TargetType);
}
public class Control1 : Control
{
}
}
}
Loading…
Cancel
Save