feat: grids, radar and document lines (#28)
Lists need one component for the whole app (SPEC §10.6-§10.7): a list query model that turns search, filters, sort and paging into SQL or runs over rows in memory, a KhGrid that pages 100,000 rows while scrolling (or in pages) with sort, selection, keyboard, inline edit, totals, row menu, saved column layout and CSV/XLSX export, the KhRadar around it with search, quick filters, a filter builder and saved filters, a radar window for F4 lookups, and KhLinesGrid for document lines typed from the keyboard. Checked in the browser on the component catalog and the sample document. Fixed on the way: the grid height lost to the flex basis, a new search kept the old scroll position, Save of a filter needed a second click, page shortcuts (Ctrl+Canc) reached the record behind a modal window, Escape did nothing once focus left a dialog, totals did not follow an inline edit, and amounts exported as 0 instead of 0,00. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d0f9d0e651
commit
75d60ee4c4
18 files changed
+3776
-28
No files matched your search
@@ -0,0 +1,54 @@
|
||||
namespace Khaemhat.Application.Querying;
|
||||
|
||||
/// <summary>
|
||||
/// A <see cref="ListSource{T}"/> over rows kept in memory (small tables, catalogs, tests). The rows a request selects
|
||||
/// are kept until the search, filters or ordering change, so scrolling through the pages of 100,000 rows only cuts
|
||||
/// slices.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The row type.</typeparam>
|
||||
/// <param name="rows">The rows.</param>
|
||||
/// <param name="fields">The fields.</param>
|
||||
public sealed class InMemoryListSource<T>(IReadOnlyList<T> rows, ListFields<T> fields)
|
||||
where T : class
|
||||
{
|
||||
private readonly Lock _lock = new();
|
||||
private (ListQuery Query, IReadOnlyList<T> Rows)? _last;
|
||||
|
||||
/// <summary>The fields.</summary>
|
||||
public ListFields<T> Fields => fields;
|
||||
|
||||
/// <summary>Answers a request.</summary>
|
||||
/// <param name="query">The request.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public Task<ListPage<T>> QueryAsync(ListQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
return Task.FromResult(fields.Page(Selected(query), query));
|
||||
}
|
||||
|
||||
/// <summary>Every row a request selects, in order, for exports.</summary>
|
||||
/// <param name="query">The request; its page is ignored.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
public IReadOnlyList<T> All(ListQuery query) => Selected(query);
|
||||
|
||||
private IReadOnlyList<T> Selected(ListQuery query)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_last is { } last && last.Query.SameRows(query))
|
||||
{
|
||||
return last.Rows;
|
||||
}
|
||||
}
|
||||
|
||||
var selected = fields.Select(rows, query);
|
||||
lock (_lock)
|
||||
{
|
||||
_last = (query, selected);
|
||||
}
|
||||
|
||||
return selected;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
using System.Globalization;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Querying;
|
||||
|
||||
/// <summary>
|
||||
/// The fields a list can search, filter, order and total, each bound to a property of the row. One description serves
|
||||
/// both sides: <see cref="Apply(Query{T}, ListQuery)"/> adds conditions, ordering and page to a repository query (SQL,
|
||||
/// case-insensitive LIKE for texts), <see cref="Apply(IEnumerable{T}, ListQuery)"/> runs the same request on rows in
|
||||
/// memory.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The row type.</typeparam>
|
||||
public sealed class ListFields<T>
|
||||
where T : class
|
||||
{
|
||||
private readonly Dictionary<string, ListField<T>> _fields = new(StringComparer.Ordinal);
|
||||
private readonly List<ListField<T>> _ordered = [];
|
||||
|
||||
/// <summary>The fields, in the order added.</summary>
|
||||
public IReadOnlyList<ListField<T>> Fields => _ordered;
|
||||
|
||||
/// <summary>The ordering used when the request has none, so that pages do not overlap.</summary>
|
||||
public IReadOnlyList<ListSort> DefaultSort { get; private set; } = [];
|
||||
|
||||
/// <summary>Adds a field.</summary>
|
||||
/// <typeparam name="TValue">The type of the property.</typeparam>
|
||||
/// <param name="id">The id used in filters and orderings.</param>
|
||||
/// <param name="selector">The property.</param>
|
||||
/// <param name="searchable">Whether the search box looks in it (texts only).</param>
|
||||
/// <param name="total">Whether the page carries its sum (numbers only).</param>
|
||||
/// <returns>This, to chain.</returns>
|
||||
public ListFields<T> Add<TValue>(string id, Expression<Func<T, TValue>> selector, bool searchable = false, bool total = false)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(id);
|
||||
ArgumentNullException.ThrowIfNull(selector);
|
||||
if (searchable && typeof(TValue) != typeof(string))
|
||||
{
|
||||
throw new ArgumentException($"Only text fields can be searched: {id}.", nameof(searchable));
|
||||
}
|
||||
|
||||
if (total && ListField<T, TValue>.Numeric is null)
|
||||
{
|
||||
throw new ArgumentException($"Only number fields can be totalled: {id}.", nameof(total));
|
||||
}
|
||||
|
||||
var field = new ListField<T, TValue>(id, selector, searchable, total);
|
||||
_fields.Add(id, field);
|
||||
_ordered.Add(field);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Sets the ordering used when the request has none.</summary>
|
||||
/// <param name="sort">The ordering; the last field should be unique (the code or the id).</param>
|
||||
/// <returns>This, to chain.</returns>
|
||||
public ListFields<T> OrderByDefault(params ListSort[] sort)
|
||||
{
|
||||
foreach (var item in sort)
|
||||
{
|
||||
_ = Get(item.Field);
|
||||
}
|
||||
|
||||
DefaultSort = sort;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>A field by id.</summary>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <returns>The field, or <see langword="null"/>.</returns>
|
||||
public ListField<T>? Find(string id) => _fields.GetValueOrDefault(id);
|
||||
|
||||
/// <summary>Whether a filter can be applied: known field, operator fit for its type, readable values.</summary>
|
||||
/// <param name="filter">The filter, for example one read from the saved filters.</param>
|
||||
/// <returns>Whether it is valid.</returns>
|
||||
public bool IsValid(ListFilter filter)
|
||||
{
|
||||
try
|
||||
{
|
||||
_ = Condition(Expression.Parameter(typeof(T), "x"), filter, inMemory: true);
|
||||
return true;
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Adds the conditions, the ordering and the page of a request to a repository query.</summary>
|
||||
/// <param name="query">The query, possibly with conditions of its own (the company, the state...).</param>
|
||||
/// <param name="list">The request.</param>
|
||||
/// <returns>The query.</returns>
|
||||
public Query<T> Apply(Query<T> query, ListQuery list)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
ArgumentNullException.ThrowIfNull(list);
|
||||
if (Predicate(list, inMemory: false) is { } predicate)
|
||||
{
|
||||
query = query.Where(predicate);
|
||||
}
|
||||
|
||||
foreach (var sort in SortOf(list))
|
||||
{
|
||||
query = Get(sort.Field).OrderQuery(query, sort.Descending);
|
||||
}
|
||||
|
||||
return query.Page(Math.Max(0, list.Offset), Math.Clamp(list.Limit, 1, ListQuery.MaxLimit));
|
||||
}
|
||||
|
||||
/// <summary>Runs a request on rows in memory: filters, totals, ordering and page.</summary>
|
||||
/// <param name="source">The rows.</param>
|
||||
/// <param name="list">The request.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public ListPage<T> Apply(IEnumerable<T> source, ListQuery list)
|
||||
{
|
||||
var rows = Select(source, list);
|
||||
return Page(rows, list);
|
||||
}
|
||||
|
||||
/// <summary>The rows a request selects, filtered and ordered, without paging (for exports and caches).</summary>
|
||||
/// <param name="source">The rows.</param>
|
||||
/// <param name="list">The request.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
public IReadOnlyList<T> Select(IEnumerable<T> source, ListQuery list)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
ArgumentNullException.ThrowIfNull(list);
|
||||
if (Predicate(list, inMemory: true) is { } predicate)
|
||||
{
|
||||
source = source.Where(predicate.Compile());
|
||||
}
|
||||
|
||||
IOrderedEnumerable<T>? ordered = null;
|
||||
foreach (var sort in SortOf(list))
|
||||
{
|
||||
ordered = Get(sort.Field).OrderMemory(source, ordered, sort.Descending);
|
||||
}
|
||||
|
||||
return [.. ordered ?? source];
|
||||
}
|
||||
|
||||
/// <summary>A page of rows already selected and ordered by <see cref="Select"/>, with the totals.</summary>
|
||||
/// <param name="rows">The rows.</param>
|
||||
/// <param name="list">The request.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public ListPage<T> Page(IReadOnlyList<T> rows, ListQuery list)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
ArgumentNullException.ThrowIfNull(list);
|
||||
var totals = _ordered.Where(f => f.Total).ToDictionary(f => f.Id, f => f.Sum(rows), StringComparer.Ordinal);
|
||||
var limit = Math.Clamp(list.Limit, 1, ListQuery.MaxLimit);
|
||||
IReadOnlyList<T> items = [.. rows.Skip(Math.Max(0, list.Offset)).Take(limit)];
|
||||
return new ListPage<T>(items, rows.Count, totals);
|
||||
}
|
||||
|
||||
/// <summary>The condition of a request (search and filters), or <see langword="null"/> when it selects everything.</summary>
|
||||
/// <param name="list">The request.</param>
|
||||
/// <param name="inMemory">Whether for rows in memory (texts compared ignoring case) or for SQL.</param>
|
||||
/// <returns>The predicate.</returns>
|
||||
public Expression<Func<T, bool>>? Predicate(ListQuery list, bool inMemory)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(list);
|
||||
var row = Expression.Parameter(typeof(T), "x");
|
||||
var parts = new List<Expression>();
|
||||
|
||||
var search = list.Search?.Trim();
|
||||
if (!string.IsNullOrEmpty(search))
|
||||
{
|
||||
// Every word must appear in some searchable field: "rossi torino" finds Rossi of Torino.
|
||||
foreach (var word in search.Split(' ', StringSplitOptions.RemoveEmptyEntries).Take(8))
|
||||
{
|
||||
var any = _ordered.Where(f => f.Searchable).Select(f => f.Search(row, word, inMemory)).Aggregate((Expression?)null, (a, b) => a is null ? b : Expression.OrElse(a, b));
|
||||
if (any is not null)
|
||||
{
|
||||
parts.Add(any);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
parts.AddRange(list.Filters.Select(filter => Condition(row, filter, inMemory)));
|
||||
return parts.Count == 0 ? null : Expression.Lambda<Func<T, bool>>(parts.Aggregate(Expression.AndAlso), row);
|
||||
}
|
||||
|
||||
private Expression Condition(ParameterExpression row, ListFilter filter, bool inMemory) =>
|
||||
(Find(filter.Field) ?? throw new ArgumentException($"Unknown field: {filter.Field}.", nameof(filter))).Condition(row, filter, inMemory);
|
||||
|
||||
private ListField<T> Get(string id) => Find(id) ?? throw new ArgumentException($"Unknown field: {id}.", nameof(id));
|
||||
|
||||
private List<ListSort> SortOf(ListQuery list)
|
||||
{
|
||||
var sort = list.Sort.Where(s => _fields.ContainsKey(s.Field)).ToList();
|
||||
foreach (var fallback in DefaultSort)
|
||||
{
|
||||
if (!sort.Any(s => s.Field == fallback.Field))
|
||||
{
|
||||
sort.Add(fallback);
|
||||
}
|
||||
}
|
||||
|
||||
return sort;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A field of a <see cref="ListFields{T}"/>.</summary>
|
||||
/// <typeparam name="T">The row type.</typeparam>
|
||||
public abstract class ListField<T>
|
||||
where T : class
|
||||
{
|
||||
private protected ListField(string id, Type valueType, bool searchable, bool total)
|
||||
{
|
||||
Id = id;
|
||||
ValueType = valueType;
|
||||
Searchable = searchable;
|
||||
Total = total;
|
||||
}
|
||||
|
||||
/// <summary>The id.</summary>
|
||||
public string Id { get; }
|
||||
|
||||
/// <summary>The type of the property (nullable included).</summary>
|
||||
public Type ValueType { get; }
|
||||
|
||||
/// <summary>Whether the search box looks in it.</summary>
|
||||
public bool Searchable { get; }
|
||||
|
||||
/// <summary>Whether the page carries its sum.</summary>
|
||||
public bool Total { get; }
|
||||
|
||||
/// <summary>The value of the field in a row.</summary>
|
||||
/// <param name="row">The row.</param>
|
||||
/// <returns>The value.</returns>
|
||||
public abstract object? ValueOf(T row);
|
||||
|
||||
internal abstract Expression Condition(ParameterExpression row, ListFilter filter, bool inMemory);
|
||||
|
||||
internal abstract Expression Search(ParameterExpression row, string text, bool inMemory);
|
||||
|
||||
internal abstract Query<T> OrderQuery(Query<T> query, bool descending);
|
||||
|
||||
internal abstract IOrderedEnumerable<T> OrderMemory(IEnumerable<T> source, IOrderedEnumerable<T>? ordered, bool descending);
|
||||
|
||||
internal abstract decimal Sum(IEnumerable<T> rows);
|
||||
}
|
||||
|
||||
/// <summary>A field bound to a property of type <typeparamref name="TValue"/>.</summary>
|
||||
/// <typeparam name="T">The row type.</typeparam>
|
||||
/// <typeparam name="TValue">The property type.</typeparam>
|
||||
internal sealed class ListField<T, TValue> : ListField<T>
|
||||
where T : class
|
||||
{
|
||||
private static readonly MethodInfo ContainsIgnoreCase = typeof(string).GetMethod(nameof(string.Contains), [typeof(string), typeof(StringComparison)])!;
|
||||
private static readonly MethodInfo StartsIgnoreCase = typeof(string).GetMethod(nameof(string.StartsWith), [typeof(string), typeof(StringComparison)])!;
|
||||
private static readonly MethodInfo ContainsText = typeof(string).GetMethod(nameof(string.Contains), [typeof(string)])!;
|
||||
private static readonly MethodInfo StartsText = typeof(string).GetMethod(nameof(string.StartsWith), [typeof(string)])!;
|
||||
private static readonly MethodInfo EnumerableContains = typeof(Enumerable).GetMethods()
|
||||
.Single(m => m.Name == nameof(Enumerable.Contains) && m.GetParameters().Length == 2).MakeGenericMethod(typeof(TValue));
|
||||
|
||||
private static readonly Type Underlying = Nullable.GetUnderlyingType(typeof(TValue)) ?? typeof(TValue);
|
||||
private readonly Expression<Func<T, TValue>> _selector;
|
||||
private readonly Func<T, TValue> _compiled;
|
||||
|
||||
public ListField(string id, Expression<Func<T, TValue>> selector, bool searchable, bool total)
|
||||
: base(id, typeof(TValue), searchable, total)
|
||||
{
|
||||
_selector = selector;
|
||||
_compiled = selector.Compile();
|
||||
}
|
||||
|
||||
/// <summary>Converts a value to decimal for the totals, or <see langword="null"/> when the type is not a number.</summary>
|
||||
public static Func<TValue, decimal?>? Numeric { get; } = Underlying switch
|
||||
{
|
||||
var t when t == typeof(decimal) => v => v is null ? null : (decimal)(object)v,
|
||||
var t when t == typeof(int) => v => v is null ? null : (int)(object)v,
|
||||
var t when t == typeof(long) => v => v is null ? null : (long)(object)v,
|
||||
var t when t == typeof(double) => v => v is null ? null : (decimal)(double)(object)v,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private static bool IsText => typeof(TValue) == typeof(string);
|
||||
|
||||
private static bool IsOrdered => !IsText && Underlying != typeof(bool) && !Underlying.IsEnum && typeof(IComparable).IsAssignableFrom(Underlying);
|
||||
|
||||
public override object? ValueOf(T row) => _compiled(row);
|
||||
|
||||
internal override Expression Search(ParameterExpression row, string text, bool inMemory) =>
|
||||
TextCall(Member(row), inMemory ? ContainsIgnoreCase : ContainsText, text, inMemory);
|
||||
|
||||
internal override Expression Condition(ParameterExpression row, ListFilter filter, bool inMemory)
|
||||
{
|
||||
var member = Member(row);
|
||||
var values = filter.Values ?? [];
|
||||
switch (filter.Operator)
|
||||
{
|
||||
case ListFilterOperator.IsEmpty or ListFilterOperator.IsNotEmpty:
|
||||
Expression empty = IsText
|
||||
? Expression.Call(typeof(string).GetMethod(nameof(string.IsNullOrEmpty))!, member)
|
||||
: typeof(TValue).IsValueType && Nullable.GetUnderlyingType(typeof(TValue)) is null
|
||||
? Expression.Constant(false)
|
||||
: Expression.Equal(member, Expression.Constant(null, typeof(TValue)));
|
||||
return filter.Operator == ListFilterOperator.IsEmpty ? empty : Expression.Not(empty);
|
||||
|
||||
case ListFilterOperator.Contains or ListFilterOperator.StartsWith:
|
||||
Require(IsText, filter);
|
||||
var method = filter.Operator == ListFilterOperator.Contains
|
||||
? (inMemory ? ContainsIgnoreCase : ContainsText)
|
||||
: (inMemory ? StartsIgnoreCase : StartsText);
|
||||
return TextCall(member, method, Single(values, filter), inMemory);
|
||||
|
||||
case ListFilterOperator.In:
|
||||
Require(values.Count > 0, filter);
|
||||
var array = values.Select(v => Convert(v, filter)).ToArray();
|
||||
return Expression.Call(EnumerableContains, Expression.Constant(array, typeof(TValue[])), member);
|
||||
|
||||
case ListFilterOperator.Between:
|
||||
Require(IsOrdered && values.Count == 2, filter);
|
||||
return Expression.AndAlso(
|
||||
Expression.GreaterThanOrEqual(member, Value(values[0], filter)),
|
||||
Expression.LessThanOrEqual(member, Value(values[1], filter)));
|
||||
|
||||
case ListFilterOperator.Equals:
|
||||
return Equal(member, Single(values, filter), filter, inMemory);
|
||||
|
||||
case ListFilterOperator.NotEquals:
|
||||
return Expression.Not(Equal(member, Single(values, filter), filter, inMemory));
|
||||
|
||||
case ListFilterOperator.GreaterThan or ListFilterOperator.GreaterOrEqual or ListFilterOperator.LessThan or ListFilterOperator.LessOrEqual:
|
||||
Require(IsOrdered, filter);
|
||||
var value = Value(Single(values, filter), filter);
|
||||
return filter.Operator switch
|
||||
{
|
||||
ListFilterOperator.GreaterThan => Expression.GreaterThan(member, value),
|
||||
ListFilterOperator.GreaterOrEqual => Expression.GreaterThanOrEqual(member, value),
|
||||
ListFilterOperator.LessThan => Expression.LessThan(member, value),
|
||||
_ => Expression.LessThanOrEqual(member, value),
|
||||
};
|
||||
|
||||
default:
|
||||
throw new ArgumentException($"Unknown operator {filter.Operator} on {Id}.", nameof(filter));
|
||||
}
|
||||
}
|
||||
|
||||
internal override Query<T> OrderQuery(Query<T> query, bool descending) =>
|
||||
descending ? query.OrderByDescending(_selector) : query.OrderBy(_selector);
|
||||
|
||||
internal override IOrderedEnumerable<T> OrderMemory(IEnumerable<T> source, IOrderedEnumerable<T>? ordered, bool descending)
|
||||
{
|
||||
var comparer = IsText ? (IComparer<TValue>)(object)StringComparer.CurrentCultureIgnoreCase : Comparer<TValue>.Default;
|
||||
return (ordered, descending) switch
|
||||
{
|
||||
(null, false) => source.OrderBy(_compiled, comparer),
|
||||
(null, true) => source.OrderByDescending(_compiled, comparer),
|
||||
(_, false) => ordered.ThenBy(_compiled, comparer),
|
||||
_ => ordered.ThenByDescending(_compiled, comparer),
|
||||
};
|
||||
}
|
||||
|
||||
internal override decimal Sum(IEnumerable<T> rows)
|
||||
{
|
||||
var numeric = Numeric ?? throw new InvalidOperationException($"{Id} is not a number.");
|
||||
return rows.Sum(r => numeric(_compiled(r)) ?? 0m);
|
||||
}
|
||||
|
||||
private static object? ConvertText(string text)
|
||||
{
|
||||
if (IsText)
|
||||
{
|
||||
return text;
|
||||
}
|
||||
|
||||
var c = CultureInfo.InvariantCulture;
|
||||
return Underlying switch
|
||||
{
|
||||
var t when t == typeof(bool) => bool.Parse(text),
|
||||
var t when t == typeof(int) => int.Parse(text, NumberStyles.Integer, c),
|
||||
var t when t == typeof(long) => long.Parse(text, NumberStyles.Integer, c),
|
||||
var t when t == typeof(decimal) => decimal.Parse(text, NumberStyles.Number, c),
|
||||
var t when t == typeof(double) => double.Parse(text, NumberStyles.Float, c),
|
||||
var t when t == typeof(DateOnly) => DateOnly.ParseExact(text, "yyyy-MM-dd", c),
|
||||
var t when t == typeof(DateTime) => DateTime.Parse(text, c, DateTimeStyles.RoundtripKind),
|
||||
var t when t == typeof(DateTimeOffset) => DateTimeOffset.Parse(text, c, DateTimeStyles.RoundtripKind),
|
||||
var t when t == typeof(Guid) => Guid.Parse(text),
|
||||
var t when t.IsEnum => Enum.Parse(t, text, ignoreCase: false),
|
||||
_ => throw new FormatException("Unsupported type " + Underlying.Name),
|
||||
};
|
||||
}
|
||||
|
||||
private Expression Member(ParameterExpression row) => new Rebind(_selector.Parameters[0], row).Visit(_selector.Body);
|
||||
|
||||
private Expression Equal(Expression member, string text, ListFilter filter, bool inMemory)
|
||||
{
|
||||
if (IsText && inMemory)
|
||||
{
|
||||
// Texts are equal ignoring case, as LIKE without wildcards would be.
|
||||
var equals = typeof(string).GetMethod(nameof(string.Equals), [typeof(string), typeof(string), typeof(StringComparison)])!;
|
||||
return Expression.Call(equals, member, Expression.Constant(text), Expression.Constant(StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
return Expression.Equal(member, Value(text, filter));
|
||||
}
|
||||
|
||||
private static Expression TextCall(Expression member, MethodInfo method, string text, bool inMemory)
|
||||
{
|
||||
if (!inMemory)
|
||||
{
|
||||
return Expression.Call(member, method, Expression.Constant(text));
|
||||
}
|
||||
|
||||
// Null texts never match in memory, as in SQL.
|
||||
return Expression.AndAlso(
|
||||
Expression.NotEqual(member, Expression.Constant(null, typeof(string))),
|
||||
Expression.Call(member, method, Expression.Constant(text), Expression.Constant(StringComparison.OrdinalIgnoreCase)));
|
||||
}
|
||||
|
||||
private ConstantExpression Value(string text, ListFilter filter) => Expression.Constant(Convert(text, filter), typeof(TValue));
|
||||
|
||||
private TValue Convert(string text, ListFilter filter)
|
||||
{
|
||||
try
|
||||
{
|
||||
return (TValue)ConvertText(text)!;
|
||||
}
|
||||
catch (Exception e) when (e is FormatException or OverflowException or ArgumentException or InvalidCastException)
|
||||
{
|
||||
throw new ArgumentException($"Value '{text}' is not valid for {Id}.", nameof(filter), e);
|
||||
}
|
||||
}
|
||||
|
||||
private string Single(IReadOnlyList<string> values, ListFilter filter)
|
||||
{
|
||||
Require(values.Count == 1, filter);
|
||||
return values[0];
|
||||
}
|
||||
|
||||
private void Require(bool condition, ListFilter filter)
|
||||
{
|
||||
if (!condition)
|
||||
{
|
||||
throw new ArgumentException($"{filter.Operator} with {filter.Values?.Count ?? 0} values is not valid on {Id}.", nameof(filter));
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Rebind(ParameterExpression from, ParameterExpression to) : ExpressionVisitor
|
||||
{
|
||||
protected override Expression VisitParameter(ParameterExpression node) => node == from ? to : base.VisitParameter(node);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Khaemhat.Application.Querying;
|
||||
|
||||
/// <summary>How a filter compares a field with its values (SPEC §10.7 <c>KhGrid</c>, <c>KhRadar</c>).</summary>
|
||||
public enum ListFilterOperator
|
||||
{
|
||||
/// <summary>Equal to the value.</summary>
|
||||
Equals = 0,
|
||||
|
||||
/// <summary>Different from the value.</summary>
|
||||
NotEquals = 1,
|
||||
|
||||
/// <summary>Text containing the value, ignoring case.</summary>
|
||||
Contains = 2,
|
||||
|
||||
/// <summary>Text starting with the value, ignoring case.</summary>
|
||||
StartsWith = 3,
|
||||
|
||||
/// <summary>Greater than the value.</summary>
|
||||
GreaterThan = 4,
|
||||
|
||||
/// <summary>Greater than or equal to the value.</summary>
|
||||
GreaterOrEqual = 5,
|
||||
|
||||
/// <summary>Less than the value.</summary>
|
||||
LessThan = 6,
|
||||
|
||||
/// <summary>Less than or equal to the value.</summary>
|
||||
LessOrEqual = 7,
|
||||
|
||||
/// <summary>Between the first and the second value, both included.</summary>
|
||||
Between = 8,
|
||||
|
||||
/// <summary>One of the values.</summary>
|
||||
In = 9,
|
||||
|
||||
/// <summary>Empty (null, or an empty text).</summary>
|
||||
IsEmpty = 10,
|
||||
|
||||
/// <summary>Not empty.</summary>
|
||||
IsNotEmpty = 11,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A filter on a field. The values are invariant texts (<c>2026-11-30</c>, <c>1234.5</c>, <c>true</c>, the name of an
|
||||
/// enum value), so a filter can be saved in the user settings and read back unchanged.
|
||||
/// </summary>
|
||||
/// <param name="Field">The field id.</param>
|
||||
/// <param name="Operator">The comparison.</param>
|
||||
/// <param name="Values">The values: none for the empty checks, two for <see cref="ListFilterOperator.Between"/>.</param>
|
||||
public sealed record ListFilter(string Field, ListFilterOperator Operator, IReadOnlyList<string> Values)
|
||||
{
|
||||
/// <summary>A filter with its values.</summary>
|
||||
/// <param name="field">The field id.</param>
|
||||
/// <param name="op">The comparison.</param>
|
||||
/// <param name="values">The values.</param>
|
||||
/// <returns>The filter.</returns>
|
||||
public static ListFilter Of(string field, ListFilterOperator op, params string[] values) => new(field, op, values);
|
||||
|
||||
/// <summary>The invariant text of a value, as filters keep it.</summary>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <returns>The text.</returns>
|
||||
public static string Text(object? value) => value switch
|
||||
{
|
||||
null => string.Empty,
|
||||
DateOnly d => d.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
|
||||
DateTime d => d.ToString("O", CultureInfo.InvariantCulture),
|
||||
DateTimeOffset d => d.ToString("O", CultureInfo.InvariantCulture),
|
||||
bool b => b ? "true" : "false",
|
||||
IFormattable f => f.ToString(null, CultureInfo.InvariantCulture),
|
||||
_ => value.ToString() ?? string.Empty,
|
||||
};
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Equals(ListFilter? other) =>
|
||||
other is not null && Field == other.Field && Operator == other.Operator && Values.SequenceEqual(other.Values);
|
||||
|
||||
/// <inheritdoc />
|
||||
public override int GetHashCode()
|
||||
{
|
||||
var hash = new HashCode();
|
||||
hash.Add(Field);
|
||||
hash.Add(Operator);
|
||||
foreach (var value in Values)
|
||||
{
|
||||
hash.Add(value);
|
||||
}
|
||||
|
||||
return hash.ToHashCode();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An ordering on a field.</summary>
|
||||
/// <param name="Field">The field id.</param>
|
||||
/// <param name="Descending">Whether from the largest.</param>
|
||||
public sealed record ListSort(string Field, bool Descending = false);
|
||||
|
||||
/// <summary>
|
||||
/// What a list or radar asks its source: the text typed in the search box, the filters, the ordering and the page.
|
||||
/// The source answers with a <see cref="ListPage{T}"/>; with <see cref="ListFields{T}"/> the same request becomes SQL for
|
||||
/// a repository or runs on rows in memory.
|
||||
/// </summary>
|
||||
public sealed record ListQuery
|
||||
{
|
||||
/// <summary>The largest page a source returns.</summary>
|
||||
public const int MaxLimit = 1000;
|
||||
|
||||
/// <summary>The text of the search box: every searchable field is checked.</summary>
|
||||
public string? Search { get; init; }
|
||||
|
||||
/// <summary>The filters, all of which must hold.</summary>
|
||||
public IReadOnlyList<ListFilter> Filters { get; init; } = [];
|
||||
|
||||
/// <summary>The ordering, first field first.</summary>
|
||||
public IReadOnlyList<ListSort> Sort { get; init; } = [];
|
||||
|
||||
/// <summary>The rows to skip.</summary>
|
||||
public int Offset { get; init; }
|
||||
|
||||
/// <summary>The rows to return, at most <see cref="MaxLimit"/>.</summary>
|
||||
public int Limit { get; init; } = 50;
|
||||
|
||||
/// <summary>The same request for another page.</summary>
|
||||
/// <param name="offset">The rows to skip.</param>
|
||||
/// <param name="limit">The rows to return.</param>
|
||||
/// <returns>The request.</returns>
|
||||
public ListQuery WithPage(int offset, int limit) => this with { Offset = Math.Max(0, offset), Limit = Math.Clamp(limit, 1, MaxLimit) };
|
||||
|
||||
/// <summary>Whether two requests select and order the same rows, whatever the page.</summary>
|
||||
/// <param name="other">The other request.</param>
|
||||
/// <returns>Whether they match.</returns>
|
||||
public bool SameRows(ListQuery? other) =>
|
||||
other is not null && string.Equals(Search?.Trim(), other.Search?.Trim(), StringComparison.OrdinalIgnoreCase)
|
||||
&& Filters.SequenceEqual(other.Filters) && Sort.SequenceEqual(other.Sort);
|
||||
}
|
||||
|
||||
/// <summary>A page of rows with the count and the totals of every row the request selects (not only the page).</summary>
|
||||
/// <typeparam name="T">The row type.</typeparam>
|
||||
/// <param name="Items">The rows of the page.</param>
|
||||
/// <param name="Total">The rows selected.</param>
|
||||
/// <param name="Totals">The sums by field id, for the totals row of the grid.</param>
|
||||
public sealed record ListPage<T>(IReadOnlyList<T> Items, long Total, IReadOnlyDictionary<string, decimal> Totals)
|
||||
{
|
||||
/// <summary>No rows.</summary>
|
||||
#pragma warning disable CA1000 // An empty page of the same row type is the natural default.
|
||||
public static ListPage<T> Empty { get; } = new([], 0, new Dictionary<string, decimal>());
|
||||
#pragma warning restore CA1000
|
||||
}
|
||||
|
||||
/// <summary>Where a grid or radar reads its rows.</summary>
|
||||
/// <typeparam name="T">The row type.</typeparam>
|
||||
/// <param name="query">The request.</param>
|
||||
/// <param name="cancellationToken">Cancellation, when a newer request replaces this one.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public delegate Task<ListPage<T>> ListSource<T>(ListQuery query, CancellationToken cancellationToken);
|
||||
@@ -153,6 +153,26 @@ else
|
||||
</KhDrawer>
|
||||
break;
|
||||
|
||||
case "griglie":
|
||||
<div class="kh-catalog">
|
||||
<KhRadar TItem="SampleCustomer" Id="catalog.customers" Columns="CustomerColumns" Source="CatalogSamples.CustomersAsync" KeyOf="c => c.Id"
|
||||
QuickFilters="CustomerQuickFilters" RowClass="CustomerRowClass" RowMenu="CustomerMenu" OnOpen="OpenCustomer"
|
||||
ExportName="clienti-di-prova" Label="@T["Pages.Catalog.Grids.Radar"]">
|
||||
<Toolbar>
|
||||
<div>
|
||||
<h2 class="kh-h2">@T["Pages.Catalog.Grids.Radar"]</h2>
|
||||
<p class="muted">@T["Pages.Catalog.Grids.RadarIntro"]</p>
|
||||
</div>
|
||||
</Toolbar>
|
||||
</KhRadar>
|
||||
<KhPanel Title="@T["Pages.Catalog.Grids.Pager"]" Icon="grid">
|
||||
<p class="muted kh-pad">@T["Pages.Catalog.Grids.PagerIntro"]</p>
|
||||
<KhGrid TItem="SampleCustomer" Columns="PagedColumns" Source="CatalogSamples.CustomersAsync" Virtual="false" PageSize="10" KeyOf="c => c.Id"
|
||||
Filters="VipOnly" Label="@T["Pages.Catalog.Grids.Pager"]" />
|
||||
</KhPanel>
|
||||
</div>
|
||||
break;
|
||||
|
||||
case "toolbar":
|
||||
<div class="kh-catalog">
|
||||
<p class="muted">@T["Pages.Catalog.Toolbar.Intro"]</p>
|
||||
@@ -202,6 +222,7 @@ else
|
||||
new("pannelli", "layers", T["Pages.Catalog.Sections.Panels"]),
|
||||
new("navigazione", "columns", T["Pages.Catalog.Sections.Navigation"]),
|
||||
new("finestre", "layout", T["Pages.Catalog.Sections.Windows"]),
|
||||
new("griglie", "list", T["Pages.Catalog.Sections.Grids"]),
|
||||
new("toolbar", "settings", T["Pages.Catalog.Sections.Toolbar"]),
|
||||
];
|
||||
|
||||
@@ -311,5 +332,82 @@ else
|
||||
|
||||
private static string KindKey(ToastKind kind) => "Pages.Catalog.Windows.Toast." + kind;
|
||||
|
||||
private static readonly IReadOnlyList<ListFilter> VipOnly = [ListFilter.Of("vip", ListFilterOperator.Equals, "true")];
|
||||
|
||||
private IReadOnlyList<KhOption<string>> KindChoices =>
|
||||
[
|
||||
new("company", T["Pages.Catalog.Grids.KindCompany"]),
|
||||
new("person", T["Pages.Catalog.Grids.KindPerson"]),
|
||||
new("public", T["Pages.Catalog.Grids.KindPublic"]),
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhOption<string>> StateChoices =>
|
||||
[
|
||||
new("active", T["Pages.Catalog.Grids.StateActive"]),
|
||||
new("blocked", T["Pages.Catalog.Grids.StateBlocked"]),
|
||||
new("disabled", T["Pages.Catalog.Grids.StateDisabled"]),
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhColumn<SampleCustomer>> CustomerColumns =>
|
||||
[
|
||||
new("code", T["Pages.Catalog.Grids.Code"], c => c.Code) { Kind = KhColumnKind.Code, Width = "96px" },
|
||||
new("name", T["Pages.Catalog.Grids.Name"], c => c.Name),
|
||||
new("city", T["Pages.Catalog.Grids.City"], c => c.City),
|
||||
new("province", T["Pages.Catalog.Grids.Province"], c => c.Province) { Width = "60px" },
|
||||
new("agent", T["Pages.Catalog.Grids.Agent"], c => c.Agent),
|
||||
new("kind", T["Pages.Catalog.Grids.Kind"], c => KindChoices.First(k => k.Value == c.Kind).Text) { Choices = KindChoices, Visible = false },
|
||||
new("revenue", T["Pages.Catalog.Grids.Revenue"], c => c.Revenue) { Kind = KhColumnKind.Money, Total = true },
|
||||
new("overdue", T["Pages.Catalog.Grids.Overdue"], c => c.Overdue) { Kind = KhColumnKind.Money, Total = true, CellClass = c => c.Overdue > 0 ? "neg" : null },
|
||||
new("since", T["Pages.Catalog.Grids.Since"], c => c.Since) { Kind = KhColumnKind.Date, Visible = false },
|
||||
new("vip", T["Pages.Catalog.Grids.Vip"], c => c.Vip) { Kind = KhColumnKind.Bool, Visible = false },
|
||||
new("state", T["Pages.Catalog.Grids.State"], c => StateChoices.First(k => k.Value == c.State).Text)
|
||||
{
|
||||
Choices = StateChoices,
|
||||
Template = c => @<KhBadge Tone="@(c.State switch { "active" => KhTone.Ok, "blocked" => KhTone.Error, _ => KhTone.Neutral })">@StateChoices.First(k => k.Value == c.State).Text</KhBadge>,
|
||||
},
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhColumn<SampleCustomer>> PagedColumns =>
|
||||
[
|
||||
new("code", T["Pages.Catalog.Grids.Code"], c => c.Code) { Kind = KhColumnKind.Code, Width = "96px" },
|
||||
new("name", T["Pages.Catalog.Grids.Name"], c => c.Name),
|
||||
new("revenue", T["Pages.Catalog.Grids.Revenue"], c => c.Revenue) { Kind = KhColumnKind.Money, Total = true },
|
||||
new("credit", T["Pages.Catalog.Grids.Credit"], c => c.Credit) { Kind = KhColumnKind.Money, Total = true, Edit = EditCreditAsync },
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhQuickFilter> CustomerQuickFilters =>
|
||||
[
|
||||
new("kind", T["Pages.Catalog.Grids.Kind"], [new(string.Empty, T["Pages.Catalog.Grids.All"]), .. KindChoices]),
|
||||
new("agent", T["Pages.Catalog.Grids.Agent"], [new(string.Empty, T["Pages.Catalog.Grids.All"]), new("M. Verdi", "M. Verdi"), new("L. Neri", "L. Neri"), new("A. Bianchi", "A. Bianchi")]),
|
||||
new("state", T["Pages.Catalog.Grids.State"], [new(string.Empty, T["Pages.Catalog.Grids.All"]), .. StateChoices]),
|
||||
];
|
||||
|
||||
private static string? CustomerRowClass(SampleCustomer customer) => customer.State == "blocked" ? "hl" : null;
|
||||
|
||||
private IEnumerable<ToolbarItem> CustomerMenu(SampleCustomer customer)
|
||||
{
|
||||
yield return new ToolbarItem("open", "external", T["Pages.Catalog.Grids.OpenCard"]) { OnClick = () => { OpenCustomer(customer); return Task.CompletedTask; } };
|
||||
yield return new ToolbarItem("copy", "copy", T["Pages.Catalog.Grids.Duplicate"]) { OnClick = () => Clicked("Pages.Catalog.Grids.Duplicate") };
|
||||
yield return new ToolbarItem("block", "lock", T["Pages.Catalog.Grids.Block"]) { Danger = true, Disabled = customer.State == "blocked", OnClick = () => Clicked("Pages.Catalog.Grids.Block") };
|
||||
}
|
||||
|
||||
private void OpenCustomer(SampleCustomer customer) => Toasts.Show(ToastKind.Info, T.Format("Pages.Catalog.Grids.Opened", customer.Name));
|
||||
|
||||
private Task<string?> EditCreditAsync(SampleCustomer customer, string text)
|
||||
{
|
||||
if (!ItalianNumber.TryParse(text, out var value) || value is null)
|
||||
{
|
||||
return Task.FromResult<string?>(T["Ui.Validation.Number"]);
|
||||
}
|
||||
|
||||
if (value < 0)
|
||||
{
|
||||
return Task.FromResult<string?>(T["Pages.Catalog.Grids.CreditInvalid"]);
|
||||
}
|
||||
|
||||
customer.Credit = Math.Round(value.Value, 2);
|
||||
return Task.FromResult<string?>(null);
|
||||
}
|
||||
|
||||
private void ShowToast(ToastKind kind) => Toasts.Show(kind, T[KindKey(kind)], T["Pages.Catalog.Windows.ToastText"]);
|
||||
}
|
||||
@@ -45,29 +45,9 @@ else
|
||||
@switch (ActiveTab)
|
||||
{
|
||||
case TabIds.Lines:
|
||||
<table class="grid">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">@T["Pages.Catalog.Lines.Code"]</th>
|
||||
<th scope="col">@T["Pages.Catalog.Lines.Description"]</th>
|
||||
<th scope="col" class="num">@T["Pages.Catalog.Lines.Quantity"]</th>
|
||||
<th scope="col" class="num">@T["Pages.Catalog.Lines.Price"]</th>
|
||||
<th scope="col" class="num">@T["Pages.Catalog.Lines.Amount"]</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var line in Record.Lines)
|
||||
{
|
||||
<tr>
|
||||
<td class="code">@line.Code</td>
|
||||
<td>@line.Description</td>
|
||||
<td class="num">@T.Number(line.Quantity ?? 0, 2)</td>
|
||||
<td class="num"><KhMoney Value="line.Price" /></td>
|
||||
<td class="num"><KhMoney Value="line.Amount" /></td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
<KhLinesGrid TLine="SampleLine" @ref="_lines" Lines="Record.Lines" Columns="LineColumns" NewLine="() => new SampleLine()" IsEmpty="l => l.IsEmpty"
|
||||
IsDescriptive="l => l.Descriptive" NewDescriptive="() => new SampleLine { Descriptive = true }" DescriptionColumn="LineColumns[1]"
|
||||
ReadOnly="IsReadOnly" OnChanged="MarkModified" Label="@T["Pages.Catalog.Grids.Lines"]" />
|
||||
break;
|
||||
|
||||
case TabIds.Header:
|
||||
@@ -91,10 +71,88 @@ else
|
||||
}
|
||||
</ChildContent>
|
||||
</KhRecordLayout>
|
||||
|
||||
<KhRadarDialog TItem="SampleItem" Id="catalog.items" Open="_lookupLine is not null" Title="@T["Pages.Catalog.Grids.ItemRadar"]" Columns="ItemColumns"
|
||||
Source="CatalogSamples.ItemsAsync" KeyOf="i => i.Code" InitialSearch="@_lookupLine?.Code" OnPick="PickItemAsync" OnClose="() => _lookupLine = null"
|
||||
OnCreate="CreateItem" />
|
||||
}
|
||||
|
||||
@code {
|
||||
private int _saved;
|
||||
private KhLinesGrid<SampleLine>? _lines;
|
||||
private SampleLine? _lookupLine;
|
||||
private TaskCompletionSource? _lookupDone;
|
||||
private IReadOnlyList<KhLineColumn<SampleLine>>? _lineColumns;
|
||||
|
||||
private IReadOnlyList<KhLineColumn<SampleLine>> LineColumns => _lineColumns ??=
|
||||
[
|
||||
new("code", T["Pages.Catalog.Grids.Item"], l => l.Code) { Kind = KhColumnKind.Code, Width = "120px", SetText = SetCode, Lookup = LookupAsync },
|
||||
new("description", T["Pages.Catalog.Grids.Description"], l => l.Description) { SetText = (l, v) => l.Description = v ?? string.Empty },
|
||||
new("unit", T["Pages.Catalog.Grids.Unit"], l => l.Unit) { Width = "56px", SetText = (l, v) => l.Unit = v?.ToUpperInvariant() },
|
||||
new("quantity", T["Pages.Catalog.Grids.Quantity"], l => l.Quantity) { Kind = KhColumnKind.Number, Width = "96px", SetNumber = (l, v) => l.Quantity = v },
|
||||
new("price", T["Pages.Catalog.Grids.Price"], l => l.Price) { Kind = KhColumnKind.Money, Width = "110px", SetNumber = (l, v) => l.Price = v },
|
||||
new("discount", T["Pages.Catalog.Grids.Discount"], l => l.Discount) { Kind = KhColumnKind.Number, Width = "80px", SetNumber = (l, v) => l.Discount = v },
|
||||
new("amount", T["Pages.Catalog.Grids.Amount"], l => l.Descriptive || l.IsEmpty ? null : l.Amount) { Kind = KhColumnKind.Money, Width = "120px" },
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhColumn<SampleItem>> ItemColumns =>
|
||||
[
|
||||
new("code", T["Pages.Catalog.Grids.Item"], i => i.Code) { Kind = KhColumnKind.Code, Width = "100px" },
|
||||
new("description", T["Pages.Catalog.Grids.Description"], i => i.Description),
|
||||
new("unit", T["Pages.Catalog.Grids.Unit"], i => i.Unit) { Width = "56px" },
|
||||
new("stock", T["Pages.Catalog.Grids.Quantity"], i => i.Stock) { Kind = KhColumnKind.Number, Decimals = 0 },
|
||||
new("price", T["Pages.Catalog.Grids.Price"], i => i.Price) { Kind = KhColumnKind.Money },
|
||||
];
|
||||
|
||||
// Typing a known code fills description, unit and price, as a real item would.
|
||||
private static void SetCode(SampleLine line, string? code)
|
||||
{
|
||||
line.Code = code?.ToUpperInvariant() ?? string.Empty;
|
||||
if (CatalogSamples.ItemByCode(code) is { } item)
|
||||
{
|
||||
Fill(line, item);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Fill(SampleLine line, SampleItem item)
|
||||
{
|
||||
line.Code = item.Code;
|
||||
line.Description = item.Description;
|
||||
line.Unit = item.Unit;
|
||||
line.Price = item.Price;
|
||||
line.Quantity ??= 1;
|
||||
}
|
||||
|
||||
private Task LookupAsync(SampleLine line)
|
||||
{
|
||||
_lookupLine = line;
|
||||
_lookupDone = new TaskCompletionSource();
|
||||
StateHasChanged();
|
||||
return _lookupDone.Task;
|
||||
}
|
||||
|
||||
private async Task PickItemAsync(SampleItem item)
|
||||
{
|
||||
if (_lookupLine is { } line)
|
||||
{
|
||||
Fill(line, item);
|
||||
_lookupLine = null;
|
||||
_lookupDone?.TrySetResult();
|
||||
MarkModified();
|
||||
await Task.Yield();
|
||||
if (_lines is not null)
|
||||
{
|
||||
await _lines.FocusCellAsync(line, "quantity");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void CreateItem(string text)
|
||||
{
|
||||
Toasts.Show(ToastKind.Info, T.Format("Pages.Catalog.Grids.ItemCreated", text));
|
||||
_lookupLine = null;
|
||||
_lookupDone?.TrySetResult();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyList<KhTabItem> Tabs => Record is null ? [] : StandardTabs(attachments: 2, links: 1);
|
||||
|
||||
@@ -0,0 +1,988 @@
|
||||
@typeparam TItem
|
||||
@implements IAsyncDisposable
|
||||
@inject IJSRuntime JS
|
||||
@inject ShellSession Session
|
||||
@inject ToastService Toasts
|
||||
|
||||
@* The grid of lists and radars (SPEC §10.7 KhGrid): typed columns, sort on the header (Shift for a second column),
|
||||
rows read from the source a page at a time (virtual scrolling, or a pager), multiple selection, editing in place,
|
||||
totals row, column layout saved per user, export to CSV and XLSX, highlights, row menu. Keyboard: arrows, Page Up
|
||||
and Down, Home, End, Enter opens, Space selects, F2 edits, the context menu key or right click opens the row menu. *@
|
||||
<div class="kh-grid @Class">
|
||||
<div class="gridwrap kh-gridwrap" style="@WrapStyle" tabindex="0" role="grid" aria-label="@Label" aria-rowcount="@_total"
|
||||
aria-multiselectable="@(Selectable ? "true" : null)" data-kh-prevent="ArrowUp ArrowDown PageUp PageDown Home End Space Enter F2 Shift+F10"
|
||||
@onkeydown="OnKeyDownAsync" @ref="_wrap">
|
||||
<table class="grid">
|
||||
<thead>
|
||||
<tr>
|
||||
@if (Selectable)
|
||||
{
|
||||
<th scope="col" class="chkc">
|
||||
<button type="button" class="kh-bxbtn" role="checkbox" aria-checked="@(AllLoadedSelected ? "true" : "false")" aria-label="@T["Ui.Grid.SelectAll"]"
|
||||
tabindex="-1" @onclick="ToggleAllAsync">
|
||||
<span class="bx @(AllLoadedSelected ? "on" : null)">@if (AllLoadedSelected) { <KhIcon Name="check" /> }</span>
|
||||
</button>
|
||||
</th>
|
||||
}
|
||||
@foreach (var column in _columns)
|
||||
{
|
||||
var sort = SortOf(column);
|
||||
<th scope="col" class="@(column.IsNumeric ? "num" : null)" style="@(column.Width is null ? null : "width:" + column.Width)"
|
||||
aria-sort="@(sort is null ? null : sort.Descending ? "descending" : "ascending")">
|
||||
@if (column.Sortable)
|
||||
{
|
||||
<button type="button" class="kh-th" tabindex="-1" data-sort="@(sort is null ? null : sort.Descending ? "desc" : "asc")"
|
||||
title="@T["Ui.Grid.SortHint"]" @onclick="e => SortAsync(column, e.ShiftKey)">@column.Title</button>
|
||||
}
|
||||
else
|
||||
{
|
||||
@column.Title
|
||||
}
|
||||
</th>
|
||||
}
|
||||
@if (RowMenu is not null)
|
||||
{
|
||||
<th scope="col" class="kh-rowmenu"><span class="kh-sr">@T["Ui.Grid.RowMenu"]</span></th>
|
||||
}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@if (Virtual)
|
||||
{
|
||||
<Virtualize @ref="_virtualize" TItem="GridRow" Context="row" ItemsProvider="ProvideAsync" ItemSize="RowHeight" OverscanCount="20" SpacerElement="tr">
|
||||
<ItemContent>@RowFragment(row)</ItemContent>
|
||||
<Placeholder><tr class="kh-ph"><td colspan="@ColumnCount"> </td></tr></Placeholder>
|
||||
</Virtualize>
|
||||
}
|
||||
else
|
||||
{
|
||||
@for (var i = 0; i < _pageItems.Count; i++)
|
||||
{
|
||||
@RowFragment(new GridRow(_pageOffset + i, _pageItems[i]))
|
||||
}
|
||||
}
|
||||
@if (_loaded && _total == 0)
|
||||
{
|
||||
<tr class="kh-empty"><td colspan="@ColumnCount">@(Empty ?? T["Ui.Grid.Empty"])</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
@if (HasTotals && _total > 0)
|
||||
{
|
||||
<tfoot>
|
||||
<tr>
|
||||
@if (Selectable)
|
||||
{
|
||||
<td class="chkc"></td>
|
||||
}
|
||||
@for (var i = 0; i < _columns.Count; i++)
|
||||
{
|
||||
var column = _columns[i];
|
||||
<td class="@(column.IsNumeric ? "num" : null)">
|
||||
@if (column.Total && _totals.TryGetValue(column.Id, out var sum))
|
||||
{
|
||||
@column.FormatValue(sum, T)
|
||||
}
|
||||
else if (i == 0)
|
||||
{
|
||||
@T["Ui.Grid.Total"]
|
||||
}
|
||||
</td>
|
||||
}
|
||||
@if (RowMenu is not null)
|
||||
{
|
||||
<td></td>
|
||||
}
|
||||
</tr>
|
||||
</tfoot>
|
||||
}
|
||||
</table>
|
||||
</div>
|
||||
@if (ShowFooter)
|
||||
{
|
||||
<div class="gridfoot">
|
||||
<span>
|
||||
@T.Format("Ui.Grid.Count", T.Number(_total))
|
||||
@if (_selected.Count > 0)
|
||||
{
|
||||
@(" · ")@T.Format("Ui.Grid.Selected", T.Number(_selected.Count))
|
||||
}
|
||||
@Summary
|
||||
</span>
|
||||
@if (!Virtual && PageCount > 1)
|
||||
{
|
||||
<nav class="kh-pager" aria-label="@T["Ui.Grid.Pages"]">
|
||||
<button type="button" class="kh-pg" disabled="@(_page == 0)" aria-label="@T["Ui.Grid.PreviousPage"]" @onclick="() => GoToPageAsync(_page - 1)"><KhIcon Name="chevron-left" Class="sm" /></button>
|
||||
@foreach (var number in PageNumbers)
|
||||
{
|
||||
if (number < 0)
|
||||
{
|
||||
<span class="kh-pgdots" aria-hidden="true">…</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<button type="button" class="kh-pg @(number == _page ? "on" : null)" aria-current="@(number == _page ? "page" : null)" @onclick="() => GoToPageAsync(number)">@(number + 1)</button>
|
||||
}
|
||||
}
|
||||
<button type="button" class="kh-pg" disabled="@(_page >= PageCount - 1)" aria-label="@T["Ui.Grid.NextPage"]" @onclick="() => GoToPageAsync(_page + 1)"><KhIcon Name="chevron-right" Class="sm" /></button>
|
||||
</nav>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@if (_menu is { } menu && RowMenu is not null)
|
||||
{
|
||||
<div class="kh-catch" @onclick="CloseMenu" @oncontextmenu="CloseMenu" @oncontextmenu:preventDefault></div>
|
||||
<div class="popmenu kh-rowpop" role="menu" style="@MenuStyle(menu)" @ref="_menuRef">
|
||||
@foreach (var item in RowMenu(menu.Item))
|
||||
{
|
||||
<button type="button" role="menuitem" class="mi @(item.Danger ? "danger" : null)" disabled="@item.Disabled" @onclick="() => RunMenuAsync(item)">
|
||||
<KhIcon Name="@item.Icon" /><span class="grow">@item.Text</span>
|
||||
@if (item.Shortcut is not null)
|
||||
{
|
||||
<span class="k">@KeyboardShortcuts.Pretty(item.Shortcut)</span>
|
||||
}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<KhDialog Open="_columnsOpen" Title="@T["Ui.Grid.Columns"]" Icon="columns" Size="sm" OnClose="() => _columnsOpen = false">
|
||||
<ChildContent>
|
||||
<p class="muted">@T["Ui.Grid.ColumnsHint"]</p>
|
||||
<ul class="kh-colchooser">
|
||||
@for (var i = 0; i < _chooser.Count; i++)
|
||||
{
|
||||
var index = i;
|
||||
var column = _chooser[i];
|
||||
var shown = !_hidden.Contains(column.Id);
|
||||
<li>
|
||||
<label class="kh-colcheck">
|
||||
<input type="checkbox" checked="@shown" @onchange="e => ToggleColumnAsync(column, e.Value is true)" />
|
||||
@column.Title
|
||||
</label>
|
||||
<KhIconButton Icon="chevron-up" Text="@T["Ui.Grid.Up"]" Disabled="index == 0" OnClick="() => MoveColumnAsync(index, -1)" />
|
||||
<KhIconButton Icon="chevron-down" Text="@T["Ui.Grid.Down"]" Disabled="index == _chooser.Count - 1" OnClick="() => MoveColumnAsync(index, 1)" />
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
</ChildContent>
|
||||
<Footer>
|
||||
<button type="button" class="btn" @onclick="ResetColumnsAsync"><KhIcon Name="refresh" /> @T["Ui.Grid.Reset"]</button>
|
||||
<button type="button" class="btn primary" @onclick="() => _columnsOpen = false">@T["Ui.Grid.Close"]</button>
|
||||
</Footer>
|
||||
</KhDialog>
|
||||
|
||||
@code {
|
||||
private readonly Dictionary<int, TItem> _loadedRows = [];
|
||||
private readonly HashSet<object> _selected = [];
|
||||
private IReadOnlyList<KhColumn<TItem>> _columns = [];
|
||||
private List<KhColumn<TItem>> _chooser = [];
|
||||
private HashSet<string> _hidden = new(StringComparer.Ordinal);
|
||||
private List<ListSort> _sort = [];
|
||||
private ListQuery? _lastQuery;
|
||||
private IReadOnlyDictionary<string, decimal> _totals = new Dictionary<string, decimal>();
|
||||
private IReadOnlyList<TItem> _pageItems = [];
|
||||
private int _pageOffset;
|
||||
private int _page;
|
||||
private long _total;
|
||||
private bool _loaded;
|
||||
private int _current = -1;
|
||||
private bool _scrollToCurrent;
|
||||
private (int Index, string Column)? _editing;
|
||||
private string _editText = string.Empty;
|
||||
private string? _editError;
|
||||
private bool _focusEditor;
|
||||
private RowMenuState? _menu;
|
||||
private bool _columnsOpen;
|
||||
private bool _layoutLoaded;
|
||||
private CancellationTokenSource? _pageLoad;
|
||||
private Virtualize<GridRow>? _virtualize;
|
||||
private ElementReference _wrap;
|
||||
private ElementReference _menuRef;
|
||||
private bool _placeMenu;
|
||||
|
||||
/// <summary>The columns, in their default order.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public IReadOnlyList<KhColumn<TItem>> Columns { get; set; } = [];
|
||||
|
||||
/// <summary>Where the rows come from.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public ListSource<TItem> Source { get; set; } = default!;
|
||||
|
||||
/// <summary>The text of the search box of the radar.</summary>
|
||||
[Parameter]
|
||||
public string? Search { get; set; }
|
||||
|
||||
/// <summary>The filters of the radar.</summary>
|
||||
[Parameter]
|
||||
public IReadOnlyList<ListFilter> Filters { get; set; } = [];
|
||||
|
||||
/// <summary>The ordering when the grid opens.</summary>
|
||||
[Parameter]
|
||||
public IReadOnlyList<ListSort>? Sort { get; set; }
|
||||
|
||||
/// <summary>Called when the user changes the ordering.</summary>
|
||||
[Parameter]
|
||||
public EventCallback<IReadOnlyList<ListSort>> SortChanged { get; set; }
|
||||
|
||||
/// <summary>The key of a row, for the selection; required with <see cref="Selectable"/>.</summary>
|
||||
[Parameter]
|
||||
public Func<TItem, object>? KeyOf { get; set; }
|
||||
|
||||
/// <summary>Shows the selection boxes.</summary>
|
||||
[Parameter]
|
||||
public bool Selectable { get; set; }
|
||||
|
||||
/// <summary>Called when the selection changes, with the keys.</summary>
|
||||
[Parameter]
|
||||
public EventCallback<IReadOnlyCollection<object>> SelectionChanged { get; set; }
|
||||
|
||||
/// <summary>Reads the rows while scrolling (the default); otherwise a pager shows <see cref="PageSize"/> rows.</summary>
|
||||
[Parameter]
|
||||
public bool Virtual { get; set; } = true;
|
||||
|
||||
/// <summary>The rows of a page, without <see cref="Virtual"/>.</summary>
|
||||
[Parameter]
|
||||
public int PageSize { get; set; } = 50;
|
||||
|
||||
/// <summary>The height of the scrolling area, as CSS; none fills the parent (flex).</summary>
|
||||
[Parameter]
|
||||
public string? Height { get; set; }
|
||||
|
||||
/// <summary>Called with the row on Enter or double click.</summary>
|
||||
[Parameter]
|
||||
public EventCallback<TItem> OnOpen { get; set; }
|
||||
|
||||
/// <summary>Called when the current row changes (keyboard or click).</summary>
|
||||
[Parameter]
|
||||
public EventCallback<TItem> OnCurrent { get; set; }
|
||||
|
||||
/// <summary>Extra classes of a row: <c>hl</c> highlights it.</summary>
|
||||
[Parameter]
|
||||
public Func<TItem, string?>? RowClass { get; set; }
|
||||
|
||||
/// <summary>The commands of the row menu (right click, the context menu key, or the button at the end of the row).</summary>
|
||||
[Parameter]
|
||||
public Func<TItem, IEnumerable<ToolbarItem>>? RowMenu { get; set; }
|
||||
|
||||
/// <summary>The id under which the column layout is saved for the user; none keeps the default layout.</summary>
|
||||
[Parameter]
|
||||
public string? LayoutKey { get; set; }
|
||||
|
||||
/// <summary>The name of the exported files, without extension.</summary>
|
||||
[Parameter]
|
||||
public string? ExportName { get; set; }
|
||||
|
||||
/// <summary>The label read by screen readers.</summary>
|
||||
[Parameter]
|
||||
public string? Label { get; set; }
|
||||
|
||||
/// <summary>The text when there are no rows.</summary>
|
||||
[Parameter]
|
||||
public string? Empty { get; set; }
|
||||
|
||||
/// <summary>Shows the bar under the grid with the counters.</summary>
|
||||
[Parameter]
|
||||
public bool ShowFooter { get; set; } = true;
|
||||
|
||||
/// <summary>Extra content of the bar under the grid (totals of the visible rows...).</summary>
|
||||
[Parameter]
|
||||
public RenderFragment? Summary { get; set; }
|
||||
|
||||
/// <summary>Extra classes.</summary>
|
||||
[Parameter]
|
||||
public string? Class { get; set; }
|
||||
|
||||
/// <summary>The most rows an export writes.</summary>
|
||||
public const int MaxExportRows = 100_000;
|
||||
|
||||
/// <summary>The rows the request selects.</summary>
|
||||
public long Total => _total;
|
||||
|
||||
/// <summary>The keys of the selected rows.</summary>
|
||||
public IReadOnlyCollection<object> SelectedKeys => _selected;
|
||||
|
||||
/// <summary>The current row, when it is loaded.</summary>
|
||||
public TItem? CurrentItem => _current >= 0 && _loadedRows.TryGetValue(_current, out var item) ? item : default;
|
||||
|
||||
/// <summary>The request the grid sends to its source, without the page.</summary>
|
||||
public ListQuery CurrentQuery => new() { Search = Search, Filters = Filters, Sort = _sort };
|
||||
|
||||
private const float RowHeight = 30;
|
||||
|
||||
private int ColumnCount => _columns.Count + (Selectable ? 1 : 0) + (RowMenu is null ? 0 : 1);
|
||||
|
||||
private bool HasTotals => _columns.Any(c => c.Total);
|
||||
|
||||
private string? WrapStyle => Height is null ? null : "flex:none;height:" + Height;
|
||||
|
||||
private int PageCount => (int)Math.Ceiling(_total / (double)Math.Max(1, PageSize));
|
||||
|
||||
private bool AllLoadedSelected => KeyOf is not null && _loadedRows.Count > 0 && _loadedRows.Values.All(i => _selected.Contains(KeyOf(i)));
|
||||
|
||||
// Page numbers around the current one, -1 for the gap: 1 2 3 4 5 ... 108.
|
||||
private IEnumerable<int> PageNumbers
|
||||
{
|
||||
get
|
||||
{
|
||||
var last = PageCount - 1;
|
||||
var from = Math.Max(0, Math.Min(_page - 2, last - 4));
|
||||
var to = Math.Min(last, from + 4);
|
||||
if (from > 0)
|
||||
{
|
||||
yield return 0;
|
||||
if (from > 1)
|
||||
{
|
||||
yield return -1;
|
||||
}
|
||||
}
|
||||
|
||||
for (var n = from; n <= to; n++)
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
if (to < last)
|
||||
{
|
||||
if (to < last - 1)
|
||||
{
|
||||
yield return -2;
|
||||
}
|
||||
|
||||
yield return last;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnParametersSetAsync()
|
||||
{
|
||||
if (!_layoutLoaded)
|
||||
{
|
||||
_layoutLoaded = true;
|
||||
_sort = [.. Sort ?? []];
|
||||
await LoadLayoutAsync();
|
||||
}
|
||||
|
||||
var query = CurrentQuery;
|
||||
if (_lastQuery is not null && !query.SameRows(_lastQuery))
|
||||
{
|
||||
await ReloadAsync();
|
||||
}
|
||||
else if (_lastQuery is null && !Virtual)
|
||||
{
|
||||
_lastQuery = query;
|
||||
await LoadPageAsync(0);
|
||||
}
|
||||
|
||||
_lastQuery = query;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||
{
|
||||
if (firstRender)
|
||||
{
|
||||
await JS.InvokeVoidAsync("khaemhat.preventKeys", _wrap);
|
||||
}
|
||||
|
||||
if (_scrollToCurrent && _current >= 0)
|
||||
{
|
||||
_scrollToCurrent = false;
|
||||
await JS.InvokeVoidAsync("khaemhat.scrollGridRow", _wrap, _current);
|
||||
}
|
||||
|
||||
if (_focusEditor)
|
||||
{
|
||||
_focusEditor = false;
|
||||
await JS.InvokeVoidAsync("khaemhat.focus", "#" + EditorId);
|
||||
}
|
||||
|
||||
if (_placeMenu && _menu is not null)
|
||||
{
|
||||
_placeMenu = false;
|
||||
await JS.InvokeVoidAsync("khaemhat.keepInWindow", _menuRef);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads the rows again from the first one, keeping the selection.</summary>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task ReloadAsync()
|
||||
{
|
||||
_loadedRows.Clear();
|
||||
_current = -1;
|
||||
_editing = null;
|
||||
_lastQuery = CurrentQuery;
|
||||
if (Virtual)
|
||||
{
|
||||
if (_virtualize is not null)
|
||||
{
|
||||
// Other rows: start from the top, or the view would stay far below the new, shorter list.
|
||||
await JS.InvokeVoidAsync("khaemhat.scrollGridRow", _wrap, 0);
|
||||
await _virtualize.RefreshDataAsync();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
await LoadPageAsync(0);
|
||||
}
|
||||
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
/// <summary>Moves the focus into the grid.</summary>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task FocusAsync()
|
||||
{
|
||||
if (_current < 0 && _total > 0)
|
||||
{
|
||||
await SetCurrentAsync(0);
|
||||
}
|
||||
|
||||
await _wrap.FocusAsync();
|
||||
}
|
||||
|
||||
/// <summary>Removes every selection.</summary>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task ClearSelectionAsync()
|
||||
{
|
||||
_selected.Clear();
|
||||
await SelectionChanged.InvokeAsync(_selected);
|
||||
}
|
||||
|
||||
/// <summary>Opens the window that shows, hides and moves the columns.</summary>
|
||||
public void ShowColumns()
|
||||
{
|
||||
_chooser = [.. Ordered()];
|
||||
_columnsOpen = true;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes every row the request selects (at most <see cref="MaxExportRows"/>) to a CSV for Excel (semicolons,
|
||||
/// decimal comma) or an XLSX, and hands it to the browser.
|
||||
/// </summary>
|
||||
/// <param name="xlsx">XLSX instead of CSV.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task ExportAsync(bool xlsx)
|
||||
{
|
||||
var columns = _columns.Where(c => c.Export).ToList();
|
||||
var rows = new List<TItem>();
|
||||
var query = CurrentQuery;
|
||||
long total;
|
||||
do
|
||||
{
|
||||
var page = await Source(query.WithPage(rows.Count, ListQuery.MaxLimit), CancellationToken.None);
|
||||
total = page.Total;
|
||||
rows.AddRange(page.Items);
|
||||
if (page.Items.Count == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
while (rows.Count < total && rows.Count < MaxExportRows);
|
||||
|
||||
using var buffer = new MemoryStream();
|
||||
if (xlsx)
|
||||
{
|
||||
await using var writer = await XlsxWriter.CreateAsync(buffer, leaveOpen: true);
|
||||
await writer.StartSheetAsync(ExportName ?? Label ?? "Dati", [.. columns.Select(c => new XlsxColumn(c.Title, null, XlsxFormatOf(c)))]);
|
||||
foreach (var row in rows.Take(MaxExportRows))
|
||||
{
|
||||
await writer.WriteRowAsync(columns.Select(c => ExportValue(c, row)));
|
||||
}
|
||||
|
||||
await writer.CompleteAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
await using var writer = new CsvWriter(buffer, CsvOptions.Italian, leaveOpen: true);
|
||||
await writer.WriteRowAsync(columns.Select(c => (object?)c.Title));
|
||||
foreach (var row in rows.Take(MaxExportRows))
|
||||
{
|
||||
await writer.WriteRowAsync(columns.Select(c => ExportValue(c, row)));
|
||||
}
|
||||
|
||||
await writer.FlushAsync();
|
||||
}
|
||||
|
||||
buffer.Position = 0;
|
||||
var name = (ExportName ?? "export") + (xlsx ? ".xlsx" : ".csv");
|
||||
using var stream = new DotNetStreamReference(buffer, leaveOpen: true);
|
||||
await JS.InvokeVoidAsync("khaemhat.download", name, xlsx ? MediaTypes.Xlsx : "text/csv", stream);
|
||||
var count = Math.Min(rows.Count, MaxExportRows);
|
||||
Toasts.Show(ToastKind.Success, T.Format(total > count ? "Ui.Grid.ExportLimit" : "Ui.Grid.Exported", T.Number(count)));
|
||||
}
|
||||
|
||||
private static object? ExportValue(KhColumn<TItem> column, TItem row) => column.Value(row) switch
|
||||
{
|
||||
Enum value => value.ToString(),
|
||||
|
||||
// Amounts always with two decimals (0,00 rather than 0): adding 0.00m sets the scale.
|
||||
decimal value when column.Kind == KhColumnKind.Money => Math.Round(value, 2, MidpointRounding.AwayFromZero) + 0.00m,
|
||||
var value => value,
|
||||
};
|
||||
|
||||
private static XlsxFormat XlsxFormatOf(KhColumn<TItem> column) => column.Kind switch
|
||||
{
|
||||
KhColumnKind.Money => XlsxFormat.Euro,
|
||||
KhColumnKind.Number when column.Decimals == 0 => XlsxFormat.WholeNumber,
|
||||
KhColumnKind.Number => XlsxFormat.TwoDecimals,
|
||||
KhColumnKind.Date => XlsxFormat.Date,
|
||||
_ => XlsxFormat.General,
|
||||
};
|
||||
|
||||
private RenderFragment RowFragment(GridRow row) => __builder =>
|
||||
{
|
||||
var item = row.Item;
|
||||
var selected = KeyOf is not null && _selected.Contains(KeyOf(item));
|
||||
var classes = (selected ? "sel " : null) + (row.Index == _current ? "kh-cur " : null) + RowClass?.Invoke(item);
|
||||
<tr data-i="@row.Index" class="@classes" aria-selected="@(Selectable ? (selected ? "true" : "false") : null)" aria-rowindex="@(row.Index + 1)"
|
||||
@onclick="() => SetCurrentAsync(row.Index)" @ondblclick="() => OpenAsync(item)"
|
||||
@oncontextmenu="e => ShowMenu(row.Index, item, e)" @oncontextmenu:preventDefault="RowMenu is not null">
|
||||
@if (Selectable)
|
||||
{
|
||||
<td class="chkc">
|
||||
<button type="button" class="kh-bxbtn" role="checkbox" aria-checked="@(selected ? "true" : "false")" aria-label="@T["Ui.Grid.SelectRow"]" tabindex="-1"
|
||||
@onclick="() => ToggleAsync(item)" @onclick:stopPropagation>
|
||||
<span class="bx @(selected ? "on" : null)">@if (selected) { <KhIcon Name="check" /> }</span>
|
||||
</button>
|
||||
</td>
|
||||
}
|
||||
@foreach (var column in _columns)
|
||||
{
|
||||
var editing = _editing is { } e && e.Index == row.Index && e.Column == column.Id;
|
||||
<td class="@CellClass(column, item, editing)" @ondblclick="() => BeginEdit(row.Index, column, item)" @ondblclick:stopPropagation="column.Edit is not null">
|
||||
@if (editing)
|
||||
{
|
||||
<input id="@EditorId" class="kh-celledit @(column.IsNumeric ? "num" : null) @(_editError is null ? null : "err")" value="@_editText"
|
||||
@oninput="e => _editText = e.Value as string ?? string.Empty" aria-label="@column.Title"
|
||||
aria-invalid="@(_editError is null ? null : "true")" title="@_editError" />
|
||||
}
|
||||
else if (column.Template is not null)
|
||||
{
|
||||
@column.Template(item)
|
||||
}
|
||||
else
|
||||
{
|
||||
@column.Format(item, T)
|
||||
}
|
||||
</td>
|
||||
}
|
||||
@if (RowMenu is not null)
|
||||
{
|
||||
<td class="kh-rowmenu">
|
||||
<button type="button" class="kh-rowbtn" tabindex="-1" aria-label="@T["Ui.Grid.RowMenu"]" @onclick="e => ShowMenu(row.Index, item, e)" @onclick:stopPropagation>
|
||||
<KhIcon Name="more" Class="sm" />
|
||||
</button>
|
||||
</td>
|
||||
}
|
||||
</tr>
|
||||
};
|
||||
|
||||
private string EditorId => "kh-gedit-" + GetHashCode().ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
|
||||
private static string? CellClass(KhColumn<TItem> column, TItem item, bool editing)
|
||||
{
|
||||
var classes = column.Kind switch
|
||||
{
|
||||
KhColumnKind.Code => "code",
|
||||
KhColumnKind.Number or KhColumnKind.Money => "num",
|
||||
_ => null,
|
||||
};
|
||||
if (column.CellClass?.Invoke(item) is { } extra)
|
||||
{
|
||||
classes += " " + extra;
|
||||
}
|
||||
|
||||
return editing ? classes + " ed" : classes;
|
||||
}
|
||||
|
||||
private ListSort? SortOf(KhColumn<TItem> column) => _sort.FirstOrDefault(s => s.Field == column.Id);
|
||||
|
||||
private async ValueTask<ItemsProviderResult<GridRow>> ProvideAsync(ItemsProviderRequest request)
|
||||
{
|
||||
var count = Math.Clamp(request.Count, 1, ListQuery.MaxLimit);
|
||||
ListPage<TItem> page;
|
||||
try
|
||||
{
|
||||
page = await Source(CurrentQuery.WithPage(request.StartIndex, count), request.CancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return new ItemsProviderResult<GridRow>([], (int)Math.Min(_total, int.MaxValue));
|
||||
}
|
||||
|
||||
var rows = new List<GridRow>(page.Items.Count);
|
||||
for (var i = 0; i < page.Items.Count; i++)
|
||||
{
|
||||
_loadedRows[request.StartIndex + i] = page.Items[i];
|
||||
rows.Add(new GridRow(request.StartIndex + i, page.Items[i]));
|
||||
}
|
||||
|
||||
TrimLoaded(request.StartIndex);
|
||||
var changed = page.Total != _total || !_loaded || !ReferenceEquals(page.Totals, _totals);
|
||||
_total = page.Total;
|
||||
_totals = page.Totals;
|
||||
_loaded = true;
|
||||
if (changed)
|
||||
{
|
||||
_ = InvokeAsync(StateHasChanged);
|
||||
}
|
||||
|
||||
return new ItemsProviderResult<GridRow>(rows, (int)Math.Min(page.Total, int.MaxValue));
|
||||
}
|
||||
|
||||
// Keeps the rows around the visible ones, so scrolling through 100,000 rows does not keep them all.
|
||||
private void TrimLoaded(int around)
|
||||
{
|
||||
if (_loadedRows.Count <= 3000)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var index in _loadedRows.Keys.Where(k => Math.Abs(k - around) > 1500 && k != _current).ToList())
|
||||
{
|
||||
_loadedRows.Remove(index);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task LoadPageAsync(int page)
|
||||
{
|
||||
if (_pageLoad is not null)
|
||||
{
|
||||
await _pageLoad.CancelAsync();
|
||||
_pageLoad.Dispose();
|
||||
}
|
||||
|
||||
_pageLoad = new CancellationTokenSource();
|
||||
var size = Math.Clamp(PageSize, 1, ListQuery.MaxLimit);
|
||||
try
|
||||
{
|
||||
var result = await Source(CurrentQuery.WithPage(page * size, size), _pageLoad.Token);
|
||||
_page = page;
|
||||
_pageOffset = page * size;
|
||||
_pageItems = result.Items;
|
||||
_total = result.Total;
|
||||
_totals = result.Totals;
|
||||
_loaded = true;
|
||||
_loadedRows.Clear();
|
||||
for (var i = 0; i < result.Items.Count; i++)
|
||||
{
|
||||
_loadedRows[_pageOffset + i] = result.Items[i];
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// A newer request replaced this one.
|
||||
}
|
||||
}
|
||||
|
||||
private async Task GoToPageAsync(int page)
|
||||
{
|
||||
if (page < 0 || page >= PageCount)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await LoadPageAsync(page);
|
||||
_current = _pageOffset;
|
||||
_scrollToCurrent = true;
|
||||
}
|
||||
|
||||
private async Task SortAsync(KhColumn<TItem> column, bool add)
|
||||
{
|
||||
var existing = SortOf(column);
|
||||
var next = new ListSort(column.Id, existing is { Descending: false });
|
||||
if (add)
|
||||
{
|
||||
var index = _sort.FindIndex(s => s.Field == column.Id);
|
||||
if (index >= 0)
|
||||
{
|
||||
_sort[index] = next;
|
||||
}
|
||||
else
|
||||
{
|
||||
_sort.Add(next);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_sort = [next];
|
||||
}
|
||||
|
||||
await SortChanged.InvokeAsync(_sort);
|
||||
await ReloadAsync();
|
||||
}
|
||||
|
||||
private async Task SetCurrentAsync(int index)
|
||||
{
|
||||
if (_total == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
index = (int)Math.Clamp(index, 0, _total - 1);
|
||||
if (!Virtual && (index < _pageOffset || index >= _pageOffset + _pageItems.Count))
|
||||
{
|
||||
await LoadPageAsync(index / Math.Max(1, PageSize));
|
||||
}
|
||||
|
||||
_current = index;
|
||||
_scrollToCurrent = true;
|
||||
if (CurrentItem is { } item)
|
||||
{
|
||||
await OnCurrent.InvokeAsync(item);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task OpenAsync(TItem item)
|
||||
{
|
||||
if (_editing is null)
|
||||
{
|
||||
await OnOpen.InvokeAsync(item);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ToggleAsync(TItem item)
|
||||
{
|
||||
if (KeyOf is null || !Selectable)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var key = KeyOf(item);
|
||||
if (!_selected.Remove(key))
|
||||
{
|
||||
_selected.Add(key);
|
||||
}
|
||||
|
||||
await SelectionChanged.InvokeAsync(_selected);
|
||||
}
|
||||
|
||||
private async Task ToggleAllAsync()
|
||||
{
|
||||
if (KeyOf is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var keys = _loadedRows.Values.Select(KeyOf).ToList();
|
||||
if (AllLoadedSelected)
|
||||
{
|
||||
_selected.ExceptWith(keys);
|
||||
}
|
||||
else
|
||||
{
|
||||
_selected.UnionWith(keys);
|
||||
}
|
||||
|
||||
await SelectionChanged.InvokeAsync(_selected);
|
||||
}
|
||||
|
||||
private async Task OnKeyDownAsync(KeyboardEventArgs e)
|
||||
{
|
||||
if (_editing is not null)
|
||||
{
|
||||
if (e.Key == "Enter")
|
||||
{
|
||||
await CommitEditAsync();
|
||||
}
|
||||
else if (e.Key == "Escape")
|
||||
{
|
||||
_editing = null;
|
||||
_editError = null;
|
||||
await _wrap.FocusAsync();
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var page = 15;
|
||||
switch (e.Key)
|
||||
{
|
||||
case "ArrowDown":
|
||||
await SetCurrentAsync(_current + 1);
|
||||
break;
|
||||
case "ArrowUp":
|
||||
await SetCurrentAsync(Math.Max(0, _current - 1));
|
||||
break;
|
||||
case "PageDown":
|
||||
await SetCurrentAsync(_current + page);
|
||||
break;
|
||||
case "PageUp":
|
||||
await SetCurrentAsync(Math.Max(0, _current - page));
|
||||
break;
|
||||
case "Home":
|
||||
await SetCurrentAsync(0);
|
||||
break;
|
||||
case "End":
|
||||
await SetCurrentAsync((int)Math.Min(_total - 1, int.MaxValue));
|
||||
break;
|
||||
case "Enter" when CurrentItem is { } item:
|
||||
await OpenAsync(item);
|
||||
break;
|
||||
case " " when CurrentItem is { } item:
|
||||
await ToggleAsync(item);
|
||||
break;
|
||||
case "F2" when CurrentItem is { } item && _columns.FirstOrDefault(c => c.Edit is not null) is { } column:
|
||||
BeginEdit(_current, column, item);
|
||||
break;
|
||||
case "ContextMenu" or "F10" when (e.Key == "ContextMenu" || e.ShiftKey) && CurrentItem is { } item && RowMenu is not null:
|
||||
_menu = new RowMenuState(_current, item, null, null);
|
||||
_placeMenu = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void BeginEdit(int index, KhColumn<TItem> column, TItem item)
|
||||
{
|
||||
if (column.Edit is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_current = index;
|
||||
_editing = (index, column.Id);
|
||||
_editError = null;
|
||||
_editText = column.Value(item) switch
|
||||
{
|
||||
decimal d => ItalianNumber.Format(d, column.Kind == KhColumnKind.Money ? 2 : column.Decimals, T.Culture),
|
||||
var value => column.FormatValue(value, T),
|
||||
};
|
||||
_focusEditor = true;
|
||||
}
|
||||
|
||||
private async Task CommitEditAsync()
|
||||
{
|
||||
if (_editing is not { } editing || !_loadedRows.TryGetValue(editing.Index, out var item)
|
||||
|| _columns.FirstOrDefault(c => c.Id == editing.Column) is not { Edit: { } edit })
|
||||
{
|
||||
_editing = null;
|
||||
return;
|
||||
}
|
||||
|
||||
var error = await edit(item, _editText);
|
||||
_editError = error;
|
||||
if (error is not null)
|
||||
{
|
||||
Toasts.Show(ToastKind.Error, error);
|
||||
_focusEditor = true;
|
||||
return;
|
||||
}
|
||||
|
||||
_editing = null;
|
||||
|
||||
// Read the rows again where they are: the totals and other columns may depend on the value.
|
||||
if (!Virtual)
|
||||
{
|
||||
var current = _current;
|
||||
await LoadPageAsync(_page);
|
||||
_current = current;
|
||||
}
|
||||
else if (_virtualize is not null)
|
||||
{
|
||||
await _virtualize.RefreshDataAsync();
|
||||
}
|
||||
|
||||
await _wrap.FocusAsync();
|
||||
}
|
||||
|
||||
private void ShowMenu(int index, TItem item, MouseEventArgs e)
|
||||
{
|
||||
if (RowMenu is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_current = index;
|
||||
_menu = new RowMenuState(index, item, e.ClientX, e.ClientY);
|
||||
_placeMenu = true;
|
||||
}
|
||||
|
||||
private void CloseMenu() => _menu = null;
|
||||
|
||||
private async Task RunMenuAsync(ToolbarItem item)
|
||||
{
|
||||
_menu = null;
|
||||
if (item.OnClick is not null && !item.Disabled)
|
||||
{
|
||||
await item.OnClick();
|
||||
}
|
||||
}
|
||||
|
||||
private static string MenuStyle(RowMenuState menu) => menu.X is { } x && menu.Y is { } y
|
||||
? string.Create(System.Globalization.CultureInfo.InvariantCulture, $"position:fixed;left:{x:0}px;top:{y:0}px;right:auto")
|
||||
: "position:fixed;left:40%;top:40%;right:auto";
|
||||
|
||||
private IEnumerable<KhColumn<TItem>> Ordered() => KhGridLayout.Apply(Columns, new KhGridLayout(_columns.Select(c => c.Id).Concat(Columns.Select(c => c.Id)).Distinct().ToList(), []));
|
||||
|
||||
private async Task LoadLayoutAsync()
|
||||
{
|
||||
var layout = LayoutKey is null ? null : KhGridLayout.Parse(await Session.ReadSettingAsync(KhGridLayout.KeyOf(LayoutKey)));
|
||||
_hidden = new HashSet<string>(layout?.Hidden ?? Columns.Where(c => !c.Visible).Select(c => c.Id), StringComparer.Ordinal);
|
||||
_columns = KhGridLayout.Apply(Columns, layout);
|
||||
}
|
||||
|
||||
private async Task ToggleColumnAsync(KhColumn<TItem> column, bool shown)
|
||||
{
|
||||
if (shown)
|
||||
{
|
||||
_hidden.Remove(column.Id);
|
||||
}
|
||||
else if (_chooser.Count(c => !_hidden.Contains(c.Id)) > 1)
|
||||
{
|
||||
_hidden.Add(column.Id);
|
||||
}
|
||||
|
||||
await SaveLayoutAsync();
|
||||
}
|
||||
|
||||
private async Task MoveColumnAsync(int index, int direction)
|
||||
{
|
||||
var target = index + direction;
|
||||
if (target < 0 || target >= _chooser.Count)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
(_chooser[index], _chooser[target]) = (_chooser[target], _chooser[index]);
|
||||
await SaveLayoutAsync();
|
||||
}
|
||||
|
||||
private async Task ResetColumnsAsync()
|
||||
{
|
||||
if (LayoutKey is not null)
|
||||
{
|
||||
await Session.SaveSettingAsync(KhGridLayout.KeyOf(LayoutKey), null);
|
||||
}
|
||||
|
||||
_hidden = new HashSet<string>(Columns.Where(c => !c.Visible).Select(c => c.Id), StringComparer.Ordinal);
|
||||
_columns = KhGridLayout.Apply(Columns, null);
|
||||
_chooser = [.. Columns];
|
||||
}
|
||||
|
||||
private async Task SaveLayoutAsync()
|
||||
{
|
||||
var layout = new KhGridLayout([.. _chooser.Select(c => c.Id)], [.. _hidden]);
|
||||
_columns = KhGridLayout.Apply(Columns, layout);
|
||||
if (LayoutKey is not null)
|
||||
{
|
||||
await Session.SaveSettingAsync(KhGridLayout.KeyOf(LayoutKey), layout.ToJson());
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_pageLoad is not null)
|
||||
{
|
||||
await _pageLoad.CancelAsync();
|
||||
_pageLoad.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private readonly record struct GridRow(int Index, TItem Item);
|
||||
|
||||
private sealed record RowMenuState(int Index, TItem Item, double? X, double? Y);
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
@typeparam TLine where TLine : class
|
||||
@implements IDisposable
|
||||
@inject IJSRuntime JS
|
||||
|
||||
@* The lines of a document (SPEC §10.5, mockup 020): every cell is a field. Enter goes to the next cell (Shift+Enter
|
||||
back), arrows up and down to the same cell of the other line, Tab as usual, F4 opens the lookup of the cell,
|
||||
Ctrl+Down inserts a line under the current one, Ctrl+Canc removes it. An empty line always waits at the end: typing in
|
||||
it adds the line. Descriptive lines hold only a text across the row. *@
|
||||
<div class="kh-linesgrid @Class">
|
||||
<div class="gridwrap">
|
||||
<table class="grid kh-lines" aria-label="@Label" @ref="_table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col" class="kh-ln">#</th>
|
||||
@foreach (var column in Columns)
|
||||
{
|
||||
<th scope="col" class="@(column.IsNumeric ? "num" : null)" style="@(column.Width is null ? null : "width:" + column.Width)">@column.Title</th>
|
||||
}
|
||||
@if (!ReadOnly)
|
||||
{
|
||||
<th scope="col" class="kh-rowmenu"><span class="kh-sr">@T["Ui.Lines.Actions"]</span></th>
|
||||
}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (var r = 0; r < RowCount; r++)
|
||||
{
|
||||
var row = r;
|
||||
var line = LineAt(r);
|
||||
var pending = r == Lines.Count;
|
||||
var descriptive = !pending && IsDescriptive?.Invoke(line) == true;
|
||||
<tr @key="line" class="@(descriptive ? "kh-desc" : null) @(pending ? "kh-pending" : null)">
|
||||
<td class="kh-ln">@(pending ? null : (r + 1).ToString(T.Culture))</td>
|
||||
@if (descriptive && DescriptionColumn is { } descriptionColumn)
|
||||
{
|
||||
var c = IndexOf(descriptionColumn);
|
||||
<td colspan="@Columns.Count" class="desc-row">
|
||||
@Cell(row, c, line, descriptionColumn)
|
||||
</td>
|
||||
}
|
||||
else
|
||||
{
|
||||
@for (var c = 0; c < Columns.Count; c++)
|
||||
{
|
||||
var column = Columns[c];
|
||||
<td class="@CellClass(column, line)">
|
||||
@if (column.IsEditable && !ReadOnly)
|
||||
{
|
||||
@Cell(row, c, line, column)
|
||||
}
|
||||
else
|
||||
{
|
||||
@Display(line, column)
|
||||
}
|
||||
</td>
|
||||
}
|
||||
}
|
||||
@if (!ReadOnly)
|
||||
{
|
||||
<td class="kh-rowmenu">
|
||||
@if (!pending)
|
||||
{
|
||||
<button type="button" class="kh-rowbtn" tabindex="-1" title="@T["Ui.Lines.Remove"]" aria-label="@T.Format("Ui.Lines.RemoveLine", row + 1)"
|
||||
@onclick="() => RemoveAt(row)"><KhIcon Name="trash" Class="sm" /></button>
|
||||
}
|
||||
</td>
|
||||
}
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@if (!ReadOnly)
|
||||
{
|
||||
<div class="kh-linesbar">
|
||||
<button type="button" class="btn" @onclick="() => InsertAfter(Lines.Count - 1)"><KhIcon Name="plus" /> @T["Ui.Lines.Add"] <span class="kbd">@T["Ui.Lines.KeyAdd"]</span></button>
|
||||
@if (NewDescriptive is not null)
|
||||
{
|
||||
<button type="button" class="btn" @onclick="AddDescriptive"><KhIcon Name="edit" /> @T["Ui.Lines.AddDescriptive"]</button>
|
||||
}
|
||||
<span class="grow"></span>
|
||||
<span class="kbdhint"><kbd>@T["Ui.Radar.KeyEnter"]</kbd> @T["Ui.Lines.HintNext"]</span>
|
||||
<span class="kbdhint"><kbd>F4</kbd> @T["Ui.Lines.HintLookup"]</span>
|
||||
<span class="kbdhint"><kbd>@T["Ui.Lines.KeyRemove"]</kbd> @T["Ui.Lines.HintRemove"]</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private readonly Dictionary<(TLine Line, string Column), string> _typed = [];
|
||||
private readonly HashSet<(TLine Line, string Column)> _errors = [];
|
||||
private ElementReference _table;
|
||||
private DotNetObjectReference<KhLinesGrid<TLine>>? _self;
|
||||
private TLine? _pending;
|
||||
|
||||
/// <summary>The lines; the grid adds and removes them in place.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public IList<TLine> Lines { get; set; } = [];
|
||||
|
||||
/// <summary>The columns.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public IReadOnlyList<KhLineColumn<TLine>> Columns { get; set; } = [];
|
||||
|
||||
/// <summary>Makes a new, empty line.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public Func<TLine> NewLine { get; set; } = default!;
|
||||
|
||||
/// <summary>Whether a line holds nothing yet (the waiting line becomes a line when this turns false).</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public Func<TLine, bool> IsEmpty { get; set; } = default!;
|
||||
|
||||
/// <summary>Whether a line is descriptive (text only).</summary>
|
||||
[Parameter]
|
||||
public Func<TLine, bool>? IsDescriptive { get; set; }
|
||||
|
||||
/// <summary>Makes a descriptive line; none hides the button.</summary>
|
||||
[Parameter]
|
||||
public Func<TLine>? NewDescriptive { get; set; }
|
||||
|
||||
/// <summary>The column a descriptive line shows across the row.</summary>
|
||||
[Parameter]
|
||||
public KhLineColumn<TLine>? DescriptionColumn { get; set; }
|
||||
|
||||
/// <summary>No changes (an issued document).</summary>
|
||||
[Parameter]
|
||||
public bool ReadOnly { get; set; }
|
||||
|
||||
/// <summary>Called after every change, to recompute the totals and mark the page modified.</summary>
|
||||
[Parameter]
|
||||
public EventCallback OnChanged { get; set; }
|
||||
|
||||
/// <summary>The label read by screen readers.</summary>
|
||||
[Parameter]
|
||||
public string? Label { get; set; }
|
||||
|
||||
/// <summary>Extra classes.</summary>
|
||||
[Parameter]
|
||||
public string? Class { get; set; }
|
||||
|
||||
private int RowCount => Lines.Count + (ReadOnly ? 0 : 1);
|
||||
|
||||
private TLine Pending => _pending ??= NewLine();
|
||||
|
||||
private TLine LineAt(int index) => index < Lines.Count ? Lines[index] : Pending;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||
{
|
||||
if (firstRender)
|
||||
{
|
||||
_self = DotNetObjectReference.Create(this);
|
||||
await JS.InvokeVoidAsync("khaemhat.linesGrid", _table, _self);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Moves the focus to a cell of a line (after a lookup, for example).</summary>
|
||||
/// <param name="line">The line.</param>
|
||||
/// <param name="columnId">The column id.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task FocusCellAsync(TLine line, string columnId)
|
||||
{
|
||||
var row = Lines.IndexOf(line);
|
||||
await JS.InvokeVoidAsync("khaemhat.focusLineCell", _table, row < 0 ? Lines.Count : row, Columns.ToList().FindIndex(c => c.Id == columnId));
|
||||
}
|
||||
|
||||
/// <summary>Called by the browser on Ctrl+Down: a new line under the given one.</summary>
|
||||
/// <param name="row">The row.</param>
|
||||
/// <returns>A task.</returns>
|
||||
[JSInvokable]
|
||||
public Task InsertAfterAsync(int row)
|
||||
{
|
||||
InsertAfter(row);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>Called by the browser on Ctrl+Canc.</summary>
|
||||
/// <param name="row">The row.</param>
|
||||
/// <returns>A task.</returns>
|
||||
[JSInvokable]
|
||||
public Task RemoveAtAsync(int row)
|
||||
{
|
||||
RemoveAt(row);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>Called by the browser on F4 in a cell.</summary>
|
||||
/// <param name="row">The row.</param>
|
||||
/// <param name="column">The column index.</param>
|
||||
/// <returns>A task.</returns>
|
||||
[JSInvokable]
|
||||
public async Task LookupAsync(int row, int column)
|
||||
{
|
||||
if (ReadOnly || row < 0 || row > Lines.Count || column < 0 || column >= Columns.Count || Columns[column].Lookup is not { } lookup)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var line = LineAt(row);
|
||||
await lookup(line);
|
||||
await InvokeAsync(() => CommitPendingAsync(line));
|
||||
}
|
||||
|
||||
private RenderFragment Cell(int row, int index, TLine line, KhLineColumn<TLine> column) => __builder =>
|
||||
{
|
||||
var key = (line, column.Id);
|
||||
<input class="kh-cell @(column.IsNumeric ? "num" : null) @(column.Kind == KhColumnKind.Code ? "code" : null) @(_errors.Contains(key) ? "err" : null)"
|
||||
data-r="@row" data-c="@index" value="@(_typed.TryGetValue(key, out var typed) ? typed : Text(line, column))"
|
||||
inputmode="@(column.IsNumeric ? "decimal" : null)" aria-label="@T.Format("Ui.Lines.Cell", column.Title, row + 1)"
|
||||
aria-invalid="@(_errors.Contains(key) ? "true" : null)" title="@(_errors.Contains(key) ? T["Ui.Validation.Number"] : null)"
|
||||
data-kh-prevent="Ctrl+ArrowDown Ctrl+Delete F4 Enter" @onchange="e => SetAsync(line, column, e.Value as string)" />
|
||||
};
|
||||
|
||||
private string Text(TLine line, KhLineColumn<TLine> column) => column.Value(line) switch
|
||||
{
|
||||
null => string.Empty,
|
||||
decimal d => ItalianNumber.Format(d, column.Decimals, T.Culture),
|
||||
var value => Convert.ToString(value, T.Culture) ?? string.Empty,
|
||||
};
|
||||
|
||||
private string Display(TLine line, KhLineColumn<TLine> column) => column.Value(line) switch
|
||||
{
|
||||
null => string.Empty,
|
||||
decimal d when column.Kind == KhColumnKind.Money => T.Money(d),
|
||||
decimal d => T.Number(d, column.Decimals),
|
||||
var value => Convert.ToString(value, T.Culture) ?? string.Empty,
|
||||
};
|
||||
|
||||
private static string? CellClass(KhLineColumn<TLine> column, TLine line) => column.Kind switch
|
||||
{
|
||||
KhColumnKind.Code => "code kh-ce",
|
||||
KhColumnKind.Number or KhColumnKind.Money => column.IsEditable ? "num kh-ce" : "num",
|
||||
_ => column.IsEditable ? "kh-ce" : null,
|
||||
};
|
||||
|
||||
private int IndexOf(KhLineColumn<TLine> column) => Columns.ToList().IndexOf(column);
|
||||
|
||||
private async Task SetAsync(TLine line, KhLineColumn<TLine> column, string? text)
|
||||
{
|
||||
var key = (line, column.Id);
|
||||
if (column.SetNumber is { } setNumber)
|
||||
{
|
||||
// Show what was typed first, so the formatted value below reaches the field even when it equals the old one.
|
||||
_typed[key] = text ?? string.Empty;
|
||||
StateHasChanged();
|
||||
await Task.Yield();
|
||||
if (!ItalianNumber.TryParse(text, out var number))
|
||||
{
|
||||
_errors.Add(key);
|
||||
return;
|
||||
}
|
||||
|
||||
_typed.Remove(key);
|
||||
_errors.Remove(key);
|
||||
setNumber(line, number is { } n ? Math.Round(n, column.Decimals, MidpointRounding.AwayFromZero) : null);
|
||||
}
|
||||
else
|
||||
{
|
||||
column.SetText?.Invoke(line, string.IsNullOrWhiteSpace(text) ? null : text.Trim());
|
||||
}
|
||||
|
||||
await CommitPendingAsync(line);
|
||||
}
|
||||
|
||||
// The waiting line becomes a line of the document when something is typed in it.
|
||||
private async Task CommitPendingAsync(TLine line)
|
||||
{
|
||||
if (ReferenceEquals(line, _pending) && !IsEmpty(line))
|
||||
{
|
||||
Lines.Add(line);
|
||||
_pending = NewLine();
|
||||
}
|
||||
|
||||
await OnChanged.InvokeAsync();
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private void InsertAfter(int row)
|
||||
{
|
||||
if (ReadOnly)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var at = Math.Clamp(row + 1, 0, Lines.Count);
|
||||
Lines.Insert(at, NewLine());
|
||||
_ = OnChanged.InvokeAsync();
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private void AddDescriptive()
|
||||
{
|
||||
if (NewDescriptive is null || ReadOnly)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Lines.Add(NewDescriptive());
|
||||
_ = OnChanged.InvokeAsync();
|
||||
_ = InvokeAsync(async () =>
|
||||
{
|
||||
await Task.Yield();
|
||||
await JS.InvokeVoidAsync("khaemhat.focusLineCell", _table, Lines.Count - 1, DescriptionColumn is null ? 0 : IndexOf(DescriptionColumn));
|
||||
});
|
||||
}
|
||||
|
||||
private void RemoveAt(int row)
|
||||
{
|
||||
if (ReadOnly || row < 0 || row >= Lines.Count)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var line = Lines[row];
|
||||
Lines.RemoveAt(row);
|
||||
foreach (var key in _typed.Keys.Where(k => ReferenceEquals(k.Line, line)).ToList())
|
||||
{
|
||||
_typed.Remove(key);
|
||||
}
|
||||
|
||||
_errors.RemoveWhere(k => ReferenceEquals(k.Line, line));
|
||||
_ = OnChanged.InvokeAsync();
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose() => _self?.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,607 @@
|
||||
@typeparam TItem
|
||||
@implements IDisposable
|
||||
@inject ShellSession Session
|
||||
@inject KeyboardShortcutService Keys
|
||||
@inject IJSRuntime JS
|
||||
|
||||
@* The radar of a list (SPEC §10.7 KhRadar, mockup 012): search box, filters of the bar, filter chips, saved filters,
|
||||
column layout, export, and the grid with selection. F9 brings the focus to the search box, arrows move into the
|
||||
rows, Enter opens, Space selects. In a dialog (hotlink F4, mockup 023) Enter picks the row. *@
|
||||
<div class="kh-radar @(Compact ? "compact" : null) @Class">
|
||||
@if (Toolbar is not null || ShowHints)
|
||||
{
|
||||
<div class="kh-radarbar">
|
||||
@Toolbar
|
||||
<div class="grow"></div>
|
||||
@if (ShowHints)
|
||||
{
|
||||
<span class="kbdhint"><kbd>F9</kbd> @T["Ui.Radar.HintRadar"]</span>
|
||||
<span class="kbdhint"><kbd>@T["Ui.Radar.KeyEnter"]</kbd> @(Picking ? T["Ui.Radar.HintPick"] : T["Ui.Radar.HintOpen"])</span>
|
||||
@if (Selectable)
|
||||
{
|
||||
<span class="kbdhint"><kbd>@T["Ui.Radar.KeySpace"]</kbd> @T["Ui.Radar.HintSelect"]</span>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
<div class="panel kh-radarpanel">
|
||||
<div class="filters">
|
||||
<label class="in kh-rsearch">
|
||||
<KhIcon Name="search" Class="sm" />
|
||||
<span class="kh-sr">@T["Ui.Radar.Search"]</span>
|
||||
<input type="search" value="@_search" placeholder="@(SearchPlaceholder ?? T["Ui.Radar.SearchPlaceholder"])" autocomplete="off"
|
||||
data-kh-prevent="ArrowDown Enter" @oninput="OnSearchInput" @onkeydown="OnSearchKeyAsync" @ref="_searchBox" />
|
||||
</label>
|
||||
@foreach (var quick in QuickFilters)
|
||||
{
|
||||
var current = QuickValue(quick);
|
||||
<div class="f">
|
||||
<label for="@QuickId(quick)">@quick.Label</label>
|
||||
<select id="@QuickId(quick)" class="in" @onchange="e => SetQuickAsync(quick, e.Value as string)">
|
||||
@foreach (var option in quick.Options)
|
||||
{
|
||||
<option value="@option.Value" selected="@(option.Value == current)">@option.Text</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
}
|
||||
@foreach (var filter in _filters.Where(f => !IsQuick(f)))
|
||||
{
|
||||
<KhChip Text="@ChipText(filter)" OnRemove="() => RemoveFilterAsync(filter)" />
|
||||
}
|
||||
<button type="button" class="btn kh-addfilter" @onclick="OpenBuilder"><KhIcon Name="filter" /> @T["Ui.Radar.AddFilter"]</button>
|
||||
<div class="grow"></div>
|
||||
<KhIconButton Icon="star" Text="@T["Ui.Radar.Saved"]" Active="IsSaved" OnClick="() => _savedOpen = true" />
|
||||
<KhIconButton Icon="columns" Text="@T["Ui.Grid.Columns"]" OnClick="() => _grid?.ShowColumns()" />
|
||||
@if (!Picking)
|
||||
{
|
||||
<div class="pop kh-morewrap">
|
||||
<KhIconButton Icon="download" Text="@T["Ui.Grid.Export"]" Active="_exportOpen" OnClick="() => _exportOpen = !_exportOpen" />
|
||||
@if (_exportOpen)
|
||||
{
|
||||
<div class="kh-catch" @onclick="() => _exportOpen = false"></div>
|
||||
<div class="popmenu" role="menu">
|
||||
<button type="button" role="menuitem" class="mi" @onclick="() => ExportAsync(false)"><KhIcon Name="file" /><span class="grow">@T["Ui.Grid.ExportCsv"]</span></button>
|
||||
<button type="button" role="menuitem" class="mi" @onclick="() => ExportAsync(true)"><KhIcon Name="grid" /><span class="grow">@T["Ui.Grid.ExportXlsx"]</span></button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<KhGrid TItem="TItem" @ref="_grid" Columns="Columns" Source="Source" Search="@_appliedSearch" Filters="_filters" Sort="_sort" SortChanged="s => _sort = [.. s]"
|
||||
KeyOf="KeyOf" Selectable="Selectable" SelectionChanged="SelectionChanged" OnOpen="OnOpen" OnCurrent="OnCurrent" RowClass="RowClass" RowMenu="RowMenu"
|
||||
LayoutKey="@("radar." + Id)" ExportName="@ExportName" Label="@Label" Height="@Height" Summary="Summary" Empty="@T["Ui.Radar.Empty"]" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<KhDialog Open="_builderOpen" Title="@T["Ui.Radar.AddFilter"]" Icon="filter" Size="sm" OnClose="() => _builderOpen = false">
|
||||
<ChildContent>
|
||||
<div class="form plain kh-filterform">
|
||||
<div class="f c12">
|
||||
<label for="kh-ff-col-@Id">@T["Ui.Radar.Field"]</label>
|
||||
<select id="kh-ff-col-@Id" class="in" @onchange="e => PickColumn(e.Value as string)">
|
||||
@foreach (var column in Filterable)
|
||||
{
|
||||
<option value="@column.Id" selected="@(column.Id == _builder.Column?.Id)">@column.Title</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
@if (_builder.Column is { } picked)
|
||||
{
|
||||
<div class="f c12">
|
||||
<label for="kh-ff-op-@Id">@T["Ui.Radar.Operator"]</label>
|
||||
<select id="kh-ff-op-@Id" class="in" @onchange="e => SetOperator(e.Value as string)">
|
||||
@foreach (var op in OperatorsOf(picked))
|
||||
{
|
||||
<option value="@op" selected="@(op == _builder.Operator)">@T["Ui.Radar.Op." + op]</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
@if (_builder.Operator is not (ListFilterOperator.IsEmpty or ListFilterOperator.IsNotEmpty))
|
||||
{
|
||||
@if (picked.Choices is { } choices)
|
||||
{
|
||||
<fieldset class="f c12 kh-choices">
|
||||
<legend>@T["Ui.Radar.Values"]</legend>
|
||||
@foreach (var choice in choices)
|
||||
{
|
||||
<label class="kh-colcheck">
|
||||
<input type="checkbox" checked="@_builder.Choices.Contains(choice.Value)" @onchange="e => ToggleChoice(choice.Value, e.Value is true)" />
|
||||
@choice.Text
|
||||
</label>
|
||||
}
|
||||
</fieldset>
|
||||
}
|
||||
else if (picked.Kind == KhColumnKind.Bool)
|
||||
{
|
||||
<KhSelect TValue="string" Label="@T["Ui.Radar.Value"]" Span="12" @bind-Value="_builder.Text"
|
||||
Options="@([new("true", T["Ui.Grid.Yes"]), new("false", T["Ui.Grid.No"])])" />
|
||||
}
|
||||
else if (picked.Kind == KhColumnKind.Date)
|
||||
{
|
||||
<KhDateBox Label="@T["Ui.Radar.Value"]" Span="@(_builder.Operator == ListFilterOperator.Between ? 6 : 12)" @bind-Value="_builder.Date" />
|
||||
@if (_builder.Operator == ListFilterOperator.Between)
|
||||
{
|
||||
<KhDateBox Label="@T["Ui.Radar.ValueTo"]" Span="6" @bind-Value="_builder.DateTo" />
|
||||
}
|
||||
}
|
||||
else if (picked.IsNumeric)
|
||||
{
|
||||
<KhNumberBox Label="@T["Ui.Radar.Value"]" Span="@(_builder.Operator == ListFilterOperator.Between ? 6 : 12)" Decimals="@NumberDecimals(picked)" @bind-Value="_builder.Number" />
|
||||
@if (_builder.Operator == ListFilterOperator.Between)
|
||||
{
|
||||
<KhNumberBox Label="@T["Ui.Radar.ValueTo"]" Span="6" Decimals="@NumberDecimals(picked)" @bind-Value="_builder.NumberTo" />
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
<KhTextBox Label="@T["Ui.Radar.Value"]" Span="12" @bind-Value="_builder.Text" />
|
||||
}
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</ChildContent>
|
||||
<Footer>
|
||||
<button type="button" class="btn" @onclick="() => _builderOpen = false">@T["Ui.Grid.Close"]</button>
|
||||
<button type="button" class="btn primary" disabled="@(BuiltFilter is null)" @onclick="AddBuiltFilterAsync"><KhIcon Name="plus" /> @T["Ui.Radar.Add"]</button>
|
||||
</Footer>
|
||||
</KhDialog>
|
||||
|
||||
<KhDialog Open="_savedOpen" Title="@T["Ui.Radar.Saved"]" Icon="star" Size="sm" OnClose="() => _savedOpen = false">
|
||||
<ChildContent>
|
||||
@if (_saved.Count == 0)
|
||||
{
|
||||
<p class="muted">@T["Ui.Radar.NoSaved"]</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<ul class="kh-savedlist">
|
||||
@foreach (var saved in _saved)
|
||||
{
|
||||
<li>
|
||||
<button type="button" class="kh-link" @onclick="() => ApplySavedAsync(saved)">@saved.Name</button>
|
||||
<KhIconButton Icon="trash" Text="@T.Format("Ui.Radar.DeleteSaved", saved.Name)" Danger="true" OnClick="() => DeleteSavedAsync(saved)" />
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
<div class="form plain">
|
||||
<KhTextBox Label="@T["Ui.Radar.SaveAs"]" Span="12" @bind-Value="_saveName" MaxLength="60" Placeholder="@T["Ui.Radar.SaveAsPlaceholder"]" />
|
||||
</div>
|
||||
</ChildContent>
|
||||
<Footer>
|
||||
<button type="button" class="btn" @onclick="() => _savedOpen = false">@T["Ui.Grid.Close"]</button>
|
||||
<button type="button" class="btn primary" @onclick="SaveCurrentAsync"><KhIcon Name="star" /> @T["Ui.Radar.Save"]</button>
|
||||
</Footer>
|
||||
</KhDialog>
|
||||
|
||||
@code {
|
||||
private readonly FilterBuilder _builder = new();
|
||||
private KhGrid<TItem>? _grid;
|
||||
private ElementReference _searchBox;
|
||||
private List<ListFilter> _filters = [];
|
||||
private List<ListSort> _sort = [];
|
||||
private List<KhSavedFilter> _saved = [];
|
||||
private string _search = string.Empty;
|
||||
private string? _appliedSearch;
|
||||
private string? _saveName;
|
||||
private bool _builderOpen;
|
||||
private bool _savedOpen;
|
||||
private bool _exportOpen;
|
||||
private bool _initialized;
|
||||
private CancellationTokenSource? _debounce;
|
||||
|
||||
/// <summary>The id of the radar: the key of its saved filters and column layout.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public string Id { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The columns.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public IReadOnlyList<KhColumn<TItem>> Columns { get; set; } = [];
|
||||
|
||||
/// <summary>Where the rows come from.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public ListSource<TItem> Source { get; set; } = default!;
|
||||
|
||||
/// <summary>The key of a row.</summary>
|
||||
[Parameter]
|
||||
public Func<TItem, object>? KeyOf { get; set; }
|
||||
|
||||
/// <summary>Shows the selection boxes.</summary>
|
||||
[Parameter]
|
||||
public bool Selectable { get; set; } = true;
|
||||
|
||||
/// <summary>Called when the selection changes.</summary>
|
||||
[Parameter]
|
||||
public EventCallback<IReadOnlyCollection<object>> SelectionChanged { get; set; }
|
||||
|
||||
/// <summary>Called with the row on Enter or double click.</summary>
|
||||
[Parameter]
|
||||
public EventCallback<TItem> OnOpen { get; set; }
|
||||
|
||||
/// <summary>Called when the current row changes.</summary>
|
||||
[Parameter]
|
||||
public EventCallback<TItem> OnCurrent { get; set; }
|
||||
|
||||
/// <summary>The drop-down filters of the bar.</summary>
|
||||
[Parameter]
|
||||
public IReadOnlyList<KhQuickFilter> QuickFilters { get; set; } = [];
|
||||
|
||||
/// <summary>The filters when the radar opens.</summary>
|
||||
[Parameter]
|
||||
public IReadOnlyList<ListFilter>? InitialFilters { get; set; }
|
||||
|
||||
/// <summary>The search text when the radar opens (the text typed in a hotlink).</summary>
|
||||
[Parameter]
|
||||
public string? InitialSearch { get; set; }
|
||||
|
||||
/// <summary>The ordering when the radar opens.</summary>
|
||||
[Parameter]
|
||||
public IReadOnlyList<ListSort>? InitialSort { get; set; }
|
||||
|
||||
/// <summary>Extra classes of a row.</summary>
|
||||
[Parameter]
|
||||
public Func<TItem, string?>? RowClass { get; set; }
|
||||
|
||||
/// <summary>The commands of the row menu.</summary>
|
||||
[Parameter]
|
||||
public Func<TItem, IEnumerable<ToolbarItem>>? RowMenu { get; set; }
|
||||
|
||||
/// <summary>The commands above the radar (the page toolbar).</summary>
|
||||
[Parameter]
|
||||
public RenderFragment? Toolbar { get; set; }
|
||||
|
||||
/// <summary>Extra content of the bar under the grid.</summary>
|
||||
[Parameter]
|
||||
public RenderFragment? Summary { get; set; }
|
||||
|
||||
/// <summary>Shows the keyboard hints.</summary>
|
||||
[Parameter]
|
||||
public bool ShowHints { get; set; } = true;
|
||||
|
||||
/// <summary>The radar picks a row for a field (in a dialog): Enter means "choose".</summary>
|
||||
[Parameter]
|
||||
public bool Picking { get; set; }
|
||||
|
||||
/// <summary>Smaller spacing, for dialogs.</summary>
|
||||
[Parameter]
|
||||
public bool Compact { get; set; }
|
||||
|
||||
/// <summary>The height of the rows area, as CSS.</summary>
|
||||
[Parameter]
|
||||
public string? Height { get; set; }
|
||||
|
||||
/// <summary>The placeholder of the search box.</summary>
|
||||
[Parameter]
|
||||
public string? SearchPlaceholder { get; set; }
|
||||
|
||||
/// <summary>The name of the exported files.</summary>
|
||||
[Parameter]
|
||||
public string? ExportName { get; set; }
|
||||
|
||||
/// <summary>The label of the grid.</summary>
|
||||
[Parameter]
|
||||
public string? Label { get; set; }
|
||||
|
||||
/// <summary>Extra classes.</summary>
|
||||
[Parameter]
|
||||
public string? Class { get; set; }
|
||||
|
||||
/// <summary>The cascaded tab of the page, so that F9 only acts on the visible page.</summary>
|
||||
[CascadingParameter]
|
||||
public KhTab? Tab { get; set; }
|
||||
|
||||
/// <summary>The grid.</summary>
|
||||
public KhGrid<TItem>? Grid => _grid;
|
||||
|
||||
/// <summary>The current request: search, filters, ordering.</summary>
|
||||
public ListQuery CurrentQuery => new() { Search = _appliedSearch, Filters = _filters, Sort = _sort };
|
||||
|
||||
private IEnumerable<KhColumn<TItem>> Filterable => Columns.Where(c => c.Sortable);
|
||||
|
||||
private bool IsSaved => _saved.Any(s => string.Equals(s.Search ?? string.Empty, _appliedSearch ?? string.Empty, StringComparison.OrdinalIgnoreCase)
|
||||
&& s.Filters.SequenceEqual(_filters));
|
||||
|
||||
private ListFilter? BuiltFilter => _builder.Build(T.Culture);
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
_search = InitialSearch ?? string.Empty;
|
||||
_appliedSearch = string.IsNullOrWhiteSpace(_search) ? null : _search;
|
||||
_filters = [.. InitialFilters ?? []];
|
||||
_sort = [.. InitialSort ?? []];
|
||||
Keys.PagePressed += OnShortcutAsync;
|
||||
_saved = [.. KhSavedFilter.ParseAll(await Session.ReadSettingAsync(KhSavedFilter.KeyOf(Id)))];
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||
{
|
||||
if (firstRender)
|
||||
{
|
||||
_initialized = true;
|
||||
await JS.InvokeVoidAsync("khaemhat.preventKeys", _searchBox);
|
||||
if (Picking || Tab is null || Tab.IsActive)
|
||||
{
|
||||
await _searchBox.FocusAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Moves the focus to the search box.</summary>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task FocusSearchAsync() => await _searchBox.FocusAsync();
|
||||
|
||||
/// <summary>Reads the rows again.</summary>
|
||||
/// <returns>A task.</returns>
|
||||
public Task ReloadAsync() => _grid?.ReloadAsync() ?? Task.CompletedTask;
|
||||
|
||||
private async Task OnShortcutAsync(string command)
|
||||
{
|
||||
if (!_initialized || command != KeyboardShortcuts.Commands.Radar || (Tab is not null && !Tab.IsActive))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await InvokeAsync(FocusSearchAsync);
|
||||
}
|
||||
|
||||
private void OnSearchInput(ChangeEventArgs e)
|
||||
{
|
||||
_search = e.Value as string ?? string.Empty;
|
||||
_debounce?.Cancel();
|
||||
_debounce?.Dispose();
|
||||
_debounce = new CancellationTokenSource();
|
||||
_ = ApplySearchLaterAsync(_debounce.Token);
|
||||
}
|
||||
|
||||
// The search waits for a pause in typing, so each key does not ask the source again.
|
||||
private async Task ApplySearchLaterAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(250, cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await InvokeAsync(() =>
|
||||
{
|
||||
_appliedSearch = string.IsNullOrWhiteSpace(_search) ? null : _search.Trim();
|
||||
StateHasChanged();
|
||||
});
|
||||
}
|
||||
|
||||
private async Task OnSearchKeyAsync(KeyboardEventArgs e)
|
||||
{
|
||||
if (e.Key is "ArrowDown" or "Enter" && _grid is not null)
|
||||
{
|
||||
_debounce?.Cancel();
|
||||
_appliedSearch = string.IsNullOrWhiteSpace(_search) ? null : _search.Trim();
|
||||
StateHasChanged();
|
||||
await Task.Yield();
|
||||
await _grid.FocusAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private string QuickId(KhQuickFilter quick) => "kh-qf-" + Id + "-" + quick.Field;
|
||||
|
||||
private string QuickValue(KhQuickFilter quick) =>
|
||||
_filters.FirstOrDefault(f => f.Field == quick.Field && f.Operator == ListFilterOperator.Equals && f.Values.Count == 1)?.Values[0] ?? string.Empty;
|
||||
|
||||
private bool IsQuick(ListFilter filter) =>
|
||||
filter.Operator == ListFilterOperator.Equals && QuickFilters.Any(q => q.Field == filter.Field && q.Options.Any(o => o.Value == filter.Values.FirstOrDefault()));
|
||||
|
||||
private Task SetQuickAsync(KhQuickFilter quick, string? value)
|
||||
{
|
||||
_filters = [.. _filters.Where(f => !(f.Field == quick.Field && f.Operator == ListFilterOperator.Equals))];
|
||||
if (!string.IsNullOrEmpty(value))
|
||||
{
|
||||
_filters.Add(ListFilter.Of(quick.Field, ListFilterOperator.Equals, value));
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private Task RemoveFilterAsync(ListFilter filter)
|
||||
{
|
||||
_filters = [.. _filters.Where(f => !f.Equals(filter))];
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private string ChipText(ListFilter filter)
|
||||
{
|
||||
var column = Columns.FirstOrDefault(c => c.Id == filter.Field);
|
||||
var title = column?.Title ?? filter.Field;
|
||||
var values = string.Join(", ", filter.Values.Select(v => DisplayValue(column, v)));
|
||||
return filter.Operator switch
|
||||
{
|
||||
ListFilterOperator.IsEmpty or ListFilterOperator.IsNotEmpty => title + " " + T["Ui.Radar.Op." + filter.Operator],
|
||||
ListFilterOperator.Between when filter.Values.Count == 2 =>
|
||||
T.Format("Ui.Radar.ChipBetween", title, DisplayValue(column, filter.Values[0]), DisplayValue(column, filter.Values[1])),
|
||||
ListFilterOperator.In or ListFilterOperator.Equals => title + ": " + values,
|
||||
_ => title + " " + T["Ui.Radar.Op." + filter.Operator] + " " + values,
|
||||
};
|
||||
}
|
||||
|
||||
private string DisplayValue(KhColumn<TItem>? column, string value)
|
||||
{
|
||||
if (column?.Choices?.FirstOrDefault(c => c.Value == value) is { } choice)
|
||||
{
|
||||
return choice.Text;
|
||||
}
|
||||
|
||||
var culture = System.Globalization.CultureInfo.InvariantCulture;
|
||||
return column?.Kind switch
|
||||
{
|
||||
KhColumnKind.Date when DateOnly.TryParseExact(value, "yyyy-MM-dd", culture, System.Globalization.DateTimeStyles.None, out var d) => T.Date(d),
|
||||
KhColumnKind.Money when decimal.TryParse(value, System.Globalization.NumberStyles.Number, culture, out var m) => T.Money(m),
|
||||
KhColumnKind.Number when decimal.TryParse(value, System.Globalization.NumberStyles.Number, culture, out var n) => T.Number(n, column.Decimals),
|
||||
KhColumnKind.Bool => T[value == "true" ? "Ui.Grid.Yes" : "Ui.Grid.No"],
|
||||
_ => value,
|
||||
};
|
||||
}
|
||||
|
||||
private void OpenBuilder()
|
||||
{
|
||||
_builder.Reset(Filterable.FirstOrDefault());
|
||||
_builder.Operator = _builder.Column is null ? ListFilterOperator.Equals : OperatorsOf(_builder.Column)[0];
|
||||
_builderOpen = true;
|
||||
}
|
||||
|
||||
private void PickColumn(string? id)
|
||||
{
|
||||
_builder.Reset(Columns.FirstOrDefault(c => c.Id == id));
|
||||
_builder.Operator = _builder.Column is null ? ListFilterOperator.Equals : OperatorsOf(_builder.Column)[0];
|
||||
}
|
||||
|
||||
private void SetOperator(string? value)
|
||||
{
|
||||
if (Enum.TryParse<ListFilterOperator>(value, out var op))
|
||||
{
|
||||
_builder.Operator = op;
|
||||
}
|
||||
}
|
||||
|
||||
private void ToggleChoice(string value, bool on)
|
||||
{
|
||||
if (on)
|
||||
{
|
||||
_builder.Choices.Add(value);
|
||||
}
|
||||
else
|
||||
{
|
||||
_builder.Choices.Remove(value);
|
||||
}
|
||||
}
|
||||
|
||||
private static int NumberDecimals(KhColumn<TItem> column) => column.Kind == KhColumnKind.Money ? 2 : column.Decimals;
|
||||
|
||||
private static IReadOnlyList<ListFilterOperator> OperatorsOf(KhColumn<TItem> column) => column switch
|
||||
{
|
||||
{ Choices: not null } => [ListFilterOperator.In, ListFilterOperator.IsEmpty, ListFilterOperator.IsNotEmpty],
|
||||
{ Kind: KhColumnKind.Bool } => [ListFilterOperator.Equals],
|
||||
{ Kind: KhColumnKind.Number or KhColumnKind.Money or KhColumnKind.Date } =>
|
||||
[
|
||||
ListFilterOperator.Equals, ListFilterOperator.GreaterThan, ListFilterOperator.GreaterOrEqual, ListFilterOperator.LessThan,
|
||||
ListFilterOperator.LessOrEqual, ListFilterOperator.Between, ListFilterOperator.NotEquals, ListFilterOperator.IsEmpty, ListFilterOperator.IsNotEmpty,
|
||||
],
|
||||
_ => [ListFilterOperator.Contains, ListFilterOperator.StartsWith, ListFilterOperator.Equals, ListFilterOperator.NotEquals, ListFilterOperator.IsEmpty, ListFilterOperator.IsNotEmpty],
|
||||
};
|
||||
|
||||
private Task AddBuiltFilterAsync()
|
||||
{
|
||||
if (BuiltFilter is { } filter)
|
||||
{
|
||||
_filters = [.. _filters.Where(f => !f.Equals(filter)), filter];
|
||||
_builderOpen = false;
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private Task ApplySavedAsync(KhSavedFilter saved)
|
||||
{
|
||||
_search = saved.Search ?? string.Empty;
|
||||
_appliedSearch = string.IsNullOrWhiteSpace(_search) ? null : _search;
|
||||
_filters = [.. saved.Filters];
|
||||
_sort = [.. saved.Sort];
|
||||
_savedOpen = false;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task SaveCurrentAsync()
|
||||
{
|
||||
var name = _saveName?.Trim();
|
||||
if (string.IsNullOrEmpty(name))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_saved = [.. _saved.Where(s => !string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase)), new KhSavedFilter(name, _appliedSearch, [.. _filters], [.. _sort])];
|
||||
_saved = [.. _saved.TakeLast(KhSavedFilter.MaxCount)];
|
||||
await Session.SaveSettingAsync(KhSavedFilter.KeyOf(Id), KhSavedFilter.ToJson(_saved));
|
||||
_saveName = null;
|
||||
}
|
||||
|
||||
private async Task DeleteSavedAsync(KhSavedFilter saved)
|
||||
{
|
||||
_saved.Remove(saved);
|
||||
await Session.SaveSettingAsync(KhSavedFilter.KeyOf(Id), _saved.Count == 0 ? null : KhSavedFilter.ToJson(_saved));
|
||||
}
|
||||
|
||||
private async Task ExportAsync(bool xlsx)
|
||||
{
|
||||
_exportOpen = false;
|
||||
if (_grid is not null)
|
||||
{
|
||||
await _grid.ExportAsync(xlsx);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
Keys.PagePressed -= OnShortcutAsync;
|
||||
_debounce?.Cancel();
|
||||
_debounce?.Dispose();
|
||||
}
|
||||
|
||||
// What the user puts together in the "Aggiungi filtro" window.
|
||||
private sealed class FilterBuilder
|
||||
{
|
||||
public KhColumn<TItem>? Column { get; private set; }
|
||||
|
||||
public ListFilterOperator Operator { get; set; }
|
||||
|
||||
public string? Text { get; set; }
|
||||
|
||||
public decimal? Number { get; set; }
|
||||
|
||||
public decimal? NumberTo { get; set; }
|
||||
|
||||
public DateOnly? Date { get; set; }
|
||||
|
||||
public DateOnly? DateTo { get; set; }
|
||||
|
||||
public HashSet<string> Choices { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
public void Reset(KhColumn<TItem>? column)
|
||||
{
|
||||
Column = column;
|
||||
Text = null;
|
||||
Number = NumberTo = null;
|
||||
Date = DateTo = null;
|
||||
Choices.Clear();
|
||||
}
|
||||
|
||||
public ListFilter? Build(System.Globalization.CultureInfo culture)
|
||||
{
|
||||
if (Column is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (Operator is ListFilterOperator.IsEmpty or ListFilterOperator.IsNotEmpty)
|
||||
{
|
||||
return ListFilter.Of(Column.Id, Operator);
|
||||
}
|
||||
|
||||
string[]? values = Column switch
|
||||
{
|
||||
{ Choices: not null } => Choices.Count == 0 ? null : [.. Choices],
|
||||
{ Kind: KhColumnKind.Date } => Operator == ListFilterOperator.Between
|
||||
? Date is { } from && DateTo is { } to ? [ListFilter.Text(from), ListFilter.Text(to)] : null
|
||||
: Date is { } day ? [ListFilter.Text(day)] : null,
|
||||
{ IsNumeric: true } => Operator == ListFilterOperator.Between
|
||||
? Number is { } low && NumberTo is { } high ? [ListFilter.Text(low), ListFilter.Text(high)] : null
|
||||
: Number is { } value ? [ListFilter.Text(value)] : null,
|
||||
_ => string.IsNullOrWhiteSpace(Text) ? null : [Text.Trim()],
|
||||
};
|
||||
return values is null ? null : new ListFilter(Column.Id, Operator, values);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
@typeparam TItem
|
||||
|
||||
@* The radar in a window, to pick a row for a field (SPEC §10.7 hotlink F4, mockup 023): the search starts from the
|
||||
text typed in the field, Enter or double click picks the current row, "Nuovo" creates one on the fly. *@
|
||||
<KhDialog Open="Open" Title="@Title" Icon="search" Size="lg" OnClose="CloseAsync">
|
||||
<ChildContent>
|
||||
@if (Open)
|
||||
{
|
||||
<KhRadar TItem="TItem" @ref="_radar" Id="@Id" Columns="Columns" Source="Source" KeyOf="KeyOf" Selectable="false" Picking="true" Compact="true"
|
||||
InitialSearch="@InitialSearch" InitialFilters="InitialFilters" QuickFilters="QuickFilters" Height="min(52vh, 460px)"
|
||||
OnOpen="PickAsync" OnCurrent="item => _current = item" ShowHints="false" Label="@Title">
|
||||
</KhRadar>
|
||||
}
|
||||
</ChildContent>
|
||||
<Footer>
|
||||
@if (OnCreate.HasDelegate)
|
||||
{
|
||||
<button type="button" class="btn" @onclick="CreateAsync"><KhIcon Name="plus" /> @T["Ui.Radar.CreateNew"]</button>
|
||||
}
|
||||
<span class="kbdhint kh-grow"><kbd>@T["Ui.Radar.KeyEnter"]</kbd> @T["Ui.Radar.HintPick"] <kbd>@T["Ui.Radar.KeyEscape"]</kbd> @T["Ui.Radar.HintClose"]</span>
|
||||
<button type="button" class="btn" @onclick="CloseAsync">@T["Ui.Grid.Close"]</button>
|
||||
<button type="button" class="btn primary" disabled="@(_current is null)" @onclick="() => PickAsync(_current!)"><KhIcon Name="check" /> @T["Ui.Radar.Pick"]</button>
|
||||
</Footer>
|
||||
</KhDialog>
|
||||
|
||||
@code {
|
||||
private KhRadar<TItem>? _radar;
|
||||
private TItem? _current;
|
||||
|
||||
/// <summary>Whether the window is open.</summary>
|
||||
[Parameter]
|
||||
public bool Open { get; set; }
|
||||
|
||||
/// <summary>Called when the window closes without a choice.</summary>
|
||||
[Parameter]
|
||||
public EventCallback OnClose { get; set; }
|
||||
|
||||
/// <summary>Called with the row picked; the window closes.</summary>
|
||||
[Parameter]
|
||||
public EventCallback<TItem> OnPick { get; set; }
|
||||
|
||||
/// <summary>Called with the search text to create a row on the fly; none hides the button.</summary>
|
||||
[Parameter]
|
||||
public EventCallback<string> OnCreate { get; set; }
|
||||
|
||||
/// <summary>The title (Ricerca articolo).</summary>
|
||||
[Parameter]
|
||||
public string? Title { get; set; }
|
||||
|
||||
/// <summary>The id of the radar, for saved filters and layout.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public string Id { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The columns.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public IReadOnlyList<KhColumn<TItem>> Columns { get; set; } = [];
|
||||
|
||||
/// <summary>Where the rows come from.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public ListSource<TItem> Source { get; set; } = default!;
|
||||
|
||||
/// <summary>The key of a row.</summary>
|
||||
[Parameter]
|
||||
public Func<TItem, object>? KeyOf { get; set; }
|
||||
|
||||
/// <summary>The text the search starts from.</summary>
|
||||
[Parameter]
|
||||
public string? InitialSearch { get; set; }
|
||||
|
||||
/// <summary>The filters the search starts from (only available items...).</summary>
|
||||
[Parameter]
|
||||
public IReadOnlyList<ListFilter>? InitialFilters { get; set; }
|
||||
|
||||
/// <summary>The drop-down filters.</summary>
|
||||
[Parameter]
|
||||
public IReadOnlyList<KhQuickFilter> QuickFilters { get; set; } = [];
|
||||
|
||||
private async Task PickAsync(TItem item)
|
||||
{
|
||||
if (item is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_current = default;
|
||||
await OnPick.InvokeAsync(item);
|
||||
}
|
||||
|
||||
private async Task CloseAsync()
|
||||
{
|
||||
_current = default;
|
||||
await OnClose.InvokeAsync();
|
||||
}
|
||||
|
||||
private async Task CreateAsync()
|
||||
{
|
||||
var text = _radar?.CurrentQuery.Search ?? InitialSearch ?? string.Empty;
|
||||
_current = default;
|
||||
await OnCreate.InvokeAsync(text);
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,9 @@
|
||||
@using Khaemhat.Web.Security
|
||||
@using Khaemhat.Application.Localization
|
||||
@using Khaemhat.Application.Preferences
|
||||
@using Khaemhat.Application.Querying
|
||||
@using Khaemhat.Application.Files
|
||||
@using Khaemhat.Infrastructure.Files
|
||||
@using Khaemhat.Web.Shell
|
||||
@using Khaemhat.Web.Components.Shell
|
||||
@using Khaemhat.Web.Components.Ui
|
||||
|
||||
@@ -202,7 +202,8 @@
|
||||
"Panels": "Pannelli",
|
||||
"Navigation": "Navigazione",
|
||||
"Windows": "Finestre",
|
||||
"Toolbar": "Toolbar e intestazione"
|
||||
"Toolbar": "Toolbar e intestazione",
|
||||
"Grids": "Griglie e radar"
|
||||
},
|
||||
"Fields": {
|
||||
"Document": "Documento",
|
||||
@@ -316,6 +317,48 @@
|
||||
"Quantity": "Quantità",
|
||||
"Price": "Prezzo",
|
||||
"Amount": "Importo"
|
||||
},
|
||||
"Grids": {
|
||||
"Radar": "Radar di 100.000 clienti finti",
|
||||
"RadarIntro": "Righe lette a pagine mentre scorri. Prova la ricerca, i filtri, l'ordinamento con Maiusc, il menu della riga, le colonne e l'esportazione.",
|
||||
"Pager": "Griglia a pagine con modifica in linea",
|
||||
"PagerIntro": "Doppio clic o F2 sul fido per modificarlo; Invio salva, Esc annulla.",
|
||||
"Code": "Codice",
|
||||
"Name": "Ragione sociale",
|
||||
"City": "Città",
|
||||
"Province": "Prov.",
|
||||
"Agent": "Agente",
|
||||
"Kind": "Tipo",
|
||||
"Revenue": "Fatturato",
|
||||
"Overdue": "Scaduto",
|
||||
"Credit": "Fido",
|
||||
"Since": "Cliente dal",
|
||||
"State": "Stato",
|
||||
"Vip": "Preferito",
|
||||
"KindCompany": "Azienda",
|
||||
"KindPerson": "Privato",
|
||||
"KindPublic": "Pubblica amministrazione",
|
||||
"StateActive": "Attivo",
|
||||
"StateBlocked": "Bloccato",
|
||||
"StateDisabled": "Disabilitato",
|
||||
"All": "Tutti",
|
||||
"NoAgent": "Senza agente",
|
||||
"Opened": "Qui si apre la scheda di {0}",
|
||||
"CreditInvalid": "Il fido non può essere negativo.",
|
||||
"Visible": "fatturato filtrato {0}",
|
||||
"Lines": "Righe del documento",
|
||||
"Item": "Articolo",
|
||||
"Description": "Descrizione",
|
||||
"Unit": "UM",
|
||||
"Quantity": "Quantità",
|
||||
"Price": "Prezzo",
|
||||
"Discount": "Sconto %",
|
||||
"Amount": "Importo",
|
||||
"ItemRadar": "Ricerca articolo",
|
||||
"ItemCreated": "Qui si crea l'articolo {0}",
|
||||
"Duplicate": "Duplica",
|
||||
"OpenCard": "Apri la scheda",
|
||||
"Block": "Blocca"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,6 +62,88 @@
|
||||
"Links": "Collegamenti",
|
||||
"History": "Storico"
|
||||
}
|
||||
},
|
||||
"Grid": {
|
||||
"Yes": "Sì",
|
||||
"No": "No",
|
||||
"Count": "{0} righe",
|
||||
"Selected": "{0} selezionate",
|
||||
"Total": "Totale",
|
||||
"Empty": "Nessuna riga.",
|
||||
"SelectAll": "Seleziona tutte le righe caricate",
|
||||
"SelectRow": "Seleziona la riga",
|
||||
"RowMenu": "Azioni della riga",
|
||||
"SortHint": "Ordina (Maiusc per aggiungere un secondo ordinamento)",
|
||||
"Columns": "Colonne",
|
||||
"ColumnsHint": "Scegli le colonne da mostrare e il loro ordine: la scelta resta per te su questa lista.",
|
||||
"Up": "Sposta su",
|
||||
"Down": "Sposta giù",
|
||||
"Reset": "Ripristina",
|
||||
"Close": "Chiudi",
|
||||
"Export": "Esporta",
|
||||
"ExportCsv": "CSV per Excel (punto e virgola)",
|
||||
"ExportXlsx": "Excel (XLSX)",
|
||||
"Exported": "Esportate {0} righe.",
|
||||
"ExportLimit": "Esportate le prime {0} righe: restringi i filtri per avere le altre.",
|
||||
"Pages": "Pagine",
|
||||
"PreviousPage": "Pagina precedente",
|
||||
"NextPage": "Pagina successiva"
|
||||
},
|
||||
"Radar": {
|
||||
"Search": "Cerca",
|
||||
"SearchPlaceholder": "Cerca per codice, nome...",
|
||||
"HintRadar": "radar",
|
||||
"HintOpen": "apri",
|
||||
"HintPick": "scegli",
|
||||
"HintSelect": "seleziona",
|
||||
"HintClose": "chiudi",
|
||||
"KeyEnter": "Invio",
|
||||
"KeySpace": "Spazio",
|
||||
"KeyEscape": "Esc",
|
||||
"AddFilter": "Filtro",
|
||||
"Field": "Campo",
|
||||
"Operator": "Condizione",
|
||||
"Value": "Valore",
|
||||
"ValueTo": "Fino a",
|
||||
"Values": "Valori",
|
||||
"Add": "Aggiungi",
|
||||
"Empty": "Nessun risultato con questa ricerca e questi filtri.",
|
||||
"Saved": "Filtri salvati",
|
||||
"NoSaved": "Nessun filtro salvato: imposta ricerca e filtri, poi dai un nome qui sotto.",
|
||||
"SaveAs": "Salva i filtri attuali come",
|
||||
"SaveAsPlaceholder": "Es. Clienti con scaduto",
|
||||
"Save": "Salva",
|
||||
"DeleteSaved": "Elimina il filtro {0}",
|
||||
"ChipBetween": "{0} da {1} a {2}",
|
||||
"Pick": "Scegli",
|
||||
"CreateNew": "Nuovo",
|
||||
"Op": {
|
||||
"Equals": "uguale a",
|
||||
"NotEquals": "diverso da",
|
||||
"Contains": "contiene",
|
||||
"StartsWith": "inizia con",
|
||||
"GreaterThan": "maggiore di",
|
||||
"GreaterOrEqual": "da",
|
||||
"LessThan": "minore di",
|
||||
"LessOrEqual": "fino a",
|
||||
"Between": "tra",
|
||||
"In": "è uno di",
|
||||
"IsEmpty": "vuoto",
|
||||
"IsNotEmpty": "non vuoto"
|
||||
}
|
||||
},
|
||||
"Lines": {
|
||||
"Actions": "Azioni",
|
||||
"Remove": "Togli la riga (Ctrl+Canc)",
|
||||
"RemoveLine": "Togli la riga {0}",
|
||||
"Cell": "{0}, riga {1}",
|
||||
"Add": "Nuova riga",
|
||||
"AddDescriptive": "Riga descrittiva",
|
||||
"KeyAdd": "Ctrl+↓",
|
||||
"KeyRemove": "Ctrl+Canc",
|
||||
"HintNext": "cella successiva",
|
||||
"HintLookup": "cerca",
|
||||
"HintRemove": "togli la riga"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
using Khaemhat.Application.Querying;
|
||||
|
||||
namespace Khaemhat.Web.Ui;
|
||||
|
||||
/// <summary>A customer of the component catalog: fake data for the development page only.</summary>
|
||||
@@ -20,10 +22,73 @@ public sealed class SampleLine
|
||||
/// <summary>The unit price.</summary>
|
||||
public decimal? Price { get; set; }
|
||||
|
||||
/// <summary>The unit of measure.</summary>
|
||||
public string? Unit { get; set; }
|
||||
|
||||
/// <summary>The discount in percent.</summary>
|
||||
public decimal? Discount { get; set; }
|
||||
|
||||
/// <summary>Whether the line is only a text.</summary>
|
||||
public bool Descriptive { get; set; }
|
||||
|
||||
/// <summary>The amount.</summary>
|
||||
public decimal Amount => Math.Round((Quantity ?? 0) * (Price ?? 0), 2, MidpointRounding.AwayFromZero);
|
||||
public decimal Amount => Descriptive ? 0 : Math.Round((Quantity ?? 0) * (Price ?? 0) * (1 - ((Discount ?? 0) / 100)), 2, MidpointRounding.AwayFromZero);
|
||||
|
||||
/// <summary>Whether nothing was typed yet.</summary>
|
||||
public bool IsEmpty => string.IsNullOrEmpty(Code) && string.IsNullOrEmpty(Description) && Quantity is null && Price is null;
|
||||
}
|
||||
|
||||
/// <summary>A customer of the radar of the component catalog: fake data.</summary>
|
||||
public sealed class SampleCustomer
|
||||
{
|
||||
/// <summary>The id.</summary>
|
||||
public long Id { get; init; }
|
||||
|
||||
/// <summary>The code.</summary>
|
||||
public string Code { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>The name.</summary>
|
||||
public string Name { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>The city.</summary>
|
||||
public string City { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>The province.</summary>
|
||||
public string Province { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>The agent, if any.</summary>
|
||||
public string? Agent { get; init; }
|
||||
|
||||
/// <summary>The kind: company, person, public.</summary>
|
||||
public string Kind { get; init; } = "company";
|
||||
|
||||
/// <summary>The revenue of the year.</summary>
|
||||
public decimal Revenue { get; init; }
|
||||
|
||||
/// <summary>The amount overdue.</summary>
|
||||
public decimal Overdue { get; init; }
|
||||
|
||||
/// <summary>The credit limit (editable in the catalog).</summary>
|
||||
public decimal Credit { get; set; }
|
||||
|
||||
/// <summary>Customer since.</summary>
|
||||
public DateOnly Since { get; init; }
|
||||
|
||||
/// <summary>The state: active, blocked, disabled.</summary>
|
||||
public string State { get; init; } = "active";
|
||||
|
||||
/// <summary>Whether marked as preferred.</summary>
|
||||
public bool Vip { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>An item for the lookup of the document lines in the catalog: fake data.</summary>
|
||||
/// <param name="Code">The code.</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="Unit">The unit.</param>
|
||||
/// <param name="Price">The price.</param>
|
||||
/// <param name="Stock">The stock.</param>
|
||||
public sealed record SampleItem(string Code, string Description, string Unit, decimal Price, decimal Stock);
|
||||
|
||||
/// <summary>The sample document of the component catalog.</summary>
|
||||
public sealed class SampleDocument
|
||||
{
|
||||
@@ -82,15 +147,127 @@ public static class CatalogSamples
|
||||
return Task.FromResult(hits);
|
||||
}
|
||||
|
||||
/// <summary>The fields of the customer radar.</summary>
|
||||
public static ListFields<SampleCustomer> CustomerFields { get; } = new ListFields<SampleCustomer>()
|
||||
.Add("code", c => c.Code, searchable: true)
|
||||
.Add("name", c => c.Name, searchable: true)
|
||||
.Add("city", c => c.City, searchable: true)
|
||||
.Add("province", c => c.Province)
|
||||
.Add("agent", c => c.Agent)
|
||||
.Add("kind", c => c.Kind)
|
||||
.Add("revenue", c => c.Revenue, total: true)
|
||||
.Add("overdue", c => c.Overdue, total: true)
|
||||
.Add("credit", c => c.Credit, total: true)
|
||||
.Add("since", c => c.Since)
|
||||
.Add("state", c => c.State)
|
||||
.Add("vip", c => c.Vip)
|
||||
.OrderByDefault(new ListSort("code"));
|
||||
|
||||
/// <summary>The fields of the item lookup.</summary>
|
||||
public static ListFields<SampleItem> ItemFields { get; } = new ListFields<SampleItem>()
|
||||
.Add("code", i => i.Code, searchable: true)
|
||||
.Add("description", i => i.Description, searchable: true)
|
||||
.Add("unit", i => i.Unit)
|
||||
.Add("price", i => i.Price)
|
||||
.Add("stock", i => i.Stock)
|
||||
.OrderByDefault(new ListSort("code"));
|
||||
|
||||
private static readonly Lazy<InMemoryListSource<SampleCustomer>> CustomerSource = new(() => new(MakeCustomers(100_000), CustomerFields));
|
||||
private static readonly Lazy<InMemoryListSource<SampleItem>> ItemSource = new(() => new(MakeItems(), ItemFields));
|
||||
|
||||
/// <summary>The 100,000 customers of the radar.</summary>
|
||||
/// <param name="query">The request.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public static Task<ListPage<SampleCustomer>> CustomersAsync(ListQuery query, CancellationToken cancellationToken) =>
|
||||
CustomerSource.Value.QueryAsync(query, cancellationToken);
|
||||
|
||||
/// <summary>The items of the lookup.</summary>
|
||||
/// <param name="query">The request.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public static Task<ListPage<SampleItem>> ItemsAsync(ListQuery query, CancellationToken cancellationToken) =>
|
||||
ItemSource.Value.QueryAsync(query, cancellationToken);
|
||||
|
||||
/// <summary>Finds an item by its exact code.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <returns>The item, or <see langword="null"/>.</returns>
|
||||
public static SampleItem? ItemByCode(string? code) =>
|
||||
code is null ? null : ItemSource.Value.All(new ListQuery()).FirstOrDefault(i => string.Equals(i.Code, code.Trim(), StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>Makes fake customers, always the same ones.</summary>
|
||||
/// <param name="count">How many.</param>
|
||||
/// <returns>The customers.</returns>
|
||||
public static IReadOnlyList<SampleCustomer> MakeCustomers(int count)
|
||||
{
|
||||
string[] first = ["Esempio", "Prova", "Demo", "Fittizia", "Campione", "Modello", "Simulata", "Test"];
|
||||
string[] second = ["Impianti", "Costruzioni", "Commerciale", "Servizi", "Forniture", "Meccanica", "Elettrica", "Logistica", "Studio", "Officine"];
|
||||
string[] forms = ["Srl", "Spa", "Snc", "Sas", "Srls"];
|
||||
(string City, string Province)[] cities = [("Torino", "TO"), ("Alba", "CN"), ("Cuneo", "CN"), ("Asti", "AT"), ("Milano", "MI"), ("Bra", "CN"), ("Novara", "NO"), ("Genova", "GE"), ("Alessandria", "AL"), ("Biella", "BI")];
|
||||
string?[] agents = ["M. Verdi", "L. Neri", "A. Bianchi", null];
|
||||
var random = new Random(20261111);
|
||||
var customers = new List<SampleCustomer>(count);
|
||||
for (var i = 1; i <= count; i++)
|
||||
{
|
||||
var (city, province) = cities[random.Next(cities.Length)];
|
||||
var kind = random.Next(20) switch { 0 => "public", < 4 => "person", _ => "company" };
|
||||
var name = kind == "person"
|
||||
? "Persona di prova " + random.Next(1, 99_999).ToString(System.Globalization.CultureInfo.InvariantCulture)
|
||||
: first[random.Next(first.Length)] + " " + second[random.Next(second.Length)] + " " + forms[random.Next(forms.Length)];
|
||||
var revenue = Math.Round((decimal)(random.NextDouble() * random.NextDouble()) * 250_000m, 2);
|
||||
customers.Add(new SampleCustomer
|
||||
{
|
||||
Id = i,
|
||||
Code = "C" + i.ToString("D6", System.Globalization.CultureInfo.InvariantCulture),
|
||||
Name = name,
|
||||
City = city,
|
||||
Province = province,
|
||||
Agent = agents[random.Next(agents.Length)],
|
||||
Kind = kind,
|
||||
Revenue = revenue,
|
||||
Overdue = random.Next(8) == 0 ? Math.Round(revenue * (decimal)random.NextDouble() * 0.3m, 2) : 0m,
|
||||
Credit = random.Next(5) * 10_000m,
|
||||
Since = new DateOnly(2005, 1, 1).AddDays(random.Next(7600)),
|
||||
State = random.Next(25) switch { 0 => "blocked", 1 => "disabled", _ => "active" },
|
||||
Vip = random.Next(12) == 0,
|
||||
});
|
||||
}
|
||||
|
||||
return customers;
|
||||
}
|
||||
|
||||
/// <summary>Makes the fake items.</summary>
|
||||
/// <returns>The items.</returns>
|
||||
public static IReadOnlyList<SampleItem> MakeItems()
|
||||
{
|
||||
string[] names = ["Valvola a sfera", "Raccordo a T", "Tubo multistrato", "Guarnizione", "Manometro", "Collettore", "Termostato", "Filtro a Y", "Pompa di prova", "Staffa zincata"];
|
||||
string[] sizes = ["1/2 pollice", "3/4 pollice", "1 pollice", "16 mm", "20 mm", "26 mm"];
|
||||
var random = new Random(1123);
|
||||
var items = new List<SampleItem>();
|
||||
var n = 1;
|
||||
foreach (var name in names)
|
||||
{
|
||||
foreach (var size in sizes)
|
||||
{
|
||||
items.Add(new SampleItem("ART-" + n.ToString("D4", System.Globalization.CultureInfo.InvariantCulture), name + " " + size, n % 3 == 0 ? "MT" : "PZ",
|
||||
Math.Round(1m + ((decimal)random.NextDouble() * 120m), 2), random.Next(0, 500)));
|
||||
n++;
|
||||
}
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
/// <summary>A new sample document.</summary>
|
||||
/// <param name="today">Today.</param>
|
||||
/// <returns>The document.</returns>
|
||||
public static SampleDocument Document(DateOnly today)
|
||||
{
|
||||
var document = new SampleDocument { Number = "2026/000123", Date = today, Party = Parties[0], Discount = 0 };
|
||||
document.Lines.Add(new SampleLine { Code = "ART-001", Description = "Articolo di prova", Quantity = 10, Price = 12.5m });
|
||||
document.Lines.Add(new SampleLine { Code = "ART-002", Description = "Servizio dimostrativo", Quantity = 1, Price = 340m });
|
||||
document.Lines.Add(new SampleLine { Code = "ART-003", Description = "Materiale fittizio", Quantity = 4.5m, Price = 8.9m });
|
||||
document.Lines.Add(new SampleLine { Code = "ART-0001", Description = "Valvola a sfera 1/2 pollice", Unit = "PZ", Quantity = 10, Price = 12.5m });
|
||||
document.Lines.Add(new SampleLine { Code = "ART-0002", Description = "Valvola a sfera 3/4 pollice", Unit = "PZ", Quantity = 1, Price = 340m });
|
||||
document.Lines.Add(new SampleLine { Descriptive = true, Description = "Consegna al cantiere di prova, piano terra" });
|
||||
document.Lines.Add(new SampleLine { Code = "ART-0003", Description = "Tubo multistrato 16 mm", Unit = "MT", Quantity = 4.5m, Price = 8.9m, Discount = 10 });
|
||||
return document;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Khaemhat.Application.Localization;
|
||||
using Khaemhat.Application.Querying;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
|
||||
namespace Khaemhat.Web.Ui;
|
||||
|
||||
/// <summary>How a grid column shows its value (SPEC §10.7 <c>KhGrid</c>: typed columns).</summary>
|
||||
public enum KhColumnKind
|
||||
{
|
||||
/// <summary>Text.</summary>
|
||||
Text = 0,
|
||||
|
||||
/// <summary>A code: monospace, accent colour.</summary>
|
||||
Code = 1,
|
||||
|
||||
/// <summary>A number with <see cref="KhColumn{TItem}.Decimals"/> decimals, right-aligned.</summary>
|
||||
Number = 2,
|
||||
|
||||
/// <summary>An amount in euro, right-aligned.</summary>
|
||||
Money = 3,
|
||||
|
||||
/// <summary>A date.</summary>
|
||||
Date = 4,
|
||||
|
||||
/// <summary>Yes or no.</summary>
|
||||
Bool = 5,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A column of a <c>KhGrid</c> or <c>KhRadar</c>. <see cref="Id"/> is also the field of <see cref="ListFields{T}"/> that
|
||||
/// sorts and filters it (when <see cref="Sortable"/>), and the key of its total in <see cref="ListPage{T}.Totals"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TItem">The row type.</typeparam>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <param name="title">The title (a text from the resources).</param>
|
||||
/// <param name="value">The value of a row, used for display, export and editing.</param>
|
||||
public sealed class KhColumn<TItem>(string id, string title, Func<TItem, object?> value)
|
||||
{
|
||||
/// <summary>The id.</summary>
|
||||
public string Id { get; } = id;
|
||||
|
||||
/// <summary>The title.</summary>
|
||||
public string Title { get; } = title;
|
||||
|
||||
/// <summary>The value of a row.</summary>
|
||||
public Func<TItem, object?> Value { get; } = value;
|
||||
|
||||
/// <summary>How the value is shown.</summary>
|
||||
public KhColumnKind Kind { get; init; }
|
||||
|
||||
/// <summary>The decimals of a <see cref="KhColumnKind.Number"/>.</summary>
|
||||
public int Decimals { get; init; }
|
||||
|
||||
/// <summary>The width, as CSS (<c>110px</c>, <c>12ch</c>); none lets the table decide.</summary>
|
||||
public string? Width { get; init; }
|
||||
|
||||
/// <summary>Whether the header sorts the rows.</summary>
|
||||
public bool Sortable { get; init; } = true;
|
||||
|
||||
/// <summary>Whether the column is shown until the user changes the layout.</summary>
|
||||
public bool Visible { get; init; } = true;
|
||||
|
||||
/// <summary>Whether the totals row shows the sum the source returned for this column.</summary>
|
||||
public bool Total { get; init; }
|
||||
|
||||
/// <summary>Whether the column goes in the exported files.</summary>
|
||||
public bool Export { get; init; } = true;
|
||||
|
||||
/// <summary>The cell content, instead of the formatted value (badges, links).</summary>
|
||||
public RenderFragment<TItem>? Template { get; init; }
|
||||
|
||||
/// <summary>Extra classes of a cell, for highlights (<c>neg</c> for a red amount).</summary>
|
||||
public Func<TItem, string?>? CellClass { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Makes the cell editable in place (double click or F2): receives the row and the text typed and returns an error
|
||||
/// message, or <see langword="null"/> when the value was saved.
|
||||
/// </summary>
|
||||
public Func<TItem, string, Task<string?>>? Edit { get; init; }
|
||||
|
||||
/// <summary>The values a filter on this column can take (states, types); none for a free value.</summary>
|
||||
public IReadOnlyList<KhOption<string>>? Choices { get; init; }
|
||||
|
||||
/// <summary>Whether the value is a number aligned right.</summary>
|
||||
public bool IsNumeric => Kind is KhColumnKind.Number or KhColumnKind.Money;
|
||||
|
||||
/// <summary>The value of a row as text, in the culture of the texts.</summary>
|
||||
/// <param name="item">The row.</param>
|
||||
/// <param name="texts">The texts.</param>
|
||||
/// <returns>The text.</returns>
|
||||
public string Format(TItem item, ITexts texts) => FormatValue(Value(item), texts);
|
||||
|
||||
/// <summary>A value of this column as text.</summary>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <param name="texts">The texts.</param>
|
||||
/// <returns>The text.</returns>
|
||||
public string FormatValue(object? value, ITexts texts)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(texts);
|
||||
return (Kind, value) switch
|
||||
{
|
||||
(_, null) => string.Empty,
|
||||
(KhColumnKind.Money, _) => texts.Money(Convert.ToDecimal(value, CultureInfo.InvariantCulture)),
|
||||
(KhColumnKind.Number, _) => texts.Number(Convert.ToDecimal(value, CultureInfo.InvariantCulture), Decimals),
|
||||
(_, DateOnly date) => texts.Date(date),
|
||||
(_, bool flag) => texts[flag ? "Ui.Grid.Yes" : "Ui.Grid.No"],
|
||||
(_, IFormattable formattable) => formattable.ToString(null, texts.Culture),
|
||||
_ => value.ToString() ?? string.Empty,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The columns a user keeps and their order, saved in the user settings per grid.</summary>
|
||||
/// <param name="Order">The column ids in order.</param>
|
||||
/// <param name="Hidden">The hidden column ids.</param>
|
||||
public sealed record KhGridLayout(IReadOnlyList<string> Order, IReadOnlyList<string> Hidden)
|
||||
{
|
||||
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
|
||||
|
||||
/// <summary>The key of the setting of a grid.</summary>
|
||||
/// <param name="grid">The grid id.</param>
|
||||
/// <returns>The key.</returns>
|
||||
public static string KeyOf(string grid) => "grid." + grid + ".layout";
|
||||
|
||||
/// <summary>Reads a saved layout; anything unreadable gives <see langword="null"/> (the default layout).</summary>
|
||||
/// <param name="json">The setting.</param>
|
||||
/// <returns>The layout.</returns>
|
||||
public static KhGridLayout? Parse(string? json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize<KhGridLayout>(json, Json);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The layout as JSON.</summary>
|
||||
/// <returns>The JSON.</returns>
|
||||
public string ToJson() => JsonSerializer.Serialize(this, Json);
|
||||
|
||||
/// <summary>The columns to show, in order: saved order first, columns added since then at their place.</summary>
|
||||
/// <typeparam name="TItem">The row type.</typeparam>
|
||||
/// <param name="columns">The columns of the grid.</param>
|
||||
/// <param name="layout">The saved layout, or <see langword="null"/>.</param>
|
||||
/// <returns>The visible columns.</returns>
|
||||
public static IReadOnlyList<KhColumn<TItem>> Apply<TItem>(IReadOnlyList<KhColumn<TItem>> columns, KhGridLayout? layout)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(columns);
|
||||
if (layout is null)
|
||||
{
|
||||
return [.. columns.Where(c => c.Visible)];
|
||||
}
|
||||
|
||||
var position = layout.Order.Select((id, i) => (id, i)).ToDictionary(p => p.id, p => p.i, StringComparer.Ordinal);
|
||||
var hidden = layout.Hidden.ToHashSet(StringComparer.Ordinal);
|
||||
return
|
||||
[
|
||||
.. columns
|
||||
.Select((c, i) => (Column: c, Index: i))
|
||||
.OrderBy(p => position.TryGetValue(p.Column.Id, out var at) ? at : p.Index + 0.5)
|
||||
.Select(p => p.Column)
|
||||
.Where(c => !hidden.Contains(c.Id) && (c.Visible || position.ContainsKey(c.Id))),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Filters, search and ordering a user saved on a radar under a name.</summary>
|
||||
/// <param name="Name">The name.</param>
|
||||
/// <param name="Search">The text of the search box.</param>
|
||||
/// <param name="Filters">The filters.</param>
|
||||
/// <param name="Sort">The ordering.</param>
|
||||
public sealed record KhSavedFilter(string Name, string? Search, IReadOnlyList<ListFilter> Filters, IReadOnlyList<ListSort> Sort)
|
||||
{
|
||||
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
|
||||
|
||||
/// <summary>The most filters kept per radar.</summary>
|
||||
public const int MaxCount = 30;
|
||||
|
||||
/// <summary>The key of the setting of a radar.</summary>
|
||||
/// <param name="radar">The radar id.</param>
|
||||
/// <returns>The key.</returns>
|
||||
public static string KeyOf(string radar) => "radar." + radar + ".filters";
|
||||
|
||||
/// <summary>Reads the saved filters; anything unreadable gives none.</summary>
|
||||
/// <param name="json">The setting.</param>
|
||||
/// <returns>The filters.</returns>
|
||||
public static IReadOnlyList<KhSavedFilter> ParseAll(string? json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize<List<KhSavedFilter>>(json, Json) ?? [];
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The saved filters as JSON.</summary>
|
||||
/// <param name="filters">The filters.</param>
|
||||
/// <returns>The JSON.</returns>
|
||||
public static string ToJson(IEnumerable<KhSavedFilter> filters) => JsonSerializer.Serialize(filters.Take(MaxCount).ToList(), Json);
|
||||
}
|
||||
|
||||
/// <summary>A filter of the bar of a radar shown as a drop-down (Tipo, Agente, Stato in mockup 012).</summary>
|
||||
/// <param name="Field">The field id.</param>
|
||||
/// <param name="Label">The label.</param>
|
||||
/// <param name="Options">The values (invariant text) and their labels; the first empty value means "all".</param>
|
||||
public sealed record KhQuickFilter(string Field, string Label, IReadOnlyList<KhOption<string>> Options);
|
||||
|
||||
/// <summary>A column of a <c>KhLinesGrid</c> (the lines of a document, SPEC §10.5).</summary>
|
||||
/// <typeparam name="TLine">The line type.</typeparam>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <param name="title">The title.</param>
|
||||
/// <param name="value">The value of a line.</param>
|
||||
public sealed class KhLineColumn<TLine>(string id, string title, Func<TLine, object?> value)
|
||||
{
|
||||
/// <summary>The id.</summary>
|
||||
public string Id { get; } = id;
|
||||
|
||||
/// <summary>The title.</summary>
|
||||
public string Title { get; } = title;
|
||||
|
||||
/// <summary>The value of a line.</summary>
|
||||
public Func<TLine, object?> Value { get; } = value;
|
||||
|
||||
/// <summary>How the value is shown and typed.</summary>
|
||||
public KhColumnKind Kind { get; init; }
|
||||
|
||||
/// <summary>The decimals of a number (two for amounts).</summary>
|
||||
public int Decimals { get; init; } = 2;
|
||||
|
||||
/// <summary>The width, as CSS.</summary>
|
||||
public string? Width { get; init; }
|
||||
|
||||
/// <summary>Saves a text typed in the cell; none with <see cref="SetNumber"/> makes the cell read-only.</summary>
|
||||
public Action<TLine, string?>? SetText { get; init; }
|
||||
|
||||
/// <summary>Saves a number typed in the cell (Italian format, inline calculation).</summary>
|
||||
public Action<TLine, decimal?>? SetNumber { get; init; }
|
||||
|
||||
/// <summary>Opens the lookup of the cell (F4): the radar of the items for the code.</summary>
|
||||
public Func<TLine, Task>? Lookup { get; init; }
|
||||
|
||||
/// <summary>Whether the cell can be typed in.</summary>
|
||||
public bool IsEditable => SetText is not null || SetNumber is not null;
|
||||
|
||||
/// <summary>Whether the value is a number aligned right.</summary>
|
||||
public bool IsNumeric => Kind is KhColumnKind.Number or KhColumnKind.Money;
|
||||
}
|
||||
@@ -218,3 +218,84 @@ button.ctx { cursor: pointer; }
|
||||
.kh-catalogrow { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.kh-catalogbar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; padding: 10px 11px; }
|
||||
.kh-resizable { resize: horizontal; overflow: hidden; min-width: 240px; max-width: 100%; padding: 2px 6px 12px 2px; border: 1px dashed var(--kh-border); border-radius: var(--kh-radius-lg); }
|
||||
|
||||
/* ---- Grids, radar and document lines (issue #28) ---- */
|
||||
.kh-sr { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
|
||||
.kh-grid { display: flex; flex-direction: column; min-height: 0; min-width: 0; }
|
||||
.kh-gridwrap { position: relative; min-height: 120px; }
|
||||
.kh-gridwrap:focus-visible { outline: 2px solid var(--kh-accent); outline-offset: -2px; }
|
||||
.kh-th { border: 0; background: none; padding: 0; font: inherit; color: inherit; cursor: pointer; display: inline-flex; align-items: center; gap: 3px; }
|
||||
.kh-th:hover { color: var(--kh-text); }
|
||||
.kh-th[data-sort="asc"]::after { content: "\25B2"; color: var(--kh-accent); font-size: 9px; }
|
||||
.kh-th[data-sort="desc"]::after { content: "\25BC"; color: var(--kh-accent); font-size: 9px; }
|
||||
.grid th.num .kh-th { flex-direction: row-reverse; }
|
||||
.grid tbody tr { cursor: default; }
|
||||
.grid tbody tr:hover td { background: var(--kh-row-sel); }
|
||||
.grid tr.kh-cur td { box-shadow: inset 0 1px 0 var(--kh-accent), inset 0 -1px 0 var(--kh-accent); }
|
||||
.grid tr.kh-cur td:first-child { box-shadow: inset 2px 0 0 var(--kh-accent), inset 0 1px 0 var(--kh-accent), inset 0 -1px 0 var(--kh-accent); }
|
||||
.grid tr.kh-ph td { color: transparent; }
|
||||
.grid tr.kh-empty td { text-align: center; color: var(--kh-text-3); height: 64px; white-space: normal; }
|
||||
.grid td.num, .grid td .num { text-align: right; font-variant-numeric: tabular-nums; }
|
||||
.grid td.neg { color: var(--kh-err); }
|
||||
.grid td.ed { padding: 0 2px; }
|
||||
.kh-bxbtn { border: 0; background: none; padding: 4px; cursor: pointer; display: grid; place-items: center; margin: 0 auto; }
|
||||
.kh-bxbtn .bx svg.i { width: 10px; height: 10px; color: #fff; }
|
||||
.grid .kh-rowmenu { width: 32px; padding: 0 4px; text-align: center; }
|
||||
.kh-rowbtn { border: 0; background: none; color: var(--kh-text-3); width: 24px; height: 24px; border-radius: 5px; display: grid; place-items: center; cursor: pointer; opacity: 0; }
|
||||
.grid tr:hover .kh-rowbtn, .grid tr.kh-cur .kh-rowbtn, .kh-rowbtn:focus-visible { opacity: 1; }
|
||||
.kh-rowbtn:hover { background: var(--kh-surface-3); color: var(--kh-text); }
|
||||
.kh-rowpop { z-index: 21; max-height: 70vh; overflow-y: auto; }
|
||||
.kh-celledit { width: 100%; height: calc(var(--kh-row-h) - 6px); border: 0; background: transparent; font: inherit; color: var(--kh-text); outline: none; padding: 0 8px; }
|
||||
.kh-celledit.num { text-align: right; }
|
||||
.gridfoot .kh-pager { display: inline-flex; gap: 2px; align-items: center; margin-left: auto; }
|
||||
.kh-pg { border: 0; background: none; font: inherit; font-size: 12px; color: var(--kh-text-2); min-width: 26px; height: 24px; padding: 0 6px; border-radius: 5px; cursor: pointer; display: inline-grid; place-items: center; }
|
||||
.kh-pg:hover:not(:disabled) { background: var(--kh-surface-3); }
|
||||
.kh-pg.on { background: var(--kh-accent); color: #fff; }
|
||||
.kh-pg:disabled { opacity: .35; cursor: default; }
|
||||
.kh-pgdots { padding: 0 4px; color: var(--kh-text-3); }
|
||||
.kh-colchooser { list-style: none; margin: 8px 0 0; padding: 0; display: flex; flex-direction: column; gap: 2px; max-height: 50vh; overflow: auto; }
|
||||
.kh-colchooser li { display: flex; align-items: center; gap: 4px; padding: 2px 4px; border-radius: 6px; }
|
||||
.kh-colchooser li:hover { background: var(--kh-surface-2); }
|
||||
.kh-colcheck { display: flex; align-items: center; gap: 8px; flex: 1; min-width: 0; font-size: 12.5px; cursor: pointer; padding: 4px 0; }
|
||||
.kh-colcheck input { accent-color: var(--kh-accent); width: 15px; height: 15px; margin: 0; }
|
||||
|
||||
.kh-radar { display: flex; flex-direction: column; gap: 10px; min-height: 0; min-width: 0; }
|
||||
.kh-radarbar { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
|
||||
.kh-radarbar .grow { flex: 1; }
|
||||
.kh-radarpanel { display: flex; flex-direction: column; min-height: 0; overflow: visible; }
|
||||
.kh-radarpanel .kh-grid { flex: 1; }
|
||||
.kh-radarpanel .kh-gridwrap { flex: none; height: calc(100vh - 330px); }
|
||||
.kh-radar.compact .filters { padding: 8px 0 10px; }
|
||||
.kh-rsearch { display: inline-flex; align-items: center; gap: 6px; height: 28px; min-width: 220px; flex: 0 1 280px; padding: 0 8px; cursor: text; }
|
||||
.kh-rsearch input { border: 0; outline: none; background: transparent; font: inherit; color: var(--kh-text); flex: 1; min-width: 0; height: 100%; }
|
||||
.kh-rsearch svg.i { color: var(--kh-text-3); flex: none; }
|
||||
.kh-rsearch:focus-within { border-color: var(--kh-accent); box-shadow: 0 0 0 3px var(--kh-accent-soft); }
|
||||
.filters .grow { flex: 1; }
|
||||
.btn.kh-addfilter { height: 28px; }
|
||||
.kh-savedlist { list-style: none; margin: 0 0 12px; padding: 0; display: flex; flex-direction: column; gap: 2px; }
|
||||
.kh-savedlist li { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 2px 4px 2px 8px; border-radius: 6px; }
|
||||
.kh-savedlist li:hover { background: var(--kh-surface-2); }
|
||||
.kh-choices { border: 0; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 2px; }
|
||||
.kh-choices legend { font-size: 12px; font-weight: 600; color: var(--kh-text-2); margin-bottom: 4px; padding: 0; }
|
||||
.kh-filterform { gap: 10px; }
|
||||
.kh-grow { flex: 1; }
|
||||
|
||||
.kh-linesgrid { display: flex; flex-direction: column; min-width: 0; }
|
||||
.kh-linesgrid .gridwrap { overflow-x: auto; }
|
||||
.grid.kh-lines td { overflow: visible; }
|
||||
.grid.kh-lines td.kh-ce { padding: 0 2px; }
|
||||
.grid .kh-ln { width: 34px; text-align: right; color: var(--kh-text-3); font-size: 11px; padding-right: 8px; }
|
||||
input.kh-cell { width: 100%; height: calc(var(--kh-row-h) - 4px); border: 1px solid transparent; border-radius: 4px; background: transparent; font: inherit; color: var(--kh-text); padding: 0 8px; outline: none; min-width: 3ch; }
|
||||
input.kh-cell:hover { border-color: var(--kh-border); }
|
||||
input.kh-cell:focus { border-color: var(--kh-accent); background: var(--kh-input); box-shadow: 0 0 0 2px var(--kh-accent-soft); }
|
||||
input.kh-cell.num { text-align: right; font-variant-numeric: tabular-nums; }
|
||||
input.kh-cell.code { font-family: var(--kh-mono); font-size: 12px; font-weight: 600; color: var(--kh-accent-text); }
|
||||
input.kh-cell.err { border-color: var(--kh-err); background: var(--kh-err-soft); }
|
||||
.grid tr.kh-desc td.desc-row input.kh-cell { font-style: italic; color: var(--kh-text-2); }
|
||||
.grid tr.kh-pending td { background: var(--kh-surface) !important; }
|
||||
.grid tr.kh-pending input.kh-cell { border-style: dashed; border-color: var(--kh-border); }
|
||||
.grid tr.kh-pending input.kh-cell:focus { border-style: solid; border-color: var(--kh-accent); }
|
||||
.kh-linesbar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; padding: 8px 12px; border-top: 1px solid var(--kh-border); }
|
||||
.kh-linesbar .grow { flex: 1; }
|
||||
.kbdhint { display: inline-flex; gap: 3px; align-items: center; font: 10.5px var(--kh-mono); color: var(--kh-text-3); white-space: nowrap; }
|
||||
.kbdhint kbd { border: 1px solid var(--kh-border-strong); border-bottom-width: 2px; padding: 0 4px; border-radius: 3px; background: var(--kh-surface); font: inherit; color: var(--kh-text-2); }
|
||||
@@ -32,11 +32,23 @@
|
||||
if (!shortcutTarget || e.isComposing) return;
|
||||
const combo = comboOf(e);
|
||||
if (!combo || !shortcutCombos.has(combo) || preventedBy(e.target, combo)) return;
|
||||
// A modal window is open: the page behind it does not react (Ctrl+Canc in a search box must not delete the record).
|
||||
if (document.querySelector(".overlay")) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
shortcutTarget.invokeMethodAsync("OnShortcut", combo).catch(function () { /* circuit gone */ });
|
||||
}
|
||||
|
||||
// Escape closes the topmost dialog even when the focus fell out of it (after a re-render, a click on the page).
|
||||
// Inside the dialog its own handler already does it.
|
||||
document.addEventListener("keydown", function (e) {
|
||||
if (e.key !== "Escape" || e.defaultPrevented) return;
|
||||
const overlays = document.querySelectorAll(".overlay");
|
||||
if (overlays.length === 0 || (e.target.closest && e.target.closest(".overlay"))) return;
|
||||
const close = overlays[overlays.length - 1].querySelector(".kh-close");
|
||||
if (close) close.click();
|
||||
});
|
||||
|
||||
function onBeforeUnload(e) {
|
||||
if (!unloadGuard) return;
|
||||
e.preventDefault();
|
||||
@@ -107,6 +119,8 @@
|
||||
element.dispatchEvent(new KeyboardEvent("keydown", { key: e.key === "+" ? "ArrowUp" : "ArrowDown", bubbles: true }));
|
||||
return;
|
||||
}
|
||||
// Keys typed in a field inside the element (a cell being edited) are the field's own.
|
||||
if (e.target !== element && e.target.matches && e.target.matches("input, textarea, select, [contenteditable]")) return;
|
||||
const combo = comboOf(e);
|
||||
if (combo && preventedBy(element, combo)) e.preventDefault();
|
||||
});
|
||||
@@ -134,6 +148,96 @@
|
||||
menu.style.overflowY = "auto";
|
||||
},
|
||||
|
||||
// Brings a row of a grid into view: the row when it is rendered, otherwise its estimated place (virtual rows).
|
||||
scrollGridRow: function (wrap, index) {
|
||||
if (!wrap) return;
|
||||
const row = wrap.querySelector('tr[data-i="' + index + '"]');
|
||||
if (row) {
|
||||
const head = wrap.querySelector("thead");
|
||||
const top = row.offsetTop - (head ? head.offsetHeight : 0);
|
||||
if (top < wrap.scrollTop) wrap.scrollTop = top;
|
||||
else if (row.offsetTop + row.offsetHeight > wrap.scrollTop + wrap.clientHeight) wrap.scrollTop = row.offsetTop + row.offsetHeight - wrap.clientHeight;
|
||||
return;
|
||||
}
|
||||
const sample = wrap.querySelector("tbody tr[data-i]");
|
||||
const height = sample ? sample.offsetHeight : 30;
|
||||
wrap.scrollTop = Math.max(0, index * height - wrap.clientHeight / 2);
|
||||
},
|
||||
|
||||
// Moves a fixed menu back inside the window when it would come out of the right or bottom edge.
|
||||
keepInWindow: function (element) {
|
||||
if (!element) return;
|
||||
const r = element.getBoundingClientRect();
|
||||
if (r.right > window.innerWidth - 8) element.style.left = Math.max(8, window.innerWidth - r.width - 8) + "px";
|
||||
if (r.bottom > window.innerHeight - 8) element.style.top = Math.max(8, window.innerHeight - r.height - 8) + "px";
|
||||
},
|
||||
|
||||
// Hands a file written by the server to the browser as a download.
|
||||
download: async function (fileName, mediaType, streamReference) {
|
||||
const buffer = await streamReference.arrayBuffer();
|
||||
const url = URL.createObjectURL(new Blob([buffer], { type: mediaType }));
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = fileName;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
setTimeout(function () { URL.revokeObjectURL(url); }, 2000);
|
||||
},
|
||||
|
||||
// The keyboard of the lines of a document: Enter next cell, Shift+Enter previous, arrows the same cell of the line
|
||||
// above or below, Ctrl+Down new line, Ctrl+Canc removes the line, F4 lookup. Rows and cells are data-r and data-c.
|
||||
linesGrid: function (table, target) {
|
||||
if (!table || table.khLines) return;
|
||||
table.khLines = true;
|
||||
const cellOf = function (r, c) { return table.querySelector('input.kh-cell[data-r="' + r + '"][data-c="' + c + '"]'); };
|
||||
const focusCell = function (r, c) {
|
||||
let tries = 0;
|
||||
(function attempt() {
|
||||
const el = cellOf(r, c) || table.querySelector('input.kh-cell[data-r="' + r + '"]');
|
||||
if (el) { el.focus(); el.select(); } else if (tries++ < 20) setTimeout(attempt, 40);
|
||||
})();
|
||||
};
|
||||
table.khFocus = focusCell;
|
||||
const flush = function (el) {
|
||||
if (el.khDirty) { el.khDirty = false; el.dispatchEvent(new Event("change", { bubbles: true })); }
|
||||
};
|
||||
table.addEventListener("input", function (e) { if (e.target.classList.contains("kh-cell")) e.target.khDirty = true; });
|
||||
table.addEventListener("change", function (e) { if (e.target.classList.contains("kh-cell")) e.target.khDirty = false; }, true);
|
||||
table.addEventListener("keydown", function (e) {
|
||||
const el = e.target;
|
||||
if (!el.classList || !el.classList.contains("kh-cell") || e.isComposing) return;
|
||||
const r = Number(el.dataset.r), c = Number(el.dataset.c);
|
||||
const combo = comboOf(e);
|
||||
const call = function (method, args, then) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
flush(el);
|
||||
target.invokeMethodAsync.apply(target, [method].concat(args)).then(then).catch(function () { /* circuit gone */ });
|
||||
};
|
||||
if (combo === "Enter" || combo === "Shift+Enter") {
|
||||
e.preventDefault();
|
||||
const cells = Array.prototype.slice.call(table.querySelectorAll("input.kh-cell:not([readonly])"));
|
||||
const next = cells[cells.indexOf(el) + (combo === "Enter" ? 1 : -1)];
|
||||
if (next) { next.focus(); next.select(); }
|
||||
} else if (combo === "ArrowDown" || combo === "ArrowUp") {
|
||||
const other = cellOf(r + (combo === "ArrowDown" ? 1 : -1), c);
|
||||
if (other) { e.preventDefault(); other.focus(); other.select(); }
|
||||
} else if (combo === "Ctrl+ArrowDown") {
|
||||
call("InsertAfterAsync", [r], function () { focusCell(r + 1, 0); });
|
||||
} else if (combo === "Ctrl+Delete") {
|
||||
call("RemoveAtAsync", [r], function () { focusCell(r, c); });
|
||||
} else if (combo === "F4") {
|
||||
call("LookupAsync", [r, c], function () { });
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
// Moves the focus to a cell of the lines of a document.
|
||||
focusLineCell: function (table, r, c) {
|
||||
if (table && table.khFocus) table.khFocus(r, Math.max(0, c));
|
||||
},
|
||||
|
||||
// Moves the focus to the first field or button inside an element (dialogs, side panels).
|
||||
focusFirst: function (element) {
|
||||
if (!element) return;
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../src/Khaemhat.Application/Khaemhat.Application.csproj" />
|
||||
<ProjectReference Include="../../src/Khaemhat.Data.Sqlite/Khaemhat.Data.Sqlite.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,157 @@
|
||||
using Khaemhat.Application.Querying;
|
||||
using Khaemhat.Data.Mapping;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Data.Sqlite;
|
||||
|
||||
namespace Khaemhat.Application.Tests;
|
||||
|
||||
/// <summary>The request of grids and radars, run in memory and translated to SQL (issue #28).</summary>
|
||||
[TestClass]
|
||||
public sealed class ListQueryTests
|
||||
{
|
||||
private static readonly ListFields<ListRow> Fields = new ListFields<ListRow>()
|
||||
.Add("code", x => x.Code, searchable: true)
|
||||
.Add("name", x => x.Name, searchable: true)
|
||||
.Add("amount", x => x.Amount, total: true)
|
||||
.Add("due", x => x.Due)
|
||||
.Add("active", x => x.Active)
|
||||
.Add("state", x => x.State)
|
||||
.OrderByDefault(new ListSort("code"));
|
||||
|
||||
private static readonly ListRow[] Rows =
|
||||
[
|
||||
new() { Id = 1, Code = "C003", Name = "Rossi Impianti", Amount = 100m, Due = new DateOnly(2026, 11, 30), Active = true, State = RowState.Open },
|
||||
new() { Id = 2, Code = "C001", Name = "Bianchi e Figli", Amount = 250.5m, Due = null, Active = true, State = RowState.Closed },
|
||||
new() { Id = 3, Code = "C002", Name = "rossi torino", Amount = -20m, Due = new DateOnly(2026, 12, 15), Active = false, State = RowState.Open },
|
||||
new() { Id = 4, Code = "C004", Name = null, Amount = 0m, Due = new DateOnly(2027, 1, 10), Active = true, State = RowState.Blocked },
|
||||
];
|
||||
|
||||
[TestMethod]
|
||||
public void Memory_SearchMatchesEveryWordIgnoringCase()
|
||||
{
|
||||
var page = Fields.Apply(Rows, new ListQuery { Search = "ROSSI" });
|
||||
CollectionAssert.AreEqual(new[] { "C002", "C003" }, page.Items.Select(r => r.Code).ToArray());
|
||||
|
||||
var both = Fields.Apply(Rows, new ListQuery { Search = "rossi torino" });
|
||||
Assert.AreEqual("C002", both.Items.Single().Code);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Memory_FiltersSortTotalsAndPage()
|
||||
{
|
||||
var query = new ListQuery
|
||||
{
|
||||
Filters = [ListFilter.Of("active", ListFilterOperator.Equals, "true"), ListFilter.Of("amount", ListFilterOperator.GreaterOrEqual, "0")],
|
||||
Sort = [new ListSort("amount", Descending: true)],
|
||||
Offset = 1,
|
||||
Limit = 1,
|
||||
};
|
||||
|
||||
var page = Fields.Apply(Rows, query);
|
||||
|
||||
Assert.AreEqual(3, page.Total);
|
||||
Assert.AreEqual("C003", page.Items.Single().Code);
|
||||
Assert.AreEqual(350.5m, page.Totals["amount"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("due", ListFilterOperator.IsEmpty, new string[0], "C001")]
|
||||
[DataRow("name", ListFilterOperator.IsEmpty, new string[0], "C004")]
|
||||
[DataRow("due", ListFilterOperator.Between, new[] { "2026-12-01", "2026-12-31" }, "C002")]
|
||||
[DataRow("state", ListFilterOperator.In, new[] { "Blocked", "Closed" }, "C001,C004")]
|
||||
[DataRow("state", ListFilterOperator.NotEquals, new[] { "Open" }, "C001,C004")]
|
||||
[DataRow("name", ListFilterOperator.StartsWith, new[] { "BIAN" }, "C001")]
|
||||
[DataRow("name", ListFilterOperator.Equals, new[] { "ROSSI TORINO" }, "C002")]
|
||||
[DataRow("amount", ListFilterOperator.LessThan, new[] { "0" }, "C002")]
|
||||
[DataRow("due", ListFilterOperator.IsNotEmpty, new string[0], "C002,C003,C004")]
|
||||
public void Memory_Operators(string field, ListFilterOperator op, string[] values, string expected)
|
||||
{
|
||||
var page = Fields.Apply(Rows, new ListQuery { Filters = [new ListFilter(field, op, values)] });
|
||||
Assert.AreEqual(expected, string.Join(',', page.Items.Select(r => r.Code)), $"{field} {op}");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void InvalidFilters_AreRecognised()
|
||||
{
|
||||
Assert.IsTrue(Fields.IsValid(ListFilter.Of("amount", ListFilterOperator.GreaterThan, "12.5")));
|
||||
Assert.IsFalse(Fields.IsValid(ListFilter.Of("missing", ListFilterOperator.Equals, "x")));
|
||||
Assert.IsFalse(Fields.IsValid(ListFilter.Of("amount", ListFilterOperator.GreaterThan, "dodici")));
|
||||
Assert.IsFalse(Fields.IsValid(ListFilter.Of("amount", ListFilterOperator.Contains, "1")));
|
||||
Assert.IsFalse(Fields.IsValid(ListFilter.Of("name", ListFilterOperator.GreaterThan, "A")));
|
||||
Assert.IsFalse(Fields.IsValid(ListFilter.Of("due", ListFilterOperator.Between, "2026-01-01")));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => new ListFields<ListRow>().Add("amount", x => x.Amount, searchable: true));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => new ListFields<ListRow>().Add("name", x => x.Name, total: true));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Sql_UsesLikeParametersOrderAndPage()
|
||||
{
|
||||
var map = new ListRowMap();
|
||||
var query = Fields.Apply(Query.For<ListRow>(), new ListQuery
|
||||
{
|
||||
Search = "rossi",
|
||||
Filters = [ListFilter.Of("amount", ListFilterOperator.Between, "10", "20.5"), ListFilter.Of("state", ListFilterOperator.In, "Open", "Closed")],
|
||||
Sort = [new ListSort("due", Descending: true)],
|
||||
Offset = 100,
|
||||
Limit = 50,
|
||||
});
|
||||
|
||||
var sql = new QueryBuilder<ListRow>(map, SqliteDialect.Instance).Select(query).Render(SqliteDialect.Instance);
|
||||
|
||||
StringAssert.Contains(sql.Text, "(kh_lower(\"code\") LIKE kh_lower(@p0) ESCAPE '\\' OR kh_lower(\"name\") LIKE kh_lower(@p1) ESCAPE '\\')");
|
||||
StringAssert.Contains(sql.Text, "(\"amount\" >= @p2 AND \"amount\" <= @p3)");
|
||||
StringAssert.Contains(sql.Text, "\"state\" IN (@p4, @p5)");
|
||||
StringAssert.Contains(sql.Text, "ORDER BY \"due\" DESC, \"code\" ASC");
|
||||
StringAssert.Contains(sql.Text, "100");
|
||||
CollectionAssert.AreEqual(new object?[] { "%rossi%", "%rossi%", 10m, 20.5m, "Open", "Closed" }, sql.Parameters.Select(p => p.Value).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task InMemorySource_PagesOfALargeListAreQuick()
|
||||
{
|
||||
var rows = Enumerable.Range(1, 100_000)
|
||||
.Select(i => new ListRow { Id = i, Code = "C" + i.ToString("D6", System.Globalization.CultureInfo.InvariantCulture), Name = "Cliente " + (i % 977), Amount = i % 1000 })
|
||||
.ToList();
|
||||
var source = new InMemoryListSource<ListRow>(rows, Fields);
|
||||
var query = new ListQuery { Search = "cliente 12", Sort = [new ListSort("amount", true)], Limit = 100 };
|
||||
|
||||
var first = await source.QueryAsync(query, CancellationToken.None);
|
||||
var watch = System.Diagnostics.Stopwatch.StartNew();
|
||||
for (var page = 1; page < 50; page++)
|
||||
{
|
||||
_ = await source.QueryAsync(query.WithPage(page * 100, 100), CancellationToken.None);
|
||||
}
|
||||
|
||||
Assert.IsGreaterThan(0, first.Total);
|
||||
Assert.IsLessThan(1000, watch.ElapsedMilliseconds, "49 pages after the first should come from the kept selection");
|
||||
}
|
||||
|
||||
public enum RowState
|
||||
{
|
||||
Open = 0,
|
||||
Closed = 1,
|
||||
Blocked = 2,
|
||||
}
|
||||
|
||||
public sealed class ListRow
|
||||
{
|
||||
public long Id { get; set; }
|
||||
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
public string? Name { get; set; }
|
||||
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
public DateOnly? Due { get; set; }
|
||||
|
||||
public bool Active { get; set; }
|
||||
|
||||
public RowState State { get; set; }
|
||||
}
|
||||
|
||||
private sealed class ListRowMap : EntityMap<ListRow>
|
||||
{
|
||||
public ListRowMap() => ToTable("list_rows");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user