From 75d60ee4c471da7cfc6c33875883e73af75cb63f Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 18:47:38 +0100 Subject: [PATCH] feat: grids, radar and document lines (#28) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .../Querying/InMemoryListSource.cs | 54 + .../Querying/ListFields.cs | 446 ++++++++ .../Querying/ListQuery.cs | 156 +++ .../Pages/Dev/ComponentCatalog.razor | 98 ++ .../Pages/Dev/SampleDocumentPage.razor | 104 +- src/Khaemhat.Web/Components/Ui/KhGrid.razor | 988 ++++++++++++++++++ .../Components/Ui/KhLinesGrid.razor | 327 ++++++ src/Khaemhat.Web/Components/Ui/KhRadar.razor | 607 +++++++++++ .../Components/Ui/KhRadarDialog.razor | 101 ++ src/Khaemhat.Web/Components/_Imports.razor | 3 + src/Khaemhat.Web/Resources/it-IT/Pages.json | 45 +- src/Khaemhat.Web/Resources/it-IT/Ui.json | 82 ++ src/Khaemhat.Web/Ui/CatalogSamples.cs | 185 +++- src/Khaemhat.Web/Ui/KhGridModels.cs | 265 +++++ src/Khaemhat.Web/wwwroot/css/interactive.css | 81 ++ src/Khaemhat.Web/wwwroot/js/khaemhat.js | 104 ++ .../Khaemhat.Application.Tests.csproj | 1 + .../ListQueryTests.cs | 157 +++ 18 files changed, 3776 insertions(+), 28 deletions(-) create mode 100644 src/Khaemhat.Application/Querying/InMemoryListSource.cs create mode 100644 src/Khaemhat.Application/Querying/ListFields.cs create mode 100644 src/Khaemhat.Application/Querying/ListQuery.cs create mode 100644 src/Khaemhat.Web/Components/Ui/KhGrid.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhLinesGrid.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhRadar.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhRadarDialog.razor create mode 100644 src/Khaemhat.Web/Ui/KhGridModels.cs create mode 100644 tests/Khaemhat.Application.Tests/ListQueryTests.cs diff --git a/src/Khaemhat.Application/Querying/InMemoryListSource.cs b/src/Khaemhat.Application/Querying/InMemoryListSource.cs new file mode 100644 index 0000000..8bfc672 --- /dev/null +++ b/src/Khaemhat.Application/Querying/InMemoryListSource.cs @@ -0,0 +1,54 @@ +namespace Khaemhat.Application.Querying; + +/// +/// A 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. +/// +/// The row type. +/// The rows. +/// The fields. +public sealed class InMemoryListSource(IReadOnlyList rows, ListFields fields) + where T : class +{ + private readonly Lock _lock = new(); + private (ListQuery Query, IReadOnlyList Rows)? _last; + + /// The fields. + public ListFields Fields => fields; + + /// Answers a request. + /// The request. + /// Cancellation. + /// The page. + public Task> QueryAsync(ListQuery query, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(query); + cancellationToken.ThrowIfCancellationRequested(); + return Task.FromResult(fields.Page(Selected(query), query)); + } + + /// Every row a request selects, in order, for exports. + /// The request; its page is ignored. + /// The rows. + public IReadOnlyList All(ListQuery query) => Selected(query); + + private IReadOnlyList 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; + } +} diff --git a/src/Khaemhat.Application/Querying/ListFields.cs b/src/Khaemhat.Application/Querying/ListFields.cs new file mode 100644 index 0000000..ea9d629 --- /dev/null +++ b/src/Khaemhat.Application/Querying/ListFields.cs @@ -0,0 +1,446 @@ +using System.Globalization; +using System.Linq.Expressions; +using System.Reflection; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Querying; + +/// +/// The fields a list can search, filter, order and total, each bound to a property of the row. One description serves +/// both sides: adds conditions, ordering and page to a repository query (SQL, +/// case-insensitive LIKE for texts), runs the same request on rows in +/// memory. +/// +/// The row type. +public sealed class ListFields + where T : class +{ + private readonly Dictionary> _fields = new(StringComparer.Ordinal); + private readonly List> _ordered = []; + + /// The fields, in the order added. + public IReadOnlyList> Fields => _ordered; + + /// The ordering used when the request has none, so that pages do not overlap. + public IReadOnlyList DefaultSort { get; private set; } = []; + + /// Adds a field. + /// The type of the property. + /// The id used in filters and orderings. + /// The property. + /// Whether the search box looks in it (texts only). + /// Whether the page carries its sum (numbers only). + /// This, to chain. + public ListFields Add(string id, Expression> 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.Numeric is null) + { + throw new ArgumentException($"Only number fields can be totalled: {id}.", nameof(total)); + } + + var field = new ListField(id, selector, searchable, total); + _fields.Add(id, field); + _ordered.Add(field); + return this; + } + + /// Sets the ordering used when the request has none. + /// The ordering; the last field should be unique (the code or the id). + /// This, to chain. + public ListFields OrderByDefault(params ListSort[] sort) + { + foreach (var item in sort) + { + _ = Get(item.Field); + } + + DefaultSort = sort; + return this; + } + + /// A field by id. + /// The id. + /// The field, or . + public ListField? Find(string id) => _fields.GetValueOrDefault(id); + + /// Whether a filter can be applied: known field, operator fit for its type, readable values. + /// The filter, for example one read from the saved filters. + /// Whether it is valid. + public bool IsValid(ListFilter filter) + { + try + { + _ = Condition(Expression.Parameter(typeof(T), "x"), filter, inMemory: true); + return true; + } + catch (ArgumentException) + { + return false; + } + } + + /// Adds the conditions, the ordering and the page of a request to a repository query. + /// The query, possibly with conditions of its own (the company, the state...). + /// The request. + /// The query. + public Query Apply(Query 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)); + } + + /// Runs a request on rows in memory: filters, totals, ordering and page. + /// The rows. + /// The request. + /// The page. + public ListPage Apply(IEnumerable source, ListQuery list) + { + var rows = Select(source, list); + return Page(rows, list); + } + + /// The rows a request selects, filtered and ordered, without paging (for exports and caches). + /// The rows. + /// The request. + /// The rows. + public IReadOnlyList Select(IEnumerable source, ListQuery list) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(list); + if (Predicate(list, inMemory: true) is { } predicate) + { + source = source.Where(predicate.Compile()); + } + + IOrderedEnumerable? ordered = null; + foreach (var sort in SortOf(list)) + { + ordered = Get(sort.Field).OrderMemory(source, ordered, sort.Descending); + } + + return [.. ordered ?? source]; + } + + /// A page of rows already selected and ordered by , with the totals. + /// The rows. + /// The request. + /// The page. + public ListPage Page(IReadOnlyList 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 items = [.. rows.Skip(Math.Max(0, list.Offset)).Take(limit)]; + return new ListPage(items, rows.Count, totals); + } + + /// The condition of a request (search and filters), or when it selects everything. + /// The request. + /// Whether for rows in memory (texts compared ignoring case) or for SQL. + /// The predicate. + public Expression>? Predicate(ListQuery list, bool inMemory) + { + ArgumentNullException.ThrowIfNull(list); + var row = Expression.Parameter(typeof(T), "x"); + var parts = new List(); + + 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>(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 Get(string id) => Find(id) ?? throw new ArgumentException($"Unknown field: {id}.", nameof(id)); + + private List 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; + } +} + +/// A field of a . +/// The row type. +public abstract class ListField + where T : class +{ + private protected ListField(string id, Type valueType, bool searchable, bool total) + { + Id = id; + ValueType = valueType; + Searchable = searchable; + Total = total; + } + + /// The id. + public string Id { get; } + + /// The type of the property (nullable included). + public Type ValueType { get; } + + /// Whether the search box looks in it. + public bool Searchable { get; } + + /// Whether the page carries its sum. + public bool Total { get; } + + /// The value of the field in a row. + /// The row. + /// The value. + 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 OrderQuery(Query query, bool descending); + + internal abstract IOrderedEnumerable OrderMemory(IEnumerable source, IOrderedEnumerable? ordered, bool descending); + + internal abstract decimal Sum(IEnumerable rows); +} + +/// A field bound to a property of type . +/// The row type. +/// The property type. +internal sealed class ListField : ListField + 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> _selector; + private readonly Func _compiled; + + public ListField(string id, Expression> selector, bool searchable, bool total) + : base(id, typeof(TValue), searchable, total) + { + _selector = selector; + _compiled = selector.Compile(); + } + + /// Converts a value to decimal for the totals, or when the type is not a number. + public static Func? 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 OrderQuery(Query query, bool descending) => + descending ? query.OrderByDescending(_selector) : query.OrderBy(_selector); + + internal override IOrderedEnumerable OrderMemory(IEnumerable source, IOrderedEnumerable? ordered, bool descending) + { + var comparer = IsText ? (IComparer)(object)StringComparer.CurrentCultureIgnoreCase : Comparer.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 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 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); + } +} diff --git a/src/Khaemhat.Application/Querying/ListQuery.cs b/src/Khaemhat.Application/Querying/ListQuery.cs new file mode 100644 index 0000000..3ac5f73 --- /dev/null +++ b/src/Khaemhat.Application/Querying/ListQuery.cs @@ -0,0 +1,156 @@ +using System.Globalization; + +namespace Khaemhat.Application.Querying; + +/// How a filter compares a field with its values (SPEC §10.7 KhGrid, KhRadar). +public enum ListFilterOperator +{ + /// Equal to the value. + Equals = 0, + + /// Different from the value. + NotEquals = 1, + + /// Text containing the value, ignoring case. + Contains = 2, + + /// Text starting with the value, ignoring case. + StartsWith = 3, + + /// Greater than the value. + GreaterThan = 4, + + /// Greater than or equal to the value. + GreaterOrEqual = 5, + + /// Less than the value. + LessThan = 6, + + /// Less than or equal to the value. + LessOrEqual = 7, + + /// Between the first and the second value, both included. + Between = 8, + + /// One of the values. + In = 9, + + /// Empty (null, or an empty text). + IsEmpty = 10, + + /// Not empty. + IsNotEmpty = 11, +} + +/// +/// A filter on a field. The values are invariant texts (2026-11-30, 1234.5, true, the name of an +/// enum value), so a filter can be saved in the user settings and read back unchanged. +/// +/// The field id. +/// The comparison. +/// The values: none for the empty checks, two for . +public sealed record ListFilter(string Field, ListFilterOperator Operator, IReadOnlyList Values) +{ + /// A filter with its values. + /// The field id. + /// The comparison. + /// The values. + /// The filter. + public static ListFilter Of(string field, ListFilterOperator op, params string[] values) => new(field, op, values); + + /// The invariant text of a value, as filters keep it. + /// The value. + /// The text. + 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, + }; + + /// + public bool Equals(ListFilter? other) => + other is not null && Field == other.Field && Operator == other.Operator && Values.SequenceEqual(other.Values); + + /// + 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(); + } +} + +/// An ordering on a field. +/// The field id. +/// Whether from the largest. +public sealed record ListSort(string Field, bool Descending = false); + +/// +/// 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 ; with the same request becomes SQL for +/// a repository or runs on rows in memory. +/// +public sealed record ListQuery +{ + /// The largest page a source returns. + public const int MaxLimit = 1000; + + /// The text of the search box: every searchable field is checked. + public string? Search { get; init; } + + /// The filters, all of which must hold. + public IReadOnlyList Filters { get; init; } = []; + + /// The ordering, first field first. + public IReadOnlyList Sort { get; init; } = []; + + /// The rows to skip. + public int Offset { get; init; } + + /// The rows to return, at most . + public int Limit { get; init; } = 50; + + /// The same request for another page. + /// The rows to skip. + /// The rows to return. + /// The request. + public ListQuery WithPage(int offset, int limit) => this with { Offset = Math.Max(0, offset), Limit = Math.Clamp(limit, 1, MaxLimit) }; + + /// Whether two requests select and order the same rows, whatever the page. + /// The other request. + /// Whether they match. + 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); +} + +/// A page of rows with the count and the totals of every row the request selects (not only the page). +/// The row type. +/// The rows of the page. +/// The rows selected. +/// The sums by field id, for the totals row of the grid. +public sealed record ListPage(IReadOnlyList Items, long Total, IReadOnlyDictionary Totals) +{ + /// No rows. +#pragma warning disable CA1000 // An empty page of the same row type is the natural default. + public static ListPage Empty { get; } = new([], 0, new Dictionary()); +#pragma warning restore CA1000 +} + +/// Where a grid or radar reads its rows. +/// The row type. +/// The request. +/// Cancellation, when a newer request replaces this one. +/// The page. +public delegate Task> ListSource(ListQuery query, CancellationToken cancellationToken); diff --git a/src/Khaemhat.Web/Components/Pages/Dev/ComponentCatalog.razor b/src/Khaemhat.Web/Components/Pages/Dev/ComponentCatalog.razor index 500424e..b5ad709 100644 --- a/src/Khaemhat.Web/Components/Pages/Dev/ComponentCatalog.razor +++ b/src/Khaemhat.Web/Components/Pages/Dev/ComponentCatalog.razor @@ -153,6 +153,26 @@ else break; + case "griglie": +
+ + +
+

@T["Pages.Catalog.Grids.Radar"]

+

@T["Pages.Catalog.Grids.RadarIntro"]

+
+
+
+ +

@T["Pages.Catalog.Grids.PagerIntro"]

+ +
+
+ break; + case "toolbar":

@T["Pages.Catalog.Toolbar.Intro"]

@@ -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 VipOnly = [ListFilter.Of("vip", ListFilterOperator.Equals, "true")]; + + private IReadOnlyList> KindChoices => + [ + new("company", T["Pages.Catalog.Grids.KindCompany"]), + new("person", T["Pages.Catalog.Grids.KindPerson"]), + new("public", T["Pages.Catalog.Grids.KindPublic"]), + ]; + + private IReadOnlyList> StateChoices => + [ + new("active", T["Pages.Catalog.Grids.StateActive"]), + new("blocked", T["Pages.Catalog.Grids.StateBlocked"]), + new("disabled", T["Pages.Catalog.Grids.StateDisabled"]), + ]; + + private IReadOnlyList> 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 => @ KhTone.Ok, "blocked" => KhTone.Error, _ => KhTone.Neutral })">@StateChoices.First(k => k.Value == c.State).Text, + }, + ]; + + private IReadOnlyList> 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 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 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 EditCreditAsync(SampleCustomer customer, string text) + { + if (!ItalianNumber.TryParse(text, out var value) || value is null) + { + return Task.FromResult(T["Ui.Validation.Number"]); + } + + if (value < 0) + { + return Task.FromResult(T["Pages.Catalog.Grids.CreditInvalid"]); + } + + customer.Credit = Math.Round(value.Value, 2); + return Task.FromResult(null); + } + private void ShowToast(ToastKind kind) => Toasts.Show(kind, T[KindKey(kind)], T["Pages.Catalog.Windows.ToastText"]); } diff --git a/src/Khaemhat.Web/Components/Pages/Dev/SampleDocumentPage.razor b/src/Khaemhat.Web/Components/Pages/Dev/SampleDocumentPage.razor index 84259a3..3ea302b 100644 --- a/src/Khaemhat.Web/Components/Pages/Dev/SampleDocumentPage.razor +++ b/src/Khaemhat.Web/Components/Pages/Dev/SampleDocumentPage.razor @@ -45,29 +45,9 @@ else @switch (ActiveTab) { case TabIds.Lines: - - - - - - - - - - - - @foreach (var line in Record.Lines) - { - - - - - - - - } - -
@T["Pages.Catalog.Lines.Code"]@T["Pages.Catalog.Lines.Description"]@T["Pages.Catalog.Lines.Quantity"]@T["Pages.Catalog.Lines.Price"]@T["Pages.Catalog.Lines.Amount"]
@line.Code@line.Description@T.Number(line.Quantity ?? 0, 2)
+ break; case TabIds.Header: @@ -91,10 +71,88 @@ else } + + } @code { private int _saved; + private KhLinesGrid? _lines; + private SampleLine? _lookupLine; + private TaskCompletionSource? _lookupDone; + private IReadOnlyList>? _lineColumns; + + private IReadOnlyList> 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> 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(); + } /// public override IReadOnlyList Tabs => Record is null ? [] : StandardTabs(attachments: 2, links: 1); diff --git a/src/Khaemhat.Web/Components/Ui/KhGrid.razor b/src/Khaemhat.Web/Components/Ui/KhGrid.razor new file mode 100644 index 0000000..cf1274b --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhGrid.razor @@ -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. *@ +
+
+ + + + @if (Selectable) + { + + } + @foreach (var column in _columns) + { + var sort = SortOf(column); + + } + @if (RowMenu is not null) + { + + } + + + + @if (Virtual) + { + + @RowFragment(row) + + + } + else + { + @for (var i = 0; i < _pageItems.Count; i++) + { + @RowFragment(new GridRow(_pageOffset + i, _pageItems[i])) + } + } + @if (_loaded && _total == 0) + { + + } + + @if (HasTotals && _total > 0) + { + + + @if (Selectable) + { + + } + @for (var i = 0; i < _columns.Count; i++) + { + var column = _columns[i]; + + } + @if (RowMenu is not null) + { + + } + + + } +
+ + + @if (column.Sortable) + { + + } + else + { + @column.Title + } + @T["Ui.Grid.RowMenu"]
 
