using Connected.Annotations; using Microsoft.AspNetCore.Components; namespace Connected.Components; public abstract class ItemsControlBase : UIComponent where TChildComponent : UIComponent { /// /// Collection of T /// [Parameter] [Category(CategoryTypes.General.Data)] public RenderFragment ChildContent { get; set; } /// /// Items - will be ignored when ItemsSource is not null /// public List Items { get; } = new List(); private int _selectedIndexField = -1; /// /// Selected Item's index /// [Parameter] [Category(CategoryTypes.General.Behavior)] public int SelectedIndex { get => _selectedIndexField; set { if (SelectedIndex == value) return; LastContainer = _selectedIndexField >= 0 ? SelectedContainer : null; _selectedIndexField = value; SelectionChanged(); StateHasChanged(); SelectedIndexChanged.InvokeAsync(value); } } [Parameter] public EventCallback SelectedIndexChanged { get; set; } /// /// Gets the Selected TChildComponent /// public TChildComponent LastContainer { get; private set; } = null; /// /// Gets the Selected TChildComponent /// public TChildComponent SelectedContainer { get => SelectedIndex >= 0 && Items.Count > SelectedIndex ? Items[SelectedIndex] : null; } protected override Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { if (Items.Count > 0 && SelectedIndex < 0) MoveTo(0); } return base.OnAfterRenderAsync(firstRender); } internal bool _moveNext = true; /// /// Move to Previous Item /// public void Previous() { _moveNext = false; if (SelectedIndex > 0) SelectedIndex--; else SelectedIndex = Items.Count - 1; } /// /// Move to Next Item /// public void Next() { _moveNext = true; if (SelectedIndex < (Items.Count - 1)) SelectedIndex++; else SelectedIndex = 0; } /// /// Move to Item at desired index /// public void MoveTo(int index) { if (SelectedIndex != index) { _moveNext = index >= SelectedIndex; SelectedIndex = index; } } protected virtual void SelectionChanged() { } public virtual void AddItem(TChildComponent item) { } }