feat: Kh component library, record pages and profile security (M3, part 2)

Adds the building blocks every later screen uses, so modules are built from
one set of components instead of ad hoc markup:

- Form components (KhForm, KhTextBox, KhNumberBox, KhDateBox, KhSelect,
  KhCheck, KhSwitch, KhHotlink) with Italian number and date input, inline
  calculation (=10*3), field messages plus a summary that focuses the field,
  and service errors added by field name.
- Display and window components (panels, tiles, badges, chips, money, tabs
  with Alt+1..9, steps, dialog, side drawer and DrawerService).
- KhIconToolbar that keeps one line and moves less used commands into the
  "..." menu, KhDocHead, and the RecordPage/DocumentPage/MasterDataPage bases
  with standard commands, shortcuts and save/cancel/delete flow (#27, #29).
- Development-only component catalog and sample document page.
- Profile: personal data, password change that ends other sessions, TOTP
  enable/disable and recovery codes through ProfileService (#31).

Refs #27 #29 #31

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 18:11:16 +01:00
1 parent cf6f849cc1
commit d958e7372d
57 files changed
+5249 -12

No files matched your search

+96
View File
@@ -0,0 +1,96 @@
namespace Khaemhat.Web.Ui;
/// <summary>A customer of the component catalog: fake data for the development page only.</summary>
/// <param name="Code">The code.</param>
/// <param name="Name">The name.</param>
public sealed record SampleParty(string Code, string Name);
/// <summary>A line of the sample document of the component catalog.</summary>
public sealed class SampleLine
{
/// <summary>The item code.</summary>
public string Code { get; set; } = string.Empty;
/// <summary>The description.</summary>
public string Description { get; set; } = string.Empty;
/// <summary>The quantity.</summary>
public decimal? Quantity { get; set; }
/// <summary>The unit price.</summary>
public decimal? Price { get; set; }
/// <summary>The amount.</summary>
public decimal Amount => Math.Round((Quantity ?? 0) * (Price ?? 0), 2, MidpointRounding.AwayFromZero);
}
/// <summary>The sample document of the component catalog.</summary>
public sealed class SampleDocument
{
/// <summary>The number.</summary>
public string Number { get; set; } = string.Empty;
/// <summary>The date.</summary>
public DateOnly? Date { get; set; }
/// <summary>The customer.</summary>
public SampleParty? Party { get; set; }
/// <summary>The discount in percent.</summary>
public decimal? Discount { get; set; }
/// <summary>The notes.</summary>
public string? Notes { get; set; }
/// <summary>Whether it is issued (read-only).</summary>
public bool Issued { get; set; }
/// <summary>The lines.</summary>
public List<SampleLine> Lines { get; } = [];
/// <summary>The taxable amount.</summary>
public decimal Taxable => Math.Round(Lines.Sum(l => l.Amount) * (1 - ((Discount ?? 0) / 100)), 2, MidpointRounding.AwayFromZero);
/// <summary>The VAT at 22%.</summary>
public decimal Vat => Math.Round(Taxable * 0.22m, 2, MidpointRounding.AwayFromZero);
/// <summary>The total.</summary>
public decimal Total => Taxable + Vat;
}
/// <summary>Fake data for the component catalog (development only): no real company or person.</summary>
public static class CatalogSamples
{
/// <summary>The customers.</summary>
public static IReadOnlyList<SampleParty> Parties { get; } =
[
new("C0001", "Esempio Uno Srl"),
new("C0002", "Esempio Due Spa"),
new("C0003", "Prova Tre Snc"),
new("C0010", "Cliente Dimostrativo"),
new("C0011", "Officine di Prova"),
new("C0020", "Studio Fittizio Associato"),
];
/// <summary>Finds customers by code or name, like a hotlink search.</summary>
/// <param name="text">The text.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>At most eight customers.</returns>
public static Task<IReadOnlyList<SampleParty>> SearchAsync(string text, CancellationToken cancellationToken)
{
IReadOnlyList<SampleParty> hits = [.. Parties.Where(p => p.Code.Contains(text, StringComparison.OrdinalIgnoreCase) || p.Name.Contains(text, StringComparison.OrdinalIgnoreCase)).Take(8)];
return Task.FromResult(hits);
}
/// <summary>A new sample document.</summary>
/// <param name="today">Today.</param>
/// <returns>The document.</returns>
public static SampleDocument Document(DateOnly today)
{
var document = new SampleDocument { Number = "2026/000123", Date = today, Party = Parties[0], Discount = 0 };
document.Lines.Add(new SampleLine { Code = "ART-001", Description = "Articolo di prova", Quantity = 10, Price = 12.5m });
document.Lines.Add(new SampleLine { Code = "ART-002", Description = "Servizio dimostrativo", Quantity = 1, Price = 340m });
document.Lines.Add(new SampleLine { Code = "ART-003", Description = "Materiale fittizio", Quantity = 4.5m, Price = 8.9m });
return document;
}
}
+293
View File
@@ -0,0 +1,293 @@
using System.Globalization;
namespace Khaemhat.Web.Ui;
/// <summary>
/// Reads numbers typed the Italian way (SPEC §10.7 <c>KhNumberBox</c>): comma for decimals, point for thousands, and
/// an inline calculation when the text starts with <c>=</c> (<c>=10*3</c>, <c>=(120+80)/4</c>). A single point
/// followed by other than three digits is taken as a decimal point, because the numeric keypad types it.
/// </summary>
public static class ItalianNumber
{
/// <summary>Reads a number or an inline calculation.</summary>
/// <param name="text">The text typed.</param>
/// <param name="value">The value.</param>
/// <returns><see langword="true"/> when the text is a number, a valid calculation, or empty (value <see langword="null"/>).</returns>
public static bool TryParse(string? text, out decimal? value)
{
value = null;
var trimmed = text?.Trim() ?? string.Empty;
if (trimmed.Length == 0)
{
return true;
}
if (trimmed[0] == '=')
{
if (InlineCalculator.TryEvaluate(trimmed[1..], out var result))
{
value = result;
return true;
}
return false;
}
if (TryParseNumber(trimmed.Replace(" ", string.Empty, StringComparison.Ordinal).Replace("€", string.Empty, StringComparison.Ordinal), out var number))
{
value = number;
return true;
}
return false;
}
/// <summary>Formats a value for the field: thousands separator and exactly <paramref name="decimals"/> decimals.</summary>
/// <param name="value">The value.</param>
/// <param name="decimals">The decimals shown.</param>
/// <param name="culture">The culture.</param>
/// <returns>The text.</returns>
public static string Format(decimal? value, int decimals, CultureInfo culture) =>
value is { } v ? v.ToString("N" + decimals.ToString(CultureInfo.InvariantCulture), culture) : string.Empty;
/// <summary>Reads one number written with Italian separators.</summary>
/// <param name="text">The text, without spaces.</param>
/// <param name="value">The value.</param>
/// <returns>Whether it is a number.</returns>
internal static bool TryParseNumber(string text, out decimal value)
{
value = 0;
if (text.Length == 0 || text.Any(c => !(char.IsAsciiDigit(c) || c is '.' or ',' or '-' or '+')))
{
return false;
}
string normalized;
var points = text.Count(c => c == '.');
if (text.Contains(',', StringComparison.Ordinal))
{
// 1.234,56: points are thousands, the comma is the decimal separator.
if (text.Count(c => c == ',') > 1)
{
return false;
}
normalized = text.Replace(".", string.Empty, StringComparison.Ordinal).Replace(',', '.');
}
else if (points == 1 && !IsThousands(text))
{
normalized = text; // 10.5 from the numeric keypad.
}
else
{
normalized = text.Replace(".", string.Empty, StringComparison.Ordinal);
}
return decimal.TryParse(normalized, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out value);
}
// "1.234" and "12.345": exactly three digits after the only point.
private static bool IsThousands(string text)
{
var index = text.IndexOf('.', StringComparison.Ordinal);
var after = text.Length - index - 1;
return after == 3 && index > 0 && text[..index].TrimStart('-', '+').Length is > 0 and <= 3;
}
}
/// <summary>
/// The four operations with parentheses and unary minus, for the inline calculation of number fields. Numbers follow
/// <see cref="ItalianNumber"/>. No variables, no functions: a small recursive-descent parser over decimals.
/// </summary>
public static class InlineCalculator
{
/// <summary>Evaluates an expression.</summary>
/// <param name="expression">The expression, without the leading <c>=</c>.</param>
/// <param name="value">The result.</param>
/// <returns>Whether the expression is valid (division by zero is not).</returns>
public static bool TryEvaluate(string expression, out decimal value)
{
ArgumentNullException.ThrowIfNull(expression);
var parser = new Parser(expression.Replace(" ", string.Empty, StringComparison.Ordinal).Replace('x', '*').Replace('X', '*').Replace(':', '/'));
try
{
value = parser.Expression();
return parser.AtEnd;
}
catch (Exception ex) when (ex is FormatException or DivideByZeroException or OverflowException)
{
value = 0;
return false;
}
}
private sealed class Parser(string text)
{
private int _position;
public bool AtEnd => _position == text.Length;
public decimal Expression()
{
var value = Term();
while (!AtEnd && text[_position] is '+' or '-')
{
var op = text[_position++];
var right = Term();
value = op == '+' ? value + right : value - right;
}
return value;
}
private decimal Term()
{
var value = Factor();
while (!AtEnd && text[_position] is '*' or '/')
{
var op = text[_position++];
var right = Factor();
value = op == '*' ? value * right : value / right;
}
return value;
}
private decimal Factor()
{
if (AtEnd)
{
throw new FormatException("Unexpected end.");
}
switch (text[_position])
{
case '-':
_position++;
return -Factor();
case '+':
_position++;
return Factor();
case '(':
_position++;
var inner = Expression();
if (AtEnd || text[_position] != ')')
{
throw new FormatException("Missing parenthesis.");
}
_position++;
return inner;
}
var start = _position;
while (!AtEnd && (char.IsAsciiDigit(text[_position]) || text[_position] is '.' or ','))
{
_position++;
}
return start < _position && ItalianNumber.TryParseNumber(text[start.._position], out var number)
? number
: throw new FormatException("Number expected.");
}
}
}
/// <summary>
/// Reads dates typed the Italian way (SPEC §10.7 <c>KhDateBox</c>): <c>gg/mm/aaaa</c> and its short forms (<c>5</c>,
/// <c>5/3</c>, <c>050326</c>, <c>5-3-26</c>), <c>T</c> today, <c>F</c> end of month, <c>+</c>/<c>-</c> one day,
/// <c>+7</c>/<c>-30</c> days from the current value (or today).
/// </summary>
public static class ItalianDate
{
private static readonly char[] Separators = ['/', '-', '.', ' '];
/// <summary>Reads a date.</summary>
/// <param name="text">The text typed.</param>
/// <param name="today">Today.</param>
/// <param name="current">The value before the change, the base of <c>F</c> and of relative days.</param>
/// <param name="value">The date; <see langword="null"/> when the text is empty.</param>
/// <returns>Whether the text is a date or empty.</returns>
public static bool TryParse(string? text, DateOnly today, DateOnly? current, out DateOnly? value)
{
value = null;
var trimmed = text?.Trim().ToUpperInvariant() ?? string.Empty;
if (trimmed.Length == 0)
{
return true;
}
var baseDate = current ?? today;
switch (trimmed)
{
case "T" or "O":
value = today;
return true;
case "F":
value = new DateOnly(baseDate.Year, baseDate.Month, DateTime.DaysInMonth(baseDate.Year, baseDate.Month));
return true;
case "I":
value = new DateOnly(baseDate.Year, baseDate.Month, 1);
return true;
case "+":
value = baseDate.AddDays(1);
return true;
case "-":
value = baseDate.AddDays(-1);
return true;
}
if (trimmed[0] is '+' or '-' && int.TryParse(trimmed, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var days) && Math.Abs(days) <= 36_500)
{
value = baseDate.AddDays(days);
return true;
}
var parts = trimmed.Split(Separators, StringSplitOptions.RemoveEmptyEntries);
if (parts.Any(p => !p.All(char.IsAsciiDigit)))
{
return false;
}
if (parts.Length == 1)
{
parts = parts[0].Length switch
{
<= 2 => [parts[0]],
4 => [parts[0][..2], parts[0][2..]],
6 => [parts[0][..2], parts[0][2..4], parts[0][4..]],
8 => [parts[0][..2], parts[0][2..4], parts[0][4..]],
_ => [],
};
}
if (parts.Length is 0 or > 3 || parts.Any(p => p.Length > 4))
{
return false;
}
var day = int.Parse(parts[0], CultureInfo.InvariantCulture);
var month = parts.Length > 1 ? int.Parse(parts[1], CultureInfo.InvariantCulture) : today.Month;
var year = parts.Length > 2 ? YearOf(parts[2], today) : today.Year;
if (year is < 1900 or > 2999 || month is < 1 or > 12 || day < 1 || day > DateTime.DaysInMonth(year, month))
{
return false;
}
value = new DateOnly(year, month, day);
return true;
}
// Two digits: this century, unless that is more than twenty years ahead (birth dates, old documents).
private static int YearOf(string text, DateOnly today)
{
var year = int.Parse(text, CultureInfo.InvariantCulture);
if (text.Length > 2)
{
return year;
}
var century = today.Year / 100 * 100;
return century + year > today.Year + 20 ? century - 100 + year : century + year;
}
}
+311
View File
@@ -0,0 +1,311 @@
using System.Globalization;
using Khaemhat.Application.Localization;
using Microsoft.AspNetCore.Components;
namespace Khaemhat.Web.Ui;
/// <summary>One message of the validation: the field it belongs to (or none for the whole form) and the text.</summary>
/// <param name="Field">The field name, or <see langword="null"/>.</param>
/// <param name="Label">The label of the field, shown in the summary.</param>
/// <param name="InputId">The element to focus from the summary.</param>
/// <param name="Message">The message.</param>
public sealed record KhValidationMessage(string? Field, string? Label, string? InputId, string Message);
/// <summary>
/// The messages of a form (SPEC §10.5.6: next to the field and in a summary). The fields add theirs when the form is
/// submitted; the page adds the ones the services return (<see cref="Add"/>), then the form shows them.
/// </summary>
public sealed class KhValidation
{
private readonly List<KhValidationMessage> _messages = [];
/// <summary>Raised when the messages change.</summary>
public event Action? Changed;
/// <summary>Every message, in the order added.</summary>
public IReadOnlyList<KhValidationMessage> Messages => _messages;
/// <summary>Whether there are no messages.</summary>
public bool IsValid => _messages.Count == 0;
/// <summary>Adds a message.</summary>
/// <param name="field">The field name, or <see langword="null"/> for the whole form.</param>
/// <param name="message">The message.</param>
public void Add(string? field, string message)
{
ArgumentException.ThrowIfNullOrWhiteSpace(message);
_messages.Add(new KhValidationMessage(field, null, null, message));
Changed?.Invoke();
}
/// <summary>The messages of a field.</summary>
/// <param name="field">The field name.</param>
/// <returns>The messages.</returns>
public IReadOnlyList<string> For(string field) => [.. _messages.Where(m => m.Field == field).Select(m => m.Message)];
/// <summary>Removes the messages of a field, when the user changes it.</summary>
/// <param name="field">The field name.</param>
public void ClearField(string field)
{
if (_messages.RemoveAll(m => m.Field == field) > 0)
{
Changed?.Invoke();
}
}
/// <summary>Removes every message.</summary>
public void Clear()
{
if (_messages.Count > 0)
{
_messages.Clear();
Changed?.Invoke();
}
}
internal void AddResolved(KhValidationMessage message) => _messages.Add(message);
internal void Notify() => Changed?.Invoke();
}
/// <summary>A field that takes part in the validation of a <c>KhForm</c>.</summary>
public interface IKhField
{
/// <summary>The name of the field: the key of its messages.</summary>
string FieldName { get; }
/// <summary>The label, shown in the summary.</summary>
string? Label { get; }
/// <summary>The id of the input element.</summary>
string InputId { get; }
/// <summary>Checks the value: required, readable, field rule.</summary>
/// <returns>The messages; empty when valid.</returns>
IEnumerable<string> Validate();
}
/// <summary>What a <c>KhForm</c> gives its fields: the messages, read-only state and the list of fields.</summary>
public sealed class KhFormContext
{
private readonly List<IKhField> _fields = [];
/// <summary>Creates the context.</summary>
/// <param name="validation">The messages of the form.</param>
public KhFormContext(KhValidation validation) => Validation = validation;
/// <summary>The messages.</summary>
public KhValidation Validation { get; }
/// <summary>Every field is read-only (an issued invoice, SPEC §10.5.6).</summary>
public bool ReadOnly { get; internal set; }
/// <summary>Adds a field.</summary>
/// <param name="field">The field.</param>
public void Register(IKhField field) => _fields.Add(field);
/// <summary>Removes a field.</summary>
/// <param name="field">The field.</param>
public void Unregister(IKhField field) => _fields.Remove(field);
/// <summary>Checks every field and puts the messages in <see cref="Validation"/>.</summary>
/// <returns>Whether the form is valid.</returns>
public bool Validate()
{
Validation.Clear();
foreach (var field in _fields)
{
foreach (var message in field.Validate())
{
Validation.AddResolved(new KhValidationMessage(field.FieldName, field.Label, field.InputId, message));
}
}
Validation.Notify();
return Validation.IsValid;
}
/// <summary>The label and input of a field, to complete the messages the page added.</summary>
/// <param name="name">The field name.</param>
/// <returns>The field, or <see langword="null"/>.</returns>
public IKhField? Find(string? name) => name is null ? null : _fields.FirstOrDefault(f => f.FieldName == name);
}
/// <summary>
/// The base of the input components (<c>KhTextBox</c>, <c>KhNumberBox</c>, <c>KhDateBox</c>...): value binding, label,
/// hint, required mark, read-only state from the form, messages next to the field and validation.
/// </summary>
/// <typeparam name="TValue">The type of the value.</typeparam>
public abstract class KhInputBase<TValue> : ComponentBase, IKhField, IDisposable
{
private static int _next;
private KhFormContext? _registered;
/// <summary>The texts (components also get them as <c>T</c> from <c>_Imports.razor</c>).</summary>
[Inject]
protected ITexts Texts { get; set; } = default!;
/// <summary>The value.</summary>
[Parameter]
public TValue? Value { get; set; }
/// <summary>Called when the user changes the value.</summary>
[Parameter]
public EventCallback<TValue?> ValueChanged { get; set; }
/// <summary>The label above the field.</summary>
[Parameter]
public string? Label { get; set; }
/// <summary>The name of the field for the messages; defaults to the label.</summary>
[Parameter]
public string? Name { get; set; }
/// <summary>A suggestion under the field.</summary>
[Parameter]
public string? Hint { get; set; }
/// <summary>The value is mandatory: asterisk and check.</summary>
[Parameter]
public bool Required { get; set; }
/// <summary>The field cannot be changed.</summary>
[Parameter]
public bool ReadOnly { get; set; }
/// <summary>The field is disabled.</summary>
[Parameter]
public bool Disabled { get; set; }
/// <summary>The columns of the 12-column grid the field takes (SPEC §10.5.4).</summary>
[Parameter]
public int Span { get; set; } = 6;
/// <summary>An extra rule: returns a message, or <see langword="null"/> when the value is good.</summary>
[Parameter]
public Func<TValue?, string?>? Rule { get; set; }
/// <summary>The id of the input; generated when not given.</summary>
[Parameter]
public string? Id { get; set; }
/// <summary>Other attributes for the input element.</summary>
[Parameter(CaptureUnmatchedValues = true)]
public IReadOnlyDictionary<string, object>? Attributes { get; set; }
/// <summary>The form the field is in.</summary>
[CascadingParameter]
public KhFormContext? Form { get; set; }
/// <inheritdoc />
public string FieldName => Name ?? Label ?? InputId;
/// <inheritdoc />
public string InputId { get; private set; } = string.Empty;
/// <summary>Whether the user may change the value.</summary>
protected bool IsReadOnly => ReadOnly || Form?.ReadOnly == true;
/// <summary>The message of a text that could not be read (a date such as 31/02), until the user fixes it.</summary>
protected string? ParseError { get; set; }
/// <summary>The messages shown next to the field.</summary>
protected IReadOnlyList<string> Messages =>
ParseError is not null ? [ParseError] : Form?.Validation.For(FieldName) ?? [];
/// <summary>The id of the hint and messages, for <c>aria-describedby</c>.</summary>
protected string DescribedBy => InputId + "-d";
/// <summary>The <c>aria-invalid</c> value: "true" with messages, absent otherwise (a bare attribute is not "true").</summary>
protected string? AriaInvalid => Messages.Count > 0 ? "true" : null;
/// <summary>The <c>aria-required</c> value.</summary>
protected string? AriaRequired => Required ? "true" : null;
/// <summary>The CSS classes of the input: error state.</summary>
protected string InputClass => Messages.Count > 0 ? "in err" : "in";
/// <inheritdoc />
protected override void OnParametersSet()
{
if (InputId.Length == 0)
{
InputId = Id ?? "kh-i" + Interlocked.Increment(ref _next).ToString(CultureInfo.InvariantCulture);
}
if (!ReferenceEquals(_registered, Form))
{
_registered?.Unregister(this);
Form?.Register(this);
_registered = Form;
}
}
/// <summary>Whether the value counts as empty for <see cref="Required"/>.</summary>
/// <param name="value">The value.</param>
/// <returns><see langword="true"/> when empty.</returns>
protected virtual bool IsEmpty(TValue? value) => value is null || (value is string s && string.IsNullOrWhiteSpace(s));
/// <inheritdoc />
public virtual IEnumerable<string> Validate()
{
if (ParseError is not null)
{
yield return ParseError;
yield break;
}
if (Required && IsEmpty(Value))
{
yield return Texts["Ui.Validation.Required"];
yield break;
}
if (Rule?.Invoke(Value) is { } message)
{
yield return message;
}
}
/// <summary>Changes the value, tells the parent and clears the messages of the field.</summary>
/// <param name="value">The new value.</param>
/// <returns>A task.</returns>
protected async Task SetValueAsync(TValue? value)
{
ParseError = null;
Form?.Validation.ClearField(FieldName);
if (EqualityComparer<TValue>.Default.Equals(Value!, value!))
{
return;
}
Value = value;
await ValueChanged.InvokeAsync(value);
}
/// <inheritdoc />
public void Dispose()
{
_registered?.Unregister(this);
GC.SuppressFinalize(this);
}
}
/// <summary>How a <c>KhForm</c> arranges its children.</summary>
public enum KhFormLayout
{
/// <summary>The 12-column grid of fields (<c>.form</c>).</summary>
Grid = 0,
/// <summary>Groups of fields side by side (<c>.fgroups</c>), each a <c>KhFieldGroup</c>.</summary>
Groups = 1,
/// <summary>The grid without padding, inside a panel that already has it.</summary>
Plain = 2,
}
/// <summary>A choice of a <c>KhSelect</c>.</summary>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="Value">The value.</param>
/// <param name="Text">The text shown.</param>
public sealed record KhOption<TValue>(TValue Value, string Text);
+104
View File
@@ -0,0 +1,104 @@
namespace Khaemhat.Web.Ui;
/// <summary>The colour of a tile, badge, chip or value: the meaning, not the hue (the theme picks the hue).</summary>
public enum KhTone
{
/// <summary>Neutral.</summary>
Neutral = 0,
/// <summary>The accent of the user.</summary>
Accent = 1,
/// <summary>Information.</summary>
Info = 2,
/// <summary>Good: paid, sent, done.</summary>
Ok = 3,
/// <summary>Attention: expiring, to check.</summary>
Warning = 4,
/// <summary>Problem: overdue, rejected.</summary>
Error = 5,
}
/// <summary>One value of a <c>KhStrip</c>.</summary>
/// <param name="Label">The label above.</param>
/// <param name="Value">The value.</param>
/// <param name="Tone">The colour of the value.</param>
public sealed record KhStat(string Label, string Value, KhTone Tone = KhTone.Neutral);
/// <summary>One tab of a <c>KhTabs</c>.</summary>
/// <param name="Id">The identifier (also the query value when the tabs are links).</param>
/// <param name="Icon">The icon.</param>
/// <param name="Text">The text.</param>
/// <param name="Count">A counter after the text: attachments (3), links (2).</param>
public sealed record KhTabItem(string Id, string Icon, string Text, int? Count = null);
/// <summary>One step of a <c>KhSteps</c> or <c>KhVSteps</c>.</summary>
/// <param name="Title">The title.</param>
/// <param name="Detail">The line under the title (vertical steps only).</param>
public sealed record KhStep(string Title, string? Detail = null);
/// <summary>Where a toolbar command sits.</summary>
public enum ToolbarKind
{
/// <summary>An icon button (32x32, tooltip with name and shortcut).</summary>
Icon = 0,
/// <summary>A contextual action of the document: icon and a short label, at most four on the bar.</summary>
Action = 1,
/// <summary>Only in the "⋯" menu.</summary>
Menu = 2,
}
/// <summary>
/// A command of a <c>KhIconToolbar</c> (SPEC §10.4). Commands of the same <see cref="Group"/> stand together with a
/// separator between groups; <see cref="End"/> puts them on the right (radar, previous, next). When the bar is too
/// narrow, the commands with the highest <see cref="Priority"/> move to the "⋯" menu first.
/// </summary>
/// <param name="Id">The identifier.</param>
/// <param name="Icon">The icon.</param>
/// <param name="Text">The name: tooltip and accessible name of icons, label of actions and menu entries.</param>
public sealed record ToolbarItem(string Id, string Icon, string Text)
{
/// <summary>The kind.</summary>
public ToolbarKind Kind { get; init; }
/// <summary>The shortcut shown in the tooltip, such as <c>Ctrl+S</c>.</summary>
public string? Shortcut { get; init; }
/// <summary>What the command does.</summary>
public Func<Task>? OnClick { get; init; }
/// <summary>An address to open instead of <see cref="OnClick"/>.</summary>
public string? Href { get; init; }
/// <summary>The main command (Save, the main action): filled with the accent.</summary>
public bool Primary { get; init; }
/// <summary>A destructive command.</summary>
public bool Danger { get; init; }
/// <summary>The command cannot be used now.</summary>
public bool Disabled { get; init; }
/// <summary>A toggled command (the radar is open).</summary>
public bool Active { get; init; }
/// <summary>A counter badge (attachments, links).</summary>
public int? Count { get; init; }
/// <summary>The group; a separator stands between groups.</summary>
public int Group { get; init; }
/// <summary>On the right side of the bar.</summary>
public bool End { get; init; }
/// <summary>Who leaves first when space is short: higher first; 0 never leaves.</summary>
public int Priority { get; init; } = 1;
/// <summary>The colour of a contextual action.</summary>
public KhTone Tone { get; init; }
}
+419
View File
@@ -0,0 +1,419 @@
using Khaemhat.Application.Localization;
using Khaemhat.Web.Components.Ui;
using Khaemhat.Web.Shell;
using Microsoft.AspNetCore.Components;
namespace Khaemhat.Web.Ui;
/// <summary>What <c>KhRecordLayout</c> needs from a record page.</summary>
public interface IRecordPage
{
/// <summary>The commands of the toolbar.</summary>
IReadOnlyList<ToolbarItem> Toolbar { get; }
/// <summary>The tabs.</summary>
IReadOnlyList<KhTabItem> Tabs { get; }
/// <summary>The tab shown.</summary>
string ActiveTab { get; }
/// <summary>Every field is read-only.</summary>
bool IsReadOnly { get; }
/// <summary>The messages of the form.</summary>
KhValidation Validation { get; }
/// <summary>Shows another tab.</summary>
/// <param name="id">The tab id.</param>
/// <returns>A task.</returns>
Task ShowTabAsync(string id);
}
/// <summary>
/// The base of the pages that edit one record (SPEC §10.5): toolbar with the standard commands, tabs, modified state
/// shown on the shell tab, validation, confirmation before discarding or deleting, and the page shortcuts of §10.5.7
/// (Ctrl+S, Ctrl+N, Ctrl+P, Ctrl+Canc, F9, Ctrl+Up/Down), active only while the page is the shown tab.
/// </summary>
/// <typeparam name="TRecord">The record.</typeparam>
public abstract class RecordPage<TRecord> : ComponentBase, IRecordPage, IDisposable
where TRecord : class
{
private string? _activeTab;
/// <summary>The texts.</summary>
[Inject]
protected ITexts Texts { get; set; } = default!;
/// <summary>The page shortcuts.</summary>
[Inject]
protected KeyboardShortcutService Keys { get; set; } = default!;
/// <summary>Confirmations.</summary>
[Inject]
protected DialogService Dialogs { get; set; } = default!;
/// <summary>Short messages.</summary>
[Inject]
protected ToastService Toasts { get; set; } = default!;
/// <summary>Navigation.</summary>
[Inject]
protected NavigationManager Navigation { get; set; } = default!;
/// <summary>The shell tab that holds the page.</summary>
[CascadingParameter]
public KhTab? Tab { get; set; }
/// <summary>The record shown.</summary>
protected TRecord? Record { get; set; }
/// <inheritdoc />
public KhValidation Validation { get; } = new();
/// <summary>The form of the page, to check the fields before saving (<c>@ref</c> it).</summary>
protected KhForm? Form { get; set; }
/// <summary>Whether there are unsaved changes.</summary>
protected bool IsModified { get; private set; }
/// <inheritdoc />
public virtual bool IsReadOnly => false;
/// <summary>Whether the record is new (Delete is not offered).</summary>
protected virtual bool IsNew => false;
/// <inheritdoc />
public abstract IReadOnlyList<KhTabItem> Tabs { get; }
/// <inheritdoc />
public string ActiveTab => _activeTab ?? (Tabs.Count > 0 ? Tabs[0].Id : string.Empty);
/// <inheritdoc />
public IReadOnlyList<ToolbarItem> Toolbar => [.. StandardCommands(), .. ContextActions(), .. MenuCommands()];
/// <summary>The address of a new record; <see langword="null"/> hides "Nuovo".</summary>
protected virtual string? NewUrl => null;
/// <summary>Whether the record may be deleted.</summary>
protected virtual bool CanDelete => !IsNew && !IsReadOnly;
/// <summary>The number of attachments, shown on the toolbar; <see langword="null"/> hides the command.</summary>
protected virtual int? AttachmentCount => null;
/// <summary>Whether there is a previous and next record (navigation with Ctrl+Up/Down).</summary>
protected virtual bool CanMove => false;
/// <summary>Marks the record as changed: the shell tab shows the orange dot.</summary>
protected void MarkModified()
{
if (!IsModified)
{
IsModified = true;
Tab?.SetModified(true);
}
}
/// <summary>Marks the record as saved.</summary>
protected void MarkSaved()
{
IsModified = false;
Tab?.SetModified(false);
}
/// <inheritdoc />
public Task ShowTabAsync(string id)
{
_activeTab = id;
StateHasChanged();
return Task.CompletedTask;
}
/// <summary>Saves: checks the form, calls <see cref="SaveCoreAsync"/>, reports the outcome.</summary>
/// <returns>Whether it was saved.</returns>
public async Task<bool> SaveAsync()
{
if (IsReadOnly)
{
return false;
}
if (Form is not null && !Form.Validate())
{
Toasts.Show(ToastKind.Error, Texts["Ui.Record.Invalid"]);
return false;
}
if (!await SaveCoreAsync())
{
Toasts.Show(ToastKind.Error, Texts["Ui.Record.Invalid"]);
StateHasChanged();
return false;
}
MarkSaved();
Toasts.Show(ToastKind.Success, Texts["Ui.Record.Saved"]);
StateHasChanged();
return true;
}
/// <summary>Discards the changes after a confirmation and reloads the record.</summary>
/// <returns>A task.</returns>
public async Task CancelAsync()
{
if (IsModified && !await Dialogs.ConfirmAsync(new(Texts["Ui.Record.DiscardTitle"], Texts["Ui.Record.DiscardText"],
Texts["Ui.Record.Discard"], Texts["Common.Cancel"], Danger: true)))
{
return;
}
Validation.Clear();
await ReloadAsync();
MarkSaved();
StateHasChanged();
}
/// <summary>Deletes the record after a confirmation.</summary>
/// <returns>A task.</returns>
public async Task DeleteAsync()
{
if (!CanDelete || !await Dialogs.ConfirmAsync(new(Texts["Ui.Record.DeleteTitle"], Texts["Ui.Record.DeleteText"],
Texts["Ui.Toolbar.Delete"], Texts["Common.Cancel"], Danger: true)))
{
return;
}
await DeleteCoreAsync();
MarkSaved();
Toasts.Show(ToastKind.Success, Texts["Ui.Record.Deleted"]);
}
/// <summary>Opens a new record.</summary>
/// <returns>A task.</returns>
public Task NewAsync()
{
if (NewUrl is not null)
{
Navigation.NavigateTo(NewUrl);
}
return Task.CompletedTask;
}
/// <summary>Writes the record; adds messages to <see cref="Validation"/> and returns <see langword="false"/> when refused.</summary>
/// <returns>Whether it was saved.</returns>
protected abstract Task<bool> SaveCoreAsync();
/// <summary>Reads the record again, dropping the changes.</summary>
/// <returns>A task.</returns>
protected abstract Task ReloadAsync();
/// <summary>Deletes the record.</summary>
/// <returns>A task.</returns>
protected virtual Task DeleteCoreAsync() => Task.CompletedTask;
/// <summary>Prints (Ctrl+P): by default the print preview of the browser.</summary>
/// <returns>A task.</returns>
protected virtual Task PrintAsync() => Task.CompletedTask;
/// <summary>Opens the radar of the records of this kind (F9).</summary>
/// <returns>A task.</returns>
protected virtual Task RadarAsync() => Task.CompletedTask;
/// <summary>Shows the previous (-1) or next (+1) record.</summary>
/// <param name="direction">The direction.</param>
/// <returns>A task.</returns>
protected virtual Task MoveAsync(int direction) => Task.CompletedTask;
/// <summary>Opens the attachments.</summary>
/// <returns>A task.</returns>
protected virtual Task AttachmentsAsync() => Task.CompletedTask;
/// <summary>The contextual actions of the record (Conferma ed emetti, Contabilizza...).</summary>
/// <returns>The actions.</returns>
protected virtual IEnumerable<ToolbarItem> ContextActions() => [];
/// <summary>The commands that live only in the "⋯" menu.</summary>
/// <returns>The commands.</returns>
protected virtual IEnumerable<ToolbarItem> MenuCommands() => [];
/// <summary>The standard commands of SPEC §10.4.</summary>
/// <returns>The commands.</returns>
protected virtual IEnumerable<ToolbarItem> StandardCommands()
{
if (NewUrl is not null)
{
yield return Command("new", "plus", "Ui.Toolbar.New", KeyboardShortcuts.Commands.New, NewAsync) with { Group = 0, Priority = 0 };
}
yield return Command("save", "save", "Ui.Toolbar.Save", KeyboardShortcuts.Commands.Save, SaveAsync) with
{
Group = 0, Priority = 0, Primary = IsModified, Disabled = IsReadOnly,
};
yield return Command("cancel", "undo", "Ui.Toolbar.Cancel", null, CancelAsync) with { Group = 0, Disabled = !IsModified, Priority = 2 };
yield return Command("delete", "trash", "Ui.Toolbar.Delete", KeyboardShortcuts.Commands.Delete, DeleteAsync) with
{
Group = 0, Danger = true, Disabled = !CanDelete, Priority = 3,
};
yield return Command("print", "printer", "Ui.Toolbar.Print", KeyboardShortcuts.Commands.Print, PrintAsync) with { Group = 1, Priority = 4 };
if (AttachmentCount is { } attachments)
{
yield return Command("attachments", "paperclip", "Ui.Toolbar.Attachments", null, AttachmentsAsync) with { Group = 2, Count = attachments, Priority = 5 };
}
yield return Command("radar", "radar", "Ui.Toolbar.Radar", KeyboardShortcuts.Commands.Radar, RadarAsync) with { End = true, Priority = 6 };
if (CanMove)
{
yield return Command("previous", "chevron-up", "Ui.Toolbar.Previous", KeyboardShortcuts.Commands.PreviousRecord, () => MoveAsync(-1)) with { End = true, Priority = 7 };
yield return Command("next", "chevron-down", "Ui.Toolbar.Next", KeyboardShortcuts.Commands.NextRecord, () => MoveAsync(1)) with { End = true, Priority = 7 };
}
}
/// <summary>A command with its text and the keys of a shortcut.</summary>
/// <param name="id">The id.</param>
/// <param name="icon">The icon.</param>
/// <param name="textKey">The text key.</param>
/// <param name="shortcut">The shortcut command, or <see langword="null"/>.</param>
/// <param name="onClick">What it does.</param>
/// <returns>The command.</returns>
protected ToolbarItem Command(string id, string icon, string textKey, string? shortcut, Func<Task> onClick) =>
new(id, icon, Texts[textKey]) { Shortcut = shortcut is null ? null : KeyboardShortcuts.KeysOf(shortcut), OnClick = onClick };
/// <inheritdoc />
protected override void OnInitialized() => Keys.PagePressed += OnShortcutAsync;
private async Task OnShortcutAsync(string command)
{
if (Tab is not null && !Tab.IsActive)
{
return;
}
Func<Task>? action = command switch
{
KeyboardShortcuts.Commands.Save => SaveAsync,
KeyboardShortcuts.Commands.New when NewUrl is not null => NewAsync,
KeyboardShortcuts.Commands.Print => PrintAsync,
KeyboardShortcuts.Commands.Delete when CanDelete => DeleteAsync,
KeyboardShortcuts.Commands.Radar => RadarAsync,
KeyboardShortcuts.Commands.PreviousRecord when CanMove => () => MoveAsync(-1),
KeyboardShortcuts.Commands.NextRecord when CanMove => () => MoveAsync(1),
_ => null,
};
if (action is not null)
{
await InvokeAsync(async () =>
{
await action();
StateHasChanged();
});
}
}
/// <inheritdoc />
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>Releases the shortcut subscription.</summary>
/// <param name="disposing">Called from <see cref="Dispose()"/>.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
Keys.PagePressed -= OnShortcutAsync;
}
}
}
/// <summary>
/// The base of document pages (SPEC §10.5.3): the first tab is <c>Righe</c> and the page opens there; then Testata,
/// Totali, Scadenze, Note, Allegati, Collegamenti, Storico as the document needs.
/// </summary>
/// <typeparam name="TDocument">The document.</typeparam>
/// <typeparam name="TLine">A line of the document.</typeparam>
public abstract class DocumentPage<TDocument, TLine> : RecordPage<TDocument>
where TDocument : class
{
/// <summary>The standard tab ids of a document.</summary>
public static class TabIds
{
/// <summary>Lines (first).</summary>
public const string Lines = "righe";
/// <summary>Header fields.</summary>
public const string Header = "testata";
/// <summary>Totals.</summary>
public const string Totals = "totali";
/// <summary>Due dates.</summary>
public const string DueDates = "scadenze";
/// <summary>Notes.</summary>
public const string Notes = "note";
/// <summary>Attachments.</summary>
public const string Attachments = "allegati";
/// <summary>Links to other documents.</summary>
public const string Links = "collegamenti";
/// <summary>History.</summary>
public const string History = "storico";
}
/// <summary>The lines of the document.</summary>
protected abstract IList<TLine> Lines { get; }
/// <summary>The standard tabs, Righe first, with the counters given.</summary>
/// <param name="attachments">The attachments, or <see langword="null"/> to leave the tab out.</param>
/// <param name="links">The linked documents, or <see langword="null"/> to leave the tab out.</param>
/// <returns>The tabs.</returns>
protected IReadOnlyList<KhTabItem> StandardTabs(int? attachments = null, int? links = null)
{
var tabs = new List<KhTabItem>
{
new(TabIds.Lines, "list", Texts["Ui.Record.Tabs.Lines"], Lines.Count),
new(TabIds.Header, "file", Texts["Ui.Record.Tabs.Header"]),
new(TabIds.Totals, "euro", Texts["Ui.Record.Tabs.Totals"]),
new(TabIds.DueDates, "calendar", Texts["Ui.Record.Tabs.DueDates"]),
new(TabIds.Notes, "edit", Texts["Ui.Record.Tabs.Notes"]),
};
if (attachments is { } a)
{
tabs.Add(new(TabIds.Attachments, "paperclip", Texts["Ui.Record.Tabs.Attachments"], a));
}
if (links is { } l)
{
tabs.Add(new(TabIds.Links, "link", Texts["Ui.Record.Tabs.Links"], l));
}
tabs.Add(new(TabIds.History, "history", Texts["Ui.Record.Tabs.History"]));
return tabs;
}
}
/// <summary>
/// The base of master data pages (SPEC §10.5.3): customers, suppliers, items. The first tab is the main data; the
/// header shows identity, contacts, condition chips and KPIs.
/// </summary>
/// <typeparam name="TRecord">The record.</typeparam>
public abstract class MasterDataPage<TRecord> : RecordPage<TRecord>
where TRecord : class
{
/// <summary>The standard tab ids of a master record.</summary>
public static class TabIds
{
/// <summary>Main data (first).</summary>
public const string Main = "dati";
/// <summary>Notes and attachments.</summary>
public const string Notes = "note";
/// <summary>History.</summary>
public const string History = "storico";
}
}