@(Empty ?? T["Ui.Grid.Empty"])
+ @if (column.Total && _totals.TryGetValue(column.Id, out var sum)) + { + @column.FormatValue(sum, T) + } + else if (i == 0) + { + @T["Ui.Grid.Total"] + } +
+
+ @if (ShowFooter) + { +
+ + @T.Format("Ui.Grid.Count", T.Number(_total)) + @if (_selected.Count > 0) + { + @(" · ")@T.Format("Ui.Grid.Selected", T.Number(_selected.Count)) + } + @Summary + + @if (!Virtual && PageCount > 1) + { + + } +
+ } + @if (_menu is { } menu && RowMenu is not null) + { +
+ + } +
+ + + +

@T["Ui.Grid.ColumnsHint"]

+
    + @for (var i = 0; i < _chooser.Count; i++) + { + var index = i; + var column = _chooser[i]; + var shown = !_hidden.Contains(column.Id); +
  • + + + +
  • + } +
+
+
+ + +
+
+ +@code { + private readonly Dictionary _loadedRows = []; + private readonly HashSet _selected = []; + private IReadOnlyList> _columns = []; + private List> _chooser = []; + private HashSet _hidden = new(StringComparer.Ordinal); + private List _sort = []; + private ListQuery? _lastQuery; + private IReadOnlyDictionary _totals = new Dictionary(); + private IReadOnlyList _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? _virtualize; + private ElementReference _wrap; + private ElementReference _menuRef; + private bool _placeMenu; + + /// The columns, in their default order. + [Parameter, EditorRequired] + public IReadOnlyList> Columns { get; set; } = []; + + /// Where the rows come from. + [Parameter, EditorRequired] + public ListSource Source { get; set; } = default!; + + /// The text of the search box of the radar. + [Parameter] + public string? Search { get; set; } + + /// The filters of the radar. + [Parameter] + public IReadOnlyList Filters { get; set; } = []; + + /// The ordering when the grid opens. + [Parameter] + public IReadOnlyList? Sort { get; set; } + + /// Called when the user changes the ordering. + [Parameter] + public EventCallback> SortChanged { get; set; } + + /// The key of a row, for the selection; required with . + [Parameter] + public Func? KeyOf { get; set; } + + /// Shows the selection boxes. + [Parameter] + public bool Selectable { get; set; } + + /// Called when the selection changes, with the keys. + [Parameter] + public EventCallback> SelectionChanged { get; set; } + + /// Reads the rows while scrolling (the default); otherwise a pager shows rows. + [Parameter] + public bool Virtual { get; set; } = true; + + /// The rows of a page, without . + [Parameter] + public int PageSize { get; set; } = 50; + + /// The height of the scrolling area, as CSS; none fills the parent (flex). + [Parameter] + public string? Height { get; set; } + + /// Called with the row on Enter or double click. + [Parameter] + public EventCallback OnOpen { get; set; } + + /// Called when the current row changes (keyboard or click). + [Parameter] + public EventCallback OnCurrent { get; set; } + + /// Extra classes of a row: hl highlights it. + [Parameter] + public Func? RowClass { get; set; } + + /// The commands of the row menu (right click, the context menu key, or the button at the end of the row). + [Parameter] + public Func>? RowMenu { get; set; } + + /// The id under which the column layout is saved for the user; none keeps the default layout. + [Parameter] + public string? LayoutKey { get; set; } + + /// The name of the exported files, without extension. + [Parameter] + public string? ExportName { get; set; } + + /// The label read by screen readers. + [Parameter] + public string? Label { get; set; } + + /// The text when there are no rows. + [Parameter] + public string? Empty { get; set; } + + /// Shows the bar under the grid with the counters. + [Parameter] + public bool ShowFooter { get; set; } = true; + + /// Extra content of the bar under the grid (totals of the visible rows...). + [Parameter] + public RenderFragment? Summary { get; set; } + + /// Extra classes. + [Parameter] + public string? Class { get; set; } + + /// The most rows an export writes. + public const int MaxExportRows = 100_000; + + /// The rows the request selects. + public long Total => _total; + + /// The keys of the selected rows. + public IReadOnlyCollection SelectedKeys => _selected; + + /// The current row, when it is loaded. + public TItem? CurrentItem => _current >= 0 && _loadedRows.TryGetValue(_current, out var item) ? item : default; + + /// The request the grid sends to its source, without the page. + 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 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; + } + } + } + + /// + 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; + } + + /// + 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); + } + } + + /// Reads the rows again from the first one, keeping the selection. + /// A task. + 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(); + } + + /// Moves the focus into the grid. + /// A task. + public async Task FocusAsync() + { + if (_current < 0 && _total > 0) + { + await SetCurrentAsync(0); + } + + await _wrap.FocusAsync(); + } + + /// Removes every selection. + /// A task. + public async Task ClearSelectionAsync() + { + _selected.Clear(); + await SelectionChanged.InvokeAsync(_selected); + } + + /// Opens the window that shows, hides and moves the columns. + public void ShowColumns() + { + _chooser = [.. Ordered()]; + _columnsOpen = true; + StateHasChanged(); + } + + /// + /// Writes every row the request selects (at most ) to a CSV for Excel (semicolons, + /// decimal comma) or an XLSX, and hands it to the browser. + /// + /// XLSX instead of CSV. + /// A task. + public async Task ExportAsync(bool xlsx) + { + var columns = _columns.Where(c => c.Export).ToList(); + var rows = new List(); + 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 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 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); + + @if (Selectable) + { + + + + } + @foreach (var column in _columns) + { + var editing = _editing is { } e && e.Index == row.Index && e.Column == column.Id; + + @if (editing) + { + + } + else if (column.Template is not null) + { + @column.Template(item) + } + else + { + @column.Format(item, T) + } + + } + @if (RowMenu is not null) + { + + + + } + + }; + + private string EditorId => "kh-gedit-" + GetHashCode().ToString(System.Globalization.CultureInfo.InvariantCulture); + + private static string? CellClass(KhColumn 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 column) => _sort.FirstOrDefault(s => s.Field == column.Id); + + private async ValueTask> ProvideAsync(ItemsProviderRequest request) + { + var count = Math.Clamp(request.Count, 1, ListQuery.MaxLimit); + ListPage page; + try + { + page = await Source(CurrentQuery.WithPage(request.StartIndex, count), request.CancellationToken); + } + catch (OperationCanceledException) + { + return new ItemsProviderResult([], (int)Math.Min(_total, int.MaxValue)); + } + + var rows = new List(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(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 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 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> 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(layout?.Hidden ?? Columns.Where(c => !c.Visible).Select(c => c.Id), StringComparer.Ordinal); + _columns = KhGridLayout.Apply(Columns, layout); + } + + private async Task ToggleColumnAsync(KhColumn 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(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()); + } + } + + /// + 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); +} diff --git a/src/Khaemhat.Web/Components/Ui/KhLinesGrid.razor b/src/Khaemhat.Web/Components/Ui/KhLinesGrid.razor new file mode 100644 index 0000000..05e4daa --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhLinesGrid.razor @@ -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. *@ +
+
+ + + + + @foreach (var column in Columns) + { + + } + @if (!ReadOnly) + { + + } + + + + @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; + + + @if (descriptive && DescriptionColumn is { } descriptionColumn) + { + var c = IndexOf(descriptionColumn); + + } + else + { + @for (var c = 0; c < Columns.Count; c++) + { + var column = Columns[c]; + + } + } + @if (!ReadOnly) + { + + } + + } + +
#@column.Title@T["Ui.Lines.Actions"]
@(pending ? null : (r + 1).ToString(T.Culture)) + @Cell(row, c, line, descriptionColumn) + + @if (column.IsEditable && !ReadOnly) + { + @Cell(row, c, line, column) + } + else + { + @Display(line, column) + } + + @if (!pending) + { + + } +
+
+ @if (!ReadOnly) + { +
+ + @if (NewDescriptive is not null) + { + + } + + @T["Ui.Radar.KeyEnter"] @T["Ui.Lines.HintNext"] + F4 @T["Ui.Lines.HintLookup"] + @T["Ui.Lines.KeyRemove"] @T["Ui.Lines.HintRemove"] +
+ } +
+ +@code { + private readonly Dictionary<(TLine Line, string Column), string> _typed = []; + private readonly HashSet<(TLine Line, string Column)> _errors = []; + private ElementReference _table; + private DotNetObjectReference>? _self; + private TLine? _pending; + + /// The lines; the grid adds and removes them in place. + [Parameter, EditorRequired] + public IList Lines { get; set; } = []; + + /// The columns. + [Parameter, EditorRequired] + public IReadOnlyList> Columns { get; set; } = []; + + /// Makes a new, empty line. + [Parameter, EditorRequired] + public Func NewLine { get; set; } = default!; + + /// Whether a line holds nothing yet (the waiting line becomes a line when this turns false). + [Parameter, EditorRequired] + public Func IsEmpty { get; set; } = default!; + + /// Whether a line is descriptive (text only). + [Parameter] + public Func? IsDescriptive { get; set; } + + /// Makes a descriptive line; none hides the button. + [Parameter] + public Func? NewDescriptive { get; set; } + + /// The column a descriptive line shows across the row. + [Parameter] + public KhLineColumn? DescriptionColumn { get; set; } + + /// No changes (an issued document). + [Parameter] + public bool ReadOnly { get; set; } + + /// Called after every change, to recompute the totals and mark the page modified. + [Parameter] + public EventCallback OnChanged { get; set; } + + /// The label read by screen readers. + [Parameter] + public string? Label { get; set; } + + /// Extra classes. + [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; + + /// + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (firstRender) + { + _self = DotNetObjectReference.Create(this); + await JS.InvokeVoidAsync("khaemhat.linesGrid", _table, _self); + } + } + + /// Moves the focus to a cell of a line (after a lookup, for example). + /// The line. + /// The column id. + /// A task. + 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)); + } + + /// Called by the browser on Ctrl+Down: a new line under the given one. + /// The row. + /// A task. + [JSInvokable] + public Task InsertAfterAsync(int row) + { + InsertAfter(row); + return Task.CompletedTask; + } + + /// Called by the browser on Ctrl+Canc. + /// The row. + /// A task. + [JSInvokable] + public Task RemoveAtAsync(int row) + { + RemoveAt(row); + return Task.CompletedTask; + } + + /// Called by the browser on F4 in a cell. + /// The row. + /// The column index. + /// A task. + [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 column) => __builder => + { + var key = (line, column.Id); + + }; + + private string Text(TLine line, KhLineColumn 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 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 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 column) => Columns.ToList().IndexOf(column); + + private async Task SetAsync(TLine line, KhLineColumn 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(); + } + + /// + public void Dispose() => _self?.Dispose(); +} diff --git a/src/Khaemhat.Web/Components/Ui/KhRadar.razor b/src/Khaemhat.Web/Components/Ui/KhRadar.razor new file mode 100644 index 0000000..e3c50d1 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhRadar.razor @@ -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. *@ +
+ @if (Toolbar is not null || ShowHints) + { +
+ @Toolbar +
+ @if (ShowHints) + { + F9 @T["Ui.Radar.HintRadar"] + @T["Ui.Radar.KeyEnter"] @(Picking ? T["Ui.Radar.HintPick"] : T["Ui.Radar.HintOpen"]) + @if (Selectable) + { + @T["Ui.Radar.KeySpace"] @T["Ui.Radar.HintSelect"] + } + } +
+ } +
+
+ + @foreach (var quick in QuickFilters) + { + var current = QuickValue(quick); +
+ + +
+ } + @foreach (var filter in _filters.Where(f => !IsQuick(f))) + { + + } + +
+ + + @if (!Picking) + { +
+ + @if (_exportOpen) + { +
+ + } +
+ } +
+ +
+
+ + + +
+
+ + +
+ @if (_builder.Column is { } picked) + { +
+ + +
+ @if (_builder.Operator is not (ListFilterOperator.IsEmpty or ListFilterOperator.IsNotEmpty)) + { + @if (picked.Choices is { } choices) + { +
+ @T["Ui.Radar.Values"] + @foreach (var choice in choices) + { + + } +
+ } + else if (picked.Kind == KhColumnKind.Bool) + { + + } + else if (picked.Kind == KhColumnKind.Date) + { + + @if (_builder.Operator == ListFilterOperator.Between) + { + + } + } + else if (picked.IsNumeric) + { + + @if (_builder.Operator == ListFilterOperator.Between) + { + + } + } + else + { + + } + } + } +
+
+
+ + +
+
+ + + + @if (_saved.Count == 0) + { +

@T["Ui.Radar.NoSaved"]

+ } + else + { +
    + @foreach (var saved in _saved) + { +
  • + + +
  • + } +
+ } +
+ +
+
+
+ + +
+
+ +@code { + private readonly FilterBuilder _builder = new(); + private KhGrid? _grid; + private ElementReference _searchBox; + private List _filters = []; + private List _sort = []; + private List _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; + + /// The id of the radar: the key of its saved filters and column layout. + [Parameter, EditorRequired] + public string Id { get; set; } = string.Empty; + + /// The columns. + [Parameter, EditorRequired] + public IReadOnlyList> Columns { get; set; } = []; + + /// Where the rows come from. + [Parameter, EditorRequired] + public ListSource Source { get; set; } = default!; + + /// The key of a row. + [Parameter] + public Func? KeyOf { get; set; } + + /// Shows the selection boxes. + [Parameter] + public bool Selectable { get; set; } = true; + + /// Called when the selection changes. + [Parameter] + public EventCallback> SelectionChanged { get; set; } + + /// Called with the row on Enter or double click. + [Parameter] + public EventCallback OnOpen { get; set; } + + /// Called when the current row changes. + [Parameter] + public EventCallback OnCurrent { get; set; } + + /// The drop-down filters of the bar. + [Parameter] + public IReadOnlyList QuickFilters { get; set; } = []; + + /// The filters when the radar opens. + [Parameter] + public IReadOnlyList? InitialFilters { get; set; } + + /// The search text when the radar opens (the text typed in a hotlink). + [Parameter] + public string? InitialSearch { get; set; } + + /// The ordering when the radar opens. + [Parameter] + public IReadOnlyList? InitialSort { get; set; } + + /// Extra classes of a row. + [Parameter] + public Func? RowClass { get; set; } + + /// The commands of the row menu. + [Parameter] + public Func>? RowMenu { get; set; } + + /// The commands above the radar (the page toolbar). + [Parameter] + public RenderFragment? Toolbar { get; set; } + + /// Extra content of the bar under the grid. + [Parameter] + public RenderFragment? Summary { get; set; } + + /// Shows the keyboard hints. + [Parameter] + public bool ShowHints { get; set; } = true; + + /// The radar picks a row for a field (in a dialog): Enter means "choose". + [Parameter] + public bool Picking { get; set; } + + /// Smaller spacing, for dialogs. + [Parameter] + public bool Compact { get; set; } + + /// The height of the rows area, as CSS. + [Parameter] + public string? Height { get; set; } + + /// The placeholder of the search box. + [Parameter] + public string? SearchPlaceholder { get; set; } + + /// The name of the exported files. + [Parameter] + public string? ExportName { get; set; } + + /// The label of the grid. + [Parameter] + public string? Label { get; set; } + + /// Extra classes. + [Parameter] + public string? Class { get; set; } + + /// The cascaded tab of the page, so that F9 only acts on the visible page. + [CascadingParameter] + public KhTab? Tab { get; set; } + + /// The grid. + public KhGrid? Grid => _grid; + + /// The current request: search, filters, ordering. + public ListQuery CurrentQuery => new() { Search = _appliedSearch, Filters = _filters, Sort = _sort }; + + private IEnumerable> 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); + + /// + 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)))]; + } + + /// + 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(); + } + } + } + + /// Moves the focus to the search box. + /// A task. + public async Task FocusSearchAsync() => await _searchBox.FocusAsync(); + + /// Reads the rows again. + /// A task. + 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? 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(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 column) => column.Kind == KhColumnKind.Money ? 2 : column.Decimals; + + private static IReadOnlyList OperatorsOf(KhColumn 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); + } + } + + /// + 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? 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 Choices { get; } = new(StringComparer.Ordinal); + + public void Reset(KhColumn? 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); + } + } +} diff --git a/src/Khaemhat.Web/Components/Ui/KhRadarDialog.razor b/src/Khaemhat.Web/Components/Ui/KhRadarDialog.razor new file mode 100644 index 0000000..4856278 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhRadarDialog.razor @@ -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. *@ + + + @if (Open) + { + + + } + +
+ @if (OnCreate.HasDelegate) + { + + } + @T["Ui.Radar.KeyEnter"] @T["Ui.Radar.HintPick"] @T["Ui.Radar.KeyEscape"] @T["Ui.Radar.HintClose"] + + +
+
+ +@code { + private KhRadar? _radar; + private TItem? _current; + + /// Whether the window is open. + [Parameter] + public bool Open { get; set; } + + /// Called when the window closes without a choice. + [Parameter] + public EventCallback OnClose { get; set; } + + /// Called with the row picked; the window closes. + [Parameter] + public EventCallback OnPick { get; set; } + + /// Called with the search text to create a row on the fly; none hides the button. + [Parameter] + public EventCallback OnCreate { get; set; } + + /// The title (Ricerca articolo). + [Parameter] + public string? Title { get; set; } + + /// The id of the radar, for saved filters and layout. + [Parameter, EditorRequired] + public string Id { get; set; } = string.Empty; + + /// The columns. + [Parameter, EditorRequired] + public IReadOnlyList> Columns { get; set; } = []; + + /// Where the rows come from. + [Parameter, EditorRequired] + public ListSource Source { get; set; } = default!; + + /// The key of a row. + [Parameter] + public Func? KeyOf { get; set; } + + /// The text the search starts from. + [Parameter] + public string? InitialSearch { get; set; } + + /// The filters the search starts from (only available items...). + [Parameter] + public IReadOnlyList? InitialFilters { get; set; } + + /// The drop-down filters. + [Parameter] + public IReadOnlyList 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); + } +} diff --git a/src/Khaemhat.Web/Components/_Imports.razor b/src/Khaemhat.Web/Components/_Imports.razor index 208fa06..1277013 100644 --- a/src/Khaemhat.Web/Components/_Imports.razor +++ b/src/Khaemhat.Web/Components/_Imports.razor @@ -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 diff --git a/src/Khaemhat.Web/Resources/it-IT/Pages.json b/src/Khaemhat.Web/Resources/it-IT/Pages.json index c908b22..9667b74 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Pages.json +++ b/src/Khaemhat.Web/Resources/it-IT/Pages.json @@ -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" } } } diff --git a/src/Khaemhat.Web/Resources/it-IT/Ui.json b/src/Khaemhat.Web/Resources/it-IT/Ui.json index 43557aa..47078a0 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Ui.json +++ b/src/Khaemhat.Web/Resources/it-IT/Ui.json @@ -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" } } } diff --git a/src/Khaemhat.Web/Ui/CatalogSamples.cs b/src/Khaemhat.Web/Ui/CatalogSamples.cs index a3be00f..697ceaf 100644 --- a/src/Khaemhat.Web/Ui/CatalogSamples.cs +++ b/src/Khaemhat.Web/Ui/CatalogSamples.cs @@ -1,3 +1,5 @@ +using Khaemhat.Application.Querying; + namespace Khaemhat.Web.Ui; /// A customer of the component catalog: fake data for the development page only. @@ -20,10 +22,73 @@ public sealed class SampleLine /// The unit price. public decimal? Price { get; set; } + /// The unit of measure. + public string? Unit { get; set; } + + /// The discount in percent. + public decimal? Discount { get; set; } + + /// Whether the line is only a text. + public bool Descriptive { get; set; } + /// The amount. - 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); + + /// Whether nothing was typed yet. + public bool IsEmpty => string.IsNullOrEmpty(Code) && string.IsNullOrEmpty(Description) && Quantity is null && Price is null; } +/// A customer of the radar of the component catalog: fake data. +public sealed class SampleCustomer +{ + /// The id. + public long Id { get; init; } + + /// The code. + public string Code { get; init; } = string.Empty; + + /// The name. + public string Name { get; init; } = string.Empty; + + /// The city. + public string City { get; init; } = string.Empty; + + /// The province. + public string Province { get; init; } = string.Empty; + + /// The agent, if any. + public string? Agent { get; init; } + + /// The kind: company, person, public. + public string Kind { get; init; } = "company"; + + /// The revenue of the year. + public decimal Revenue { get; init; } + + /// The amount overdue. + public decimal Overdue { get; init; } + + /// The credit limit (editable in the catalog). + public decimal Credit { get; set; } + + /// Customer since. + public DateOnly Since { get; init; } + + /// The state: active, blocked, disabled. + public string State { get; init; } = "active"; + + /// Whether marked as preferred. + public bool Vip { get; init; } +} + +/// An item for the lookup of the document lines in the catalog: fake data. +/// The code. +/// The description. +/// The unit. +/// The price. +/// The stock. +public sealed record SampleItem(string Code, string Description, string Unit, decimal Price, decimal Stock); + /// The sample document of the component catalog. public sealed class SampleDocument { @@ -82,15 +147,127 @@ public static class CatalogSamples return Task.FromResult(hits); } + /// The fields of the customer radar. + public static ListFields CustomerFields { get; } = new ListFields() + .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")); + + /// The fields of the item lookup. + public static ListFields ItemFields { get; } = new ListFields() + .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> CustomerSource = new(() => new(MakeCustomers(100_000), CustomerFields)); + private static readonly Lazy> ItemSource = new(() => new(MakeItems(), ItemFields)); + + /// The 100,000 customers of the radar. + /// The request. + /// Cancellation. + /// The page. + public static Task> CustomersAsync(ListQuery query, CancellationToken cancellationToken) => + CustomerSource.Value.QueryAsync(query, cancellationToken); + + /// The items of the lookup. + /// The request. + /// Cancellation. + /// The page. + public static Task> ItemsAsync(ListQuery query, CancellationToken cancellationToken) => + ItemSource.Value.QueryAsync(query, cancellationToken); + + /// Finds an item by its exact code. + /// The code. + /// The item, or . + 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)); + + /// Makes fake customers, always the same ones. + /// How many. + /// The customers. + public static IReadOnlyList 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(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; + } + + /// Makes the fake items. + /// The items. + public static IReadOnlyList 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(); + 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; + } + /// A new sample document. /// Today. /// The document. 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; } } diff --git a/src/Khaemhat.Web/Ui/KhGridModels.cs b/src/Khaemhat.Web/Ui/KhGridModels.cs new file mode 100644 index 0000000..558f58d --- /dev/null +++ b/src/Khaemhat.Web/Ui/KhGridModels.cs @@ -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; + +/// How a grid column shows its value (SPEC §10.7 KhGrid: typed columns). +public enum KhColumnKind +{ + /// Text. + Text = 0, + + /// A code: monospace, accent colour. + Code = 1, + + /// A number with decimals, right-aligned. + Number = 2, + + /// An amount in euro, right-aligned. + Money = 3, + + /// A date. + Date = 4, + + /// Yes or no. + Bool = 5, +} + +/// +/// A column of a KhGrid or KhRadar. is also the field of that +/// sorts and filters it (when ), and the key of its total in . +/// +/// The row type. +/// The id. +/// The title (a text from the resources). +/// The value of a row, used for display, export and editing. +public sealed class KhColumn(string id, string title, Func value) +{ + /// The id. + public string Id { get; } = id; + + /// The title. + public string Title { get; } = title; + + /// The value of a row. + public Func Value { get; } = value; + + /// How the value is shown. + public KhColumnKind Kind { get; init; } + + /// The decimals of a . + public int Decimals { get; init; } + + /// The width, as CSS (110px, 12ch); none lets the table decide. + public string? Width { get; init; } + + /// Whether the header sorts the rows. + public bool Sortable { get; init; } = true; + + /// Whether the column is shown until the user changes the layout. + public bool Visible { get; init; } = true; + + /// Whether the totals row shows the sum the source returned for this column. + public bool Total { get; init; } + + /// Whether the column goes in the exported files. + public bool Export { get; init; } = true; + + /// The cell content, instead of the formatted value (badges, links). + public RenderFragment? Template { get; init; } + + /// Extra classes of a cell, for highlights (neg for a red amount). + public Func? CellClass { get; init; } + + /// + /// Makes the cell editable in place (double click or F2): receives the row and the text typed and returns an error + /// message, or when the value was saved. + /// + public Func>? Edit { get; init; } + + /// The values a filter on this column can take (states, types); none for a free value. + public IReadOnlyList>? Choices { get; init; } + + /// Whether the value is a number aligned right. + public bool IsNumeric => Kind is KhColumnKind.Number or KhColumnKind.Money; + + /// The value of a row as text, in the culture of the texts. + /// The row. + /// The texts. + /// The text. + public string Format(TItem item, ITexts texts) => FormatValue(Value(item), texts); + + /// A value of this column as text. + /// The value. + /// The texts. + /// The text. + 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, + }; + } +} + +/// The columns a user keeps and their order, saved in the user settings per grid. +/// The column ids in order. +/// The hidden column ids. +public sealed record KhGridLayout(IReadOnlyList Order, IReadOnlyList Hidden) +{ + private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); + + /// The key of the setting of a grid. + /// The grid id. + /// The key. + public static string KeyOf(string grid) => "grid." + grid + ".layout"; + + /// Reads a saved layout; anything unreadable gives (the default layout). + /// The setting. + /// The layout. + public static KhGridLayout? Parse(string? json) + { + if (string.IsNullOrWhiteSpace(json)) + { + return null; + } + + try + { + return JsonSerializer.Deserialize(json, Json); + } + catch (JsonException) + { + return null; + } + } + + /// The layout as JSON. + /// The JSON. + public string ToJson() => JsonSerializer.Serialize(this, Json); + + /// The columns to show, in order: saved order first, columns added since then at their place. + /// The row type. + /// The columns of the grid. + /// The saved layout, or . + /// The visible columns. + public static IReadOnlyList> Apply(IReadOnlyList> 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))), + ]; + } +} + +/// Filters, search and ordering a user saved on a radar under a name. +/// The name. +/// The text of the search box. +/// The filters. +/// The ordering. +public sealed record KhSavedFilter(string Name, string? Search, IReadOnlyList Filters, IReadOnlyList Sort) +{ + private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); + + /// The most filters kept per radar. + public const int MaxCount = 30; + + /// The key of the setting of a radar. + /// The radar id. + /// The key. + public static string KeyOf(string radar) => "radar." + radar + ".filters"; + + /// Reads the saved filters; anything unreadable gives none. + /// The setting. + /// The filters. + public static IReadOnlyList ParseAll(string? json) + { + if (string.IsNullOrWhiteSpace(json)) + { + return []; + } + + try + { + return JsonSerializer.Deserialize>(json, Json) ?? []; + } + catch (JsonException) + { + return []; + } + } + + /// The saved filters as JSON. + /// The filters. + /// The JSON. + public static string ToJson(IEnumerable filters) => JsonSerializer.Serialize(filters.Take(MaxCount).ToList(), Json); +} + +/// A filter of the bar of a radar shown as a drop-down (Tipo, Agente, Stato in mockup 012). +/// The field id. +/// The label. +/// The values (invariant text) and their labels; the first empty value means "all". +public sealed record KhQuickFilter(string Field, string Label, IReadOnlyList> Options); + +/// A column of a KhLinesGrid (the lines of a document, SPEC §10.5). +/// The line type. +/// The id. +/// The title. +/// The value of a line. +public sealed class KhLineColumn(string id, string title, Func value) +{ + /// The id. + public string Id { get; } = id; + + /// The title. + public string Title { get; } = title; + + /// The value of a line. + public Func Value { get; } = value; + + /// How the value is shown and typed. + public KhColumnKind Kind { get; init; } + + /// The decimals of a number (two for amounts). + public int Decimals { get; init; } = 2; + + /// The width, as CSS. + public string? Width { get; init; } + + /// Saves a text typed in the cell; none with makes the cell read-only. + public Action? SetText { get; init; } + + /// Saves a number typed in the cell (Italian format, inline calculation). + public Action? SetNumber { get; init; } + + /// Opens the lookup of the cell (F4): the radar of the items for the code. + public Func? Lookup { get; init; } + + /// Whether the cell can be typed in. + public bool IsEditable => SetText is not null || SetNumber is not null; + + /// Whether the value is a number aligned right. + public bool IsNumeric => Kind is KhColumnKind.Number or KhColumnKind.Money; +} diff --git a/src/Khaemhat.Web/wwwroot/css/interactive.css b/src/Khaemhat.Web/wwwroot/css/interactive.css index 39def1d..b6da1e8 100644 --- a/src/Khaemhat.Web/wwwroot/css/interactive.css +++ b/src/Khaemhat.Web/wwwroot/css/interactive.css @@ -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); } diff --git a/src/Khaemhat.Web/wwwroot/js/khaemhat.js b/src/Khaemhat.Web/wwwroot/js/khaemhat.js index 7c7546c..d1ec203 100644 --- a/src/Khaemhat.Web/wwwroot/js/khaemhat.js +++ b/src/Khaemhat.Web/wwwroot/js/khaemhat.js @@ -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; diff --git a/tests/Khaemhat.Application.Tests/Khaemhat.Application.Tests.csproj b/tests/Khaemhat.Application.Tests/Khaemhat.Application.Tests.csproj index 1087861..56cd603 100644 --- a/tests/Khaemhat.Application.Tests/Khaemhat.Application.Tests.csproj +++ b/tests/Khaemhat.Application.Tests/Khaemhat.Application.Tests.csproj @@ -6,6 +6,7 @@ + diff --git a/tests/Khaemhat.Application.Tests/ListQueryTests.cs b/tests/Khaemhat.Application.Tests/ListQueryTests.cs new file mode 100644 index 0000000..7157350 --- /dev/null +++ b/tests/Khaemhat.Application.Tests/ListQueryTests.cs @@ -0,0 +1,157 @@ +using Khaemhat.Application.Querying; +using Khaemhat.Data.Mapping; +using Khaemhat.Data.Querying; +using Khaemhat.Data.Sqlite; + +namespace Khaemhat.Application.Tests; + +/// The request of grids and radars, run in memory and translated to SQL (issue #28). +[TestClass] +public sealed class ListQueryTests +{ + private static readonly ListFields Fields = new ListFields() + .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(() => new ListFields().Add("amount", x => x.Amount, searchable: true)); + Assert.ThrowsExactly(() => new ListFields().Add("name", x => x.Name, total: true)); + } + + [TestMethod] + public void Sql_UsesLikeParametersOrderAndPage() + { + var map = new ListRowMap(); + var query = Fields.Apply(Query.For(), 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(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(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 + { + public ListRowMap() => ToTable("list_rows"); + } +}