< Summary

Information
Class: MyNet.UI.ViewModels.List.Sorting.SortingViewModel<T>
Assembly: MyNet.UI
File(s): https://raw.githubusercontent.com/sandre58/MyNet/5aaaab311aa14541478b9e402357d98b657a23e4/src/MyNet.UI/ViewModels/List/Sorting/SortingViewModel.cs
Tag: 342_31701152804
Line coverage
0%
Covered lines: 0
Uncovered lines: 62
Coverable lines: 62
Total lines: 221
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 34
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
CreateBuilder()100%210%
.ctor(...)0%7280%
set_CurrentSorting(...)100%210%
get_HasActiveSorting()100%210%
Apply()100%210%
Clear()0%620%
Reset()0%2040%
SetActive(...)0%620%
Toggle(...)0%4260%
SetDirection(...)0%620%
ComputeCurrentSorting()0%4260%
HandlePropertyChanged(...)100%210%
RaiseSortingChanged()0%620%
Find(...)100%210%
FindMatching(...)100%210%
DisposeManagedResources()0%620%

File(s)

https://raw.githubusercontent.com/sandre58/MyNet/5aaaab311aa14541478b9e402357d98b657a23e4/src/MyNet.UI/ViewModels/List/Sorting/SortingViewModel.cs

#LineLine coverage
 1// -----------------------------------------------------------------------
 2// <copyright file="SortingViewModel.cs" company="Stéphane ANDRE">
 3// Copyright (c) Stéphane ANDRE. All rights reserved.
 4// </copyright>
 5// -----------------------------------------------------------------------
 6
 7using System;
 8using System.Collections.Generic;
 9using System.Collections.ObjectModel;
 10using System.ComponentModel;
 11using System.Linq;
 12using MyNet.Collections;
 13using MyNet.Observable;
 14using MyNet.Observable.Collections.Sorting;
 15using MyNet.Utilities.Deferring;
 16
 17namespace MyNet.UI.ViewModels.List.Sorting;
 18
 19/// <summary>
 20/// Represents a view model for managing sorting configuration of a collection.
 21/// </summary>
 22/// <typeparam name="T">The type of items in the collection.</typeparam>
 23public class SortingViewModel<T> : ObservableObject, ISortingViewModel<T>
 24{
 25    private readonly DeferredAction _deferredAction;
 26
 27    /// <summary>
 28    /// Creates a fluent builder used to configure and instantiate a <see cref="SortingViewModel{T}"/>.
 29    /// </summary>
 030    public static SortingViewModelBuilder<T> CreateBuilder() => new();
 31
 32    /// <summary>
 33    /// Initializes a new instance of the <see cref="SortingViewModel{T}"/> class with the specified sorting properties 
 34    /// </summary>
 35    /// <param name="properties">The sorting properties for the collection.</param>
 36    /// <param name="defaultSorting">The optional default sorting configuration.</param>
 037    public SortingViewModel(IEnumerable<ISortingPropertyViewModel<T>> properties, IEnumerable<ISortingProperty<T>>? defa
 38    {
 039        Properties = [with([.. properties])];
 040        DefaultSorting = defaultSorting?.ToList() ?? [];
 41
 042        _deferredAction = new DeferredAction(RaiseSortingChanged);
 43
 044        Reset();
 45
 046        foreach (var property in Properties)
 047            property.PropertyChanged += HandlePropertyChanged;
 048    }
 49
 50    /// <summary>
 51    /// Gets the collection of sorting property view models that can be configured for sorting. This collection is read-
 52    /// </summary>
 53    public ReadOnlyObservableCollection<ISortingPropertyViewModel<T>> Properties { get; }
 54
 55    /// <summary>
 56    /// Gets the current sorting configuration built from the UI. This collection is read-only and represents the active
 57    /// </summary>
 058    public IReadOnlyList<ISortingProperty<T>> CurrentSorting { get; private set => SetProperty(ref field, value); } = []
 59
 60    /// <summary>
 61    /// Gets the default sorting configuration for the collection. This collection is read-only and represents the initi
 62    /// </summary>
 63    public IReadOnlyList<ISortingProperty<T>> DefaultSorting { get; }
 64
 65    /// <summary>
 66    /// Gets a value indicating whether there are any active sorting properties in the current configuration. This prope
 67    /// </summary>
 068    public bool HasActiveSorting => CurrentSorting.Count > 0;
 69
 70    /// <summary>
 71    /// Occurs when the sorting configuration has changed. Subscribers can react to this event to apply the new sorting 
 72    /// </summary>
 73    public event EventHandler<SortingChangedEventArgs<T>>? SortingChanged;
 74
 75    /// <summary>
 76    /// Applies the current sorting configuration. This method triggers the sorting update process by invoking the defer
 77    /// </summary>
 078    public void Apply() => _deferredAction.Request();
 79
 80    /// <summary>
 81    /// Clears all active sorting by disabling all sorting properties. This method iterates through the Properties colle
 82    /// </summary>
 83    public void Clear()
 84    {
 085        using (_deferredAction.Defer())
 086            Properties.ForEach(p => p.IsEnabled = false);
 087    }
 88
 89    /// <summary>
 90    /// Resets the sorting configuration to its default state. This method first clears all active sorting properties an
 91    /// </summary>
 92    public void Reset()
 93    {
 094        using (_deferredAction.Defer())
 95        {
 096            Clear();
 97
 098            foreach (var def in DefaultSorting)
 99            {
 0100                var vm = FindMatching(def);
 101
 0102                if (vm == null) continue;
 0103                vm.IsEnabled = true;
 0104                vm.Direction = def.Direction;
 105            }
 106        }
 0107    }
 108
 109    /// <summary>
 110    /// Sets the active state of a sorting property identified by the specified key. This method finds the sorting prope
 111    /// </summary>
 112    /// <param name="key">The key of the sorting property to update.</param>
 113    /// <param name="isActive">A value indicating whether the sorting property should be active.</param>
 114    public void SetActive(string key, bool isActive)
 115    {
 0116        var property = Find(key);
 117
 0118        if (property is null) return;
 119
 0120        using (_deferredAction.Defer())
 0121            property.IsEnabled = isActive;
 0122    }
 123
 124    /// <summary>
 125    /// Toggles the sort direction of a sorting property identified by the specified key. If the sorting property is cur
 126    /// </summary>
 127    /// <param name="key">The key of the sorting property to toggle.</param>
 128    public void Toggle(string key)
 129    {
 0130        var property = Find(key);
 131
 0132        if (property is null) return;
 133
 0134        using (_deferredAction.Defer())
 135        {
 0136            if (!property.IsEnabled)
 137            {
 0138                property.IsEnabled = true;
 0139                property.Direction = ListSortDirection.Ascending;
 140            }
 141            else
 142            {
 0143                property.Direction = property.Direction == ListSortDirection.Ascending
 0144                    ? ListSortDirection.Descending
 0145                    : ListSortDirection.Ascending;
 146            }
 0147        }
 0148    }
 149
 150    /// <summary>
 151    /// Sets the sort direction of a sorting property identified by the specified key. This method finds the sorting pro
 152    /// </summary>
 153    /// <param name="key">The key of the sorting property to update.</param>
 154    /// <param name="direction">The direction to set for the sorting property.</param>
 155    public void SetDirection(string key, ListSortDirection direction)
 156    {
 0157        var property = Find(key);
 158
 0159        if (property is null) return;
 160
 0161        using (_deferredAction.Defer())
 162        {
 0163            property.IsEnabled = true;
 0164            property.Direction = direction;
 0165        }
 0166    }
 167
 168    /// <summary>
 169    /// Computes the current sorting configuration based on the enabled sorting properties in the Properties collection.
 170    /// </summary>
 171    /// <returns>A read-only list of the current sorting properties.</returns>
 172    private IReadOnlyList<ISortingProperty<T>> ComputeCurrentSorting() =>
 0173    [
 0174        .. Properties
 0175            .Where(p => p.IsEnabled)
 0176            .OrderBy(p => p.ActivatedAt)
 0177            .Select(p => p.Build())
 0178    ];
 179
 180    /// <summary>
 181    /// Handles the PropertyChanged event for the sorting property view models. When any property of a sorting property 
 182    /// </summary>
 183    /// <param name="sender">The source of the event.</param>
 184    /// <param name="e">The event data.</param>
 0185    private void HandlePropertyChanged(object? sender, PropertyChangedEventArgs e) => _deferredAction.Request();
 186
 187    /// <summary>
 188    /// Handles the logic for when the sorting configuration has changed. This method computes the current sorting confi
 189    /// </summary>
 190    private void RaiseSortingChanged()
 191    {
 0192        CurrentSorting = ComputeCurrentSorting();
 0193        SortingChanged?.Invoke(this, new SortingChangedEventArgs<T>(CurrentSorting));
 0194    }
 195
 196    /// <summary>
 197    /// Finds a sorting property view model in the Properties collection by its unique key. This method searches through
 198    /// </summary>
 199    /// <param name="key">The unique key of the sorting property to find.</param>
 200    /// <returns>The sorting property view model with the specified key, or null if not found.</returns>
 201    private ISortingPropertyViewModel<T>? Find(string key)
 0202        => Properties.FirstOrDefault(p => p.Key == key);
 203
 204    /// <summary>
 205    /// Finds a sorting property view model in the Properties collection that matches the specified sorting property. Th
 206    /// </summary>
 207    /// <param name="property">The sorting property to match.</param>
 208    /// <returns>The sorting property view model that matches the specified sorting property, or null if not found.</ret
 209    private ISortingPropertyViewModel<T>? FindMatching(ISortingProperty<T> property)
 0210        => Properties.FirstOrDefault(p => p.Matches(property));
 211
 212    /// <inheritdoc />
 213    protected override void DisposeManagedResources()
 214    {
 0215        foreach (var property in Properties)
 0216            property.PropertyChanged -= HandlePropertyChanged;
 217
 0218        base.DisposeManagedResources();
 0219    }
 220}
 221