M3 · Framework UI #119

Merged
Alby96 merged 9 commits from feat/25-interfaccia into main 2026-11-11 21:00:47 +01:00
57 changed files with 5249 additions and 12 deletions
Showing only changes of commit d958e7372d - Show all commits

No files matched your search

@@ -237,11 +237,40 @@ public sealed class AccountSecurity
}
account.TotpEnabled = true;
return NewRecoveryCodes(account);
}
/// <summary>Replaces the recovery codes with ten new ones; the old ones stop working.</summary>
/// <param name="account">The account.</param>
/// <returns>The new codes, to show once.</returns>
public static IReadOnlyList<string> NewRecoveryCodes(IAccount account)
{
ArgumentNullException.ThrowIfNull(account);
var codes = Enumerable.Range(0, 10).Select(_ => SecureTokenGenerator.CreateReadableCode(2)).ToList();
account.TotpRecoveryCodes = JsonSerializer.Serialize(codes.Select(c => SecureTokenGenerator.Hash(c)).ToList());
return codes;
}
/// <summary>How many recovery codes are still unused.</summary>
/// <param name="account">The account.</param>
/// <returns>The number of codes left.</returns>
public static int RecoveryCodesLeft(IAccount account)
{
ArgumentNullException.ThrowIfNull(account);
return account.TotpEnabled ? Deserialize(account.TotpRecoveryCodes).Count : 0;
}
/// <summary>Checks the current password without counting failures (profile changes that ask for it again).</summary>
/// <param name="account">The account.</param>
/// <param name="password">The password typed.</param>
/// <returns>Whether it is right.</returns>
public static bool IsCurrentPassword(IAccount account, string password)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(password);
return account.PasswordHash is not null && PasswordHasher.Verify(account.PasswordHash, password) != PasswordVerification.Failed;
}
/// <summary>Checks a TOTP code at sign-in. A code is never accepted twice.</summary>
/// <param name="account">The account.</param>
/// <param name="code">The code.</param>
@@ -0,0 +1,270 @@
using System.Net.Mail;
using Khaemhat.Application.Audit;
using Khaemhat.Core.Security;
using Khaemhat.Infrastructure.Security;
namespace Khaemhat.Application.Security;
/// <summary>What the profile page shows about the signed-in account (SPEC §12, mockup 008).</summary>
/// <param name="UserName">The sign-in name.</param>
/// <param name="DisplayName">The name shown in the interface.</param>
/// <param name="Email">The e-mail address.</param>
/// <param name="IsInstanceAccount">Whether it is an instance account (super user or administrator).</param>
/// <param name="TotpEnabled">Whether the two-step verification is active.</param>
/// <param name="TotpRequired">Whether the two-step verification is mandatory, so it cannot be turned off.</param>
/// <param name="RecoveryCodesLeft">Unused recovery codes.</param>
/// <param name="HasPassword">Whether the account signs in with a password (technical users do not).</param>
/// <param name="PasswordChangedAt">When the password was last set (UTC).</param>
/// <param name="LastLoginAt">The last successful sign-in (UTC).</param>
public sealed record ProfileInfo(
string UserName,
string DisplayName,
string? Email,
bool IsInstanceAccount,
bool TotpEnabled,
bool TotpRequired,
int RecoveryCodesLeft,
bool HasPassword,
DateTime? PasswordChangedAt,
DateTime? LastLoginAt);
/// <summary>
/// The changes users make to their own account from the profile (SPEC §12, issue #31): name and e-mail, password,
/// two-step verification and recovery codes. Unlike <see cref="SignInService"/> it works from the session owner, not
/// from the cookie, because the profile runs in the interactive circuit where the cookie cannot be read. Every change is
/// recorded in <c>sys_security_audit</c>; a password change closes the other sessions of the account.
/// </summary>
/// <param name="systemUsers">Instance accounts.</param>
/// <param name="companyUsers">Company users.</param>
/// <param name="security">Credential rules.</param>
/// <param name="sessions">Sessions.</param>
/// <param name="audit">The security audit.</param>
public sealed class ProfileService(
SystemUserService systemUsers,
UserService companyUsers,
AccountSecurity security,
SessionStore sessions,
ISecurityAuditLog audit)
{
/// <summary>The longest display name accepted.</summary>
public const int DisplayNameMaxLength = 100;
/// <summary>The display name is empty or too long.</summary>
public const string DisplayNameInvalid = "display_name_invalid";
/// <summary>The e-mail address is not valid.</summary>
public const string EmailInvalid = "email_invalid";
/// <summary>The two-step verification is mandatory for the account and cannot be turned off.</summary>
public const string TotpRequiredError = "totp_required";
/// <summary>Reads the account of a session owner.</summary>
/// <param name="owner">The session owner.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The profile, or <see langword="null"/> when the account no longer exists or is disabled.</returns>
public async Task<ProfileInfo?> GetAsync(SessionOwner owner, CancellationToken cancellationToken = default)
{
var account = await LoadAsync(owner, cancellationToken).ConfigureAwait(false);
return account is null ? null : InfoOf(account, owner);
}
/// <summary>Changes name and e-mail.</summary>
/// <param name="owner">The session owner.</param>
/// <param name="displayName">The new name.</param>
/// <param name="email">The new e-mail, or empty to remove it.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The error codes; empty when saved.</returns>
public async Task<IReadOnlyList<string>> UpdateAsync(SessionOwner owner, string? displayName, string? email, CancellationToken cancellationToken = default)
{
var name = displayName?.Trim() ?? string.Empty;
var mail = string.IsNullOrWhiteSpace(email) ? null : email.Trim();
var errors = new List<string>();
if (name.Length is 0 or > DisplayNameMaxLength)
{
errors.Add(DisplayNameInvalid);
}
if (mail is not null && !IsEmail(mail))
{
errors.Add(EmailInvalid);
}
if (errors.Count > 0)
{
return errors;
}
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
account.DisplayName = name;
account.Email = mail;
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
await AuditAsync("user.profile-updated", account, owner, cancellationToken).ConfigureAwait(false);
return [];
}
/// <summary>Changes the password, checking the current one, and closes every other session of the account.</summary>
/// <param name="owner">The session owner.</param>
/// <param name="currentSessionId">The session that stays open.</param>
/// <param name="currentPassword">The current password.</param>
/// <param name="newPassword">The new password.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The error codes (<see cref="SecurityErrors"/>); empty when changed.</returns>
public async Task<IReadOnlyList<string>> ChangePasswordAsync(
SessionOwner owner, long? currentSessionId, string currentPassword, string newPassword, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(currentPassword);
ArgumentNullException.ThrowIfNull(newPassword);
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
if (!AccountSecurity.IsCurrentPassword(account, currentPassword))
{
await AuditAsync("user.password-change-refused", account, owner, cancellationToken).ConfigureAwait(false);
return [SecurityErrors.CurrentPasswordWrong];
}
var errors = security.ChangePassword(account, newPassword);
if (errors.Count > 0)
{
return errors;
}
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
await sessions.RevokeAllAsync(owner, "password_changed", currentSessionId, cancellationToken).ConfigureAwait(false);
await AuditAsync("user.password-changed", account, owner, cancellationToken).ConfigureAwait(false);
return [];
}
/// <summary>Starts turning on the two-step verification; reloading the page shows the same secret.</summary>
/// <param name="owner">The session owner.</param>
/// <param name="companyCode">The company of the session, shown in the label of the authenticator app.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The secret to show, or <see langword="null"/> when the verification is already active.</returns>
public async Task<TotpSetup?> BeginTotpSetupAsync(SessionOwner owner, string? companyCode, CancellationToken cancellationToken = default)
{
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
if (account.TotpEnabled)
{
return null;
}
var secret = security.PendingTotpSecret(account);
if (secret is null)
{
secret = security.BeginTotpSetup(account);
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
}
var label = companyCode is null ? account.UserName : account.UserName + "@" + companyCode;
return new TotpSetup(secret, TotpGenerator.ProvisioningUri(secret, label));
}
/// <summary>Completes turning on the two-step verification with the first code from the app.</summary>
/// <param name="owner">The session owner.</param>
/// <param name="code">The code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The ten recovery codes to show once, or <see langword="null"/> when the code is wrong.</returns>
public async Task<IReadOnlyList<string>?> ConfirmTotpSetupAsync(SessionOwner owner, string code, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(code);
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
if (account.TotpEnabled)
{
return null;
}
var codes = security.ConfirmTotpSetup(account, code.Trim());
if (codes is null)
{
return null;
}
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
await AuditAsync("user.totp-enabled", account, owner, cancellationToken).ConfigureAwait(false);
return codes;
}
/// <summary>Replaces the recovery codes, asking the password again.</summary>
/// <param name="owner">The session owner.</param>
/// <param name="password">The current password.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new codes, or <see langword="null"/> when the password is wrong or the verification is off.</returns>
public async Task<IReadOnlyList<string>?> RenewRecoveryCodesAsync(SessionOwner owner, string password, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(password);
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
if (!account.TotpEnabled || !AccountSecurity.IsCurrentPassword(account, password))
{
return null;
}
var codes = AccountSecurity.NewRecoveryCodes(account);
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
await AuditAsync("user.recovery-codes-renewed", account, owner, cancellationToken).ConfigureAwait(false);
return codes;
}
/// <summary>Turns the two-step verification off, asking the password again; refused when it is mandatory.</summary>
/// <param name="owner">The session owner.</param>
/// <param name="password">The current password.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The error codes; empty when turned off.</returns>
public async Task<IReadOnlyList<string>> DisableTotpAsync(SessionOwner owner, string password, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(password);
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
if (IsTotpRequired(account, owner))
{
return [TotpRequiredError];
}
if (!AccountSecurity.IsCurrentPassword(account, password))
{
return [SecurityErrors.CurrentPasswordWrong];
}
AccountSecurity.ResetTotp(account);
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
await AuditAsync("user.totp-disabled", account, owner, cancellationToken).ConfigureAwait(false);
return [];
}
private static bool IsEmail(string value) =>
value.Length <= 254 && MailAddress.TryCreate(value, out var address) && address.Address == value && value.Contains('.', StringComparison.Ordinal);
private bool IsTotpRequired(IAccount account, SessionOwner owner) =>
owner.IsInstanceAccount || account is CompanyUser { TotpRequired: true } || security.Options.TotpRequiredForUsers;
private ProfileInfo InfoOf(IAccount account, SessionOwner owner) => new(
account.UserName,
account.DisplayName,
account.Email,
owner.IsInstanceAccount,
account.TotpEnabled,
IsTotpRequired(account, owner),
AccountSecurity.RecoveryCodesLeft(account),
account.PasswordHash is not null,
account.PasswordChangedAt,
account.LastLoginAt);
private async Task<IAccount?> LoadAsync(SessionOwner owner, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(owner);
IAccount? account = owner.IsInstanceAccount
? await systemUsers.GetAsync(owner.UserId, cancellationToken).ConfigureAwait(false)
: await companyUsers.GetAsync(owner.CompanyDatabase!, owner.UserId, cancellationToken).ConfigureAwait(false);
return account is { IsActive: true } ? account : null;
}
private async Task<IAccount> RequireAsync(SessionOwner owner, CancellationToken cancellationToken) =>
await LoadAsync(owner, cancellationToken).ConfigureAwait(false)
?? throw new AccessDeniedException(SecurityErrors.InvalidCredentials, "The account no longer exists or is disabled.");
private Task SaveAsync(IAccount account, SessionOwner owner, CancellationToken cancellationToken) => account switch
{
SystemUser system => systemUsers.SaveAsync(system, cancellationToken),
CompanyUser user => companyUsers.SaveAsync(owner.CompanyDatabase!, user, cancellationToken),
_ => throw new InvalidOperationException("Unknown account type."),
};
private Task AuditAsync(string action, IAccount account, SessionOwner owner, CancellationToken cancellationToken) =>
audit.WriteAsync(new SecurityEvent(action, account.UserName, owner.CompanyDatabase), cancellationToken);
}
@@ -56,6 +56,7 @@
<KhCommandPalette Open="_searchOpen" OpenChanged="open => _searchOpen = open" OnToggleMenu="ToggleMenuAsync" />
<KhToastHost />
<KhDialogHost />
<KhDrawerHost />
<div id="blazor-error-ui" data-nosnippet>
@T["Shell.Error.Unexpected"]
@@ -0,0 +1,315 @@
@page "/sviluppo/componenti"
@attribute [Authorize]
@inject IWebHostEnvironment Environment
@inject ToastService Toasts
@inject DialogService Dialogs
@inject DrawerService Drawers
@inject TimeProvider Clock
@* The catalog of the Kh components with all their states (issue #27): development only. *@
<KhPageTitle Text="@T["Pages.Catalog.Title"]" Icon="grid" />
@if (!Environment.IsDevelopment())
{
<div class="kh-message">
<h1>@T["Pages.Catalog.DevOnly"]</h1>
<a class="btn" href="/">@T["Common.BackHome"]</a>
</div>
}
else
{
<div class="phead">
<div>
<h1>@T["Pages.Catalog.Title"]</h1>
<div class="sub">@T["Pages.Catalog.Subtitle"]</div>
</div>
<div class="grow"></div>
<a class="btn" href="sviluppo/documento"><KhIcon Name="file" /> @T["Pages.Catalog.OpenDocument"]</a>
</div>
<KhTabs Items="Sections" Active="@_section" ActiveChanged="s => _section = s" Label="@T["Pages.Catalog.Title"]" />
@switch (_section)
{
case "campi":
<KhForm Validation="_validation" ReadOnly="_readOnly" Layout="KhFormLayout.Groups" OnValidSubmit="OnValid" @ref="_form">
<KhFieldGroup Title="@T["Pages.Catalog.Fields.Document"]" Icon="file">
<KhTextBox Label="@T["Pages.Catalog.Fields.Number"]" Name="number" @bind-Value="_document.Number" Required="true" Span="6" Mono="true" />
<KhDateBox Label="@T["Pages.Catalog.Fields.Date"]" Name="date" @bind-Value="_document.Date" Required="true" Span="6" Hint="@T["Pages.Catalog.Fields.DateHint"]" />
<KhSelect TValue="string" Label="@T["Pages.Catalog.Fields.Kind"]" Name="kind" @bind-Value="_kind" Options="Kinds" Required="true" Empty="" Span="12" />
<KhHotlink TItem="SampleParty" Label="@T["Pages.Catalog.Fields.Party"]" Name="party" @bind-Value="_document.Party" Required="true" Span="12"
Search="CatalogSamples.SearchAsync" CodeOf="p => p.Code" DescriptionOf="p => p.Name"
OnRadar="Radar" OnOpen="OpenParty" OnCreate="CreateParty" Hint="@T["Pages.Catalog.Fields.PartyHint"]" />
</KhFieldGroup>
<KhFieldGroup Title="@T["Pages.Catalog.Fields.Conditions"]" Icon="coins">
<KhNumberBox Label="@T["Pages.Catalog.Fields.Discount"]" Name="discount" @bind-Value="_document.Discount" Min="0" Max="100" Span="6" Hint="@T["Pages.Catalog.Fields.DiscountHint"]" />
<KhNumberBox Label="@T["Pages.Catalog.Fields.Amount"]" Name="amount" @bind-Value="_amount" Span="6" Hint="@T["Pages.Catalog.Fields.AmountHint"]" />
<KhTextBox Label="@T["Pages.Catalog.Fields.Email"]" Name="email" Type="email" @bind-Value="_email" Span="12" Rule="EmailRule" />
<KhCheck Label="@T["Pages.Catalog.Fields.Split"]" Name="split" @bind-Value="_split" Span="6" />
<KhSwitch Label="@T["Pages.Catalog.Fields.Stamp"]" Name="stamp" @bind-Value="_stamp" Span="6" />
<KhTextArea Label="@T["Pages.Catalog.Fields.Notes"]" Name="notes" @bind-Value="_document.Notes" Span="12" Rows="2" />
<KhTextBox Label="@T["Pages.Catalog.Fields.Disabled"]" Value="@T["Pages.Catalog.Fields.DisabledValue"]" Disabled="true" Span="12" />
</KhFieldGroup>
<section class="fgroup wide">
<div class="fgh"><KhIcon Name="check-circle" /> @T["Pages.Catalog.Fields.States"]</div>
<div class="kh-catalogbar">
<button type="submit" class="btn primary"><KhIcon Name="check" /> @T["Pages.Catalog.Fields.Validate"]</button>
<button type="button" class="btn" @onclick="ServerError"><KhIcon Name="alert" /> @T["Pages.Catalog.Fields.ServerError"]</button>
<button type="button" class="btn" @onclick="() => _validation.Clear()">@T["Pages.Catalog.Fields.ClearMessages"]</button>
<KhSwitch Label="@T["Pages.Catalog.Fields.ReadOnly"]" Value="_readOnly" ValueChanged="v => _readOnly = v" Span="0" />
</div>
</section>
</KhForm>
break;
case "pannelli":
<div class="kh-catalog">
<div class="cols cols-4">
<KhTile Title="@T["Pages.Catalog.Panels.Revenue"]" Icon="euro" Value="@T.Money(128_450.30m)" Tone="KhTone.Accent">
<Detail>@T["Pages.Catalog.Panels.RevenueDetail"]</Detail>
</KhTile>
<KhTile Title="@T["Pages.Catalog.Panels.Collected"]" Icon="check-circle" Value="@T.Money(96_120m)" Tone="KhTone.Ok" />
<KhTile Title="@T["Pages.Catalog.Panels.Expiring"]" Icon="clock" Value="@T.Money(12_300m)" Tone="KhTone.Warning" />
<KhTile Title="@T["Pages.Catalog.Panels.Overdue"]" Icon="alert" Value="@T.Money(4_870.55m)" Tone="KhTone.Error" Href="sviluppo/componenti" />
</div>
<KhStrip Items="Stats" Label="@T["Pages.Catalog.Panels.Strip"]" />
<KhPanel Title="@T["Pages.Catalog.Panels.Panel"]" Icon="layers" LinkHref="sviluppo/componenti" LinkText="@T["Pages.Catalog.Panels.Link"]">
<div class="kh-catalogrow">
<KhBadge Tone="KhTone.Neutral">@T["Pages.Catalog.Panels.Draft"]</KhBadge>
<KhBadge Tone="KhTone.Info">@T["Pages.Catalog.Panels.Sent"]</KhBadge>
<KhBadge Tone="KhTone.Ok">@T["Pages.Catalog.Panels.Paid"]</KhBadge>
<KhBadge Tone="KhTone.Warning">@T["Pages.Catalog.Panels.Expiring"]</KhBadge>
<KhBadge Tone="KhTone.Error">@T["Pages.Catalog.Panels.Overdue"]</KhBadge>
<KhBadge Tone="KhTone.Accent">@T["Pages.Catalog.Panels.Issued"]</KhBadge>
</div>
<div class="kh-catalogrow">
<KhChip Icon="coins" Text="@T["Pages.Catalog.Panels.Payment"]" Value="@T["Pages.Catalog.Panels.PaymentValue"]" />
<KhChip Icon="tag" Text="@T["Pages.Catalog.Panels.PriceList"]" Value="@T["Pages.Catalog.Panels.PriceListValue"]" Tone="KhTone.Accent" />
<KhChip Icon="alert" Text="@T["Pages.Catalog.Panels.Credit"]" Tone="KhTone.Warning" />
<KhChip Icon="x-circle" Text="@T["Pages.Catalog.Panels.Blocked"]" Tone="KhTone.Error" />
@if (_filter)
{
<KhChip Text="@T["Pages.Catalog.Panels.Filter"]" Value="@T["Pages.Catalog.Panels.FilterValue"]" OnRemove="() => _filter = false" />
}
</div>
<div class="kh-catalogrow">
<KhMoney Value="1234.5m" /> <KhMoney Value="-87.2m" RedWhenNegative="true" /> <KhMoney Value="null" Empty="-" />
</div>
</KhPanel>
</div>
break;
case "navigazione":
<div class="kh-catalog">
<KhPanel Title="@T["Pages.Catalog.Navigation.Tabs"]" Icon="columns" Tight="true">
<KhTabs Items="DemoTabs" Active="@_demoTab" ActiveChanged="t => _demoTab = t" Shortcuts="false" />
<div class="pb">@T.Format("Pages.Catalog.Navigation.TabShown", DemoTabs.First(t => t.Id == _demoTab).Text)</div>
</KhPanel>
<KhPanel Title="@T["Pages.Catalog.Navigation.Steps"]" Icon="activity">
<KhSteps Items="Steps" Current="_step" Label="@T["Pages.Catalog.Navigation.Steps"]" />
<div class="cols cols-2">
<KhVSteps Items="Steps" Current="_step" Label="@T["Pages.Catalog.Navigation.Steps"]" />
<div class="kh-catalogrow">
<button type="button" class="btn" disabled="@(_step == 0)" @onclick="() => _step--"><KhIcon Name="chevron-left" /> @T["Common.Back"]</button>
<button type="button" class="btn primary" disabled="@(_step >= Steps.Count)" @onclick="() => _step++">@T["Common.Continue"] <KhIcon Name="chevron-right" /></button>
</div>
</div>
</KhPanel>
</div>
break;
case "finestre":
<div class="kh-catalog">
<KhPanel Title="@T["Pages.Catalog.Windows.Title"]" Icon="layout">
<div class="kh-catalogrow">
<button type="button" class="btn" @onclick="() => _dialog = true"><KhIcon Name="layout" /> @T["Pages.Catalog.Windows.Dialog"]</button>
<button type="button" class="btn" @onclick="() => _drawer = true"><KhIcon Name="sidebar" /> @T["Pages.Catalog.Windows.Drawer"]</button>
<button type="button" class="btn" @onclick="ServiceDrawerAsync"><KhIcon Name="sidebar" /> @T["Pages.Catalog.Windows.DrawerService"]</button>
<button type="button" class="btn danger" @onclick="ConfirmAsync"><KhIcon Name="trash" /> @T["Pages.Catalog.Windows.Confirm"]</button>
</div>
<div class="kh-catalogrow">
@foreach (var kind in Enum.GetValues<ToastKind>())
{
<button type="button" class="btn" @onclick="() => ShowToast(kind)">@T[KindKey(kind)]</button>
}
</div>
</KhPanel>
</div>
<KhDialog Open="_dialog" Title="@T["Pages.Catalog.Windows.Dialog"]" Icon="layout" OnClose="() => _dialog = false">
<ChildContent>
<p>@T["Pages.Catalog.Windows.DialogText"]</p>
<KhForm Layout="KhFormLayout.Plain">
<KhTextBox Label="@T["Pages.Catalog.Fields.Number"]" @bind-Value="_dialogText" Span="12" />
</KhForm>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _dialog = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" @onclick="() => _dialog = false">@T["Common.Save"]</button>
</Footer>
</KhDialog>
<KhDrawer Open="_drawer" Title="@T["Pages.Catalog.Windows.Drawer"]" Icon="sidebar" OnClose="() => _drawer = false">
<p>@T["Pages.Catalog.Windows.DrawerText"]</p>
<KhStrip Items="Stats" />
</KhDrawer>
break;
case "toolbar":
<div class="kh-catalog">
<p class="muted">@T["Pages.Catalog.Toolbar.Intro"]</p>
<div class="kh-resizable">
<KhIconToolbar Items="DemoToolbar" Label="@T["Ui.Toolbar.Label"]" />
</div>
<KhDocHead KindIcon="file" KindLabel="@T["Pages.Catalog.Head.Kind"]" Number="@_document.Number"
PartyName="@_document.Party?.Name" PartyCode="@_document.Party?.Code" PartyLines="PartyLines"
TotalLabel="@T["Pages.Catalog.Head.Total"]" TotalValue="@T.Money(_document.Total)" SubValues="SubValues">
<Facts>
<span>@T["Pages.Catalog.Fields.Date"] <b>@(_document.Date is { } d ? T.Date(d) : null)</b></span>
<span>@T["Pages.Catalog.Head.Section"] <b>A</b></span>
</Facts>
<State><KhBadge Tone="KhTone.Info">@T["Pages.Catalog.Panels.Draft"]</KhBadge></State>
<Chips>
<KhChip Icon="coins" Text="@T["Pages.Catalog.Panels.Payment"]" Value="@T["Pages.Catalog.Panels.PaymentValue"]" />
<KhChip Icon="tag" Text="@T["Pages.Catalog.Panels.PriceList"]" Value="@T["Pages.Catalog.Panels.PriceListValue"]" Tone="KhTone.Accent" />
<KhChip Icon="alert" Text="@T["Pages.Catalog.Panels.Credit"]" Tone="KhTone.Warning" />
</Chips>
</KhDocHead>
</div>
break;
}
}
@code {
private readonly KhValidation _validation = new();
private SampleDocument _document = default!;
private KhForm? _form;
private string _section = "campi";
private string _demoTab = "righe";
private string? _kind;
private string? _email;
private string? _dialogText;
private decimal? _amount;
private bool _split;
private bool _stamp = true;
private bool _readOnly;
private bool _filter = true;
private bool _dialog;
private bool _drawer;
private int _step = 1;
private IReadOnlyList<KhTabItem> Sections =>
[
new("campi", "edit", T["Pages.Catalog.Sections.Fields"]),
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("toolbar", "settings", T["Pages.Catalog.Sections.Toolbar"]),
];
private IReadOnlyList<KhOption<string>> Kinds =>
[
new("TD01", T["Pages.Catalog.Fields.KindInvoice"]),
new("TD04", T["Pages.Catalog.Fields.KindCredit"]),
new("TD24", T["Pages.Catalog.Fields.KindDeferred"]),
];
private IReadOnlyList<KhStat> Stats =>
[
new(T["Pages.Catalog.Panels.Documents"], "128"),
new(T["Pages.Catalog.Panels.Taxable"], T.Money(104_000m)),
new(T["Pages.Catalog.Panels.Collected"], T.Money(96_120m), KhTone.Ok),
new(T["Pages.Catalog.Panels.Overdue"], T.Money(4_870.55m), KhTone.Error),
];
private IReadOnlyList<KhTabItem> DemoTabs =>
[
new("righe", "list", T["Ui.Record.Tabs.Lines"], 3),
new("testata", "file", T["Ui.Record.Tabs.Header"]),
new("allegati", "paperclip", T["Ui.Record.Tabs.Attachments"], 2),
new("storico", "history", T["Ui.Record.Tabs.History"]),
];
private IReadOnlyList<KhStep> Steps =>
[
new(T["Pages.Catalog.Navigation.Step1"], T["Pages.Catalog.Navigation.Step1Detail"]),
new(T["Pages.Catalog.Navigation.Step2"], T["Pages.Catalog.Navigation.Step2Detail"]),
new(T["Pages.Catalog.Navigation.Step3"], T["Pages.Catalog.Navigation.Step3Detail"]),
];
private IReadOnlyList<string> PartyLines => [T["Pages.Catalog.Head.Address"], T["Pages.Catalog.Head.Vat"]];
private IReadOnlyList<KhStat> SubValues =>
[
new(T["Pages.Catalog.Panels.Taxable"], T.Money(_document.Taxable)),
new(T["Pages.Catalog.Head.VatAmount"], T.Money(_document.Vat)),
new(T["Pages.Catalog.Head.Stamp"], T.Money(2m)),
];
private IReadOnlyList<ToolbarItem> DemoToolbar =>
[
Item("new", "plus", "Ui.Toolbar.New", "Ctrl+N") with { Priority = 0 },
Item("save", "save", "Ui.Toolbar.Save", "Ctrl+S") with { Primary = true, Priority = 0 },
Item("cancel", "undo", "Ui.Toolbar.Cancel", null) with { Priority = 2 },
Item("delete", "trash", "Ui.Toolbar.Delete", "Ctrl+Delete") with { Danger = true, Priority = 3 },
Item("copy", "copy", "Ui.Toolbar.Duplicate", null) with { Group = 1, Priority = 4 },
Item("print", "printer", "Ui.Toolbar.Print", "Ctrl+P") with { Group = 1, Priority = 4 },
Item("mail", "mail", "Ui.Toolbar.Email", null) with { Group = 1, Priority = 5 },
Item("export", "download", "Ui.Toolbar.Export", null) with { Group = 1, Priority = 5 },
Item("attachments", "paperclip", "Ui.Toolbar.Attachments", null) with { Group = 2, Count = 2, Priority = 5 },
Item("history", "history", "Ui.Toolbar.History", null) with { Group = 2, Priority = 6 },
Item("links", "link", "Ui.Toolbar.Links", null) with { Group = 2, Count = 1, Priority = 6 },
Item("issue", "send", "Pages.Catalog.Toolbar.Issue", null) with { Kind = ToolbarKind.Action, Primary = true, Priority = 1 },
Item("xml", "file-check", "Pages.Catalog.Toolbar.Xml", null) with { Kind = ToolbarKind.Action, Priority = 3 },
Item("post", "book", "Pages.Catalog.Toolbar.Post", null) with { Kind = ToolbarKind.Action, Tone = KhTone.Ok, Priority = 3 },
Item("ddt", "truck", "Pages.Catalog.Toolbar.Ddt", null) with { Kind = ToolbarKind.Action, Priority = 4 },
Item("final", "lock", "Pages.Catalog.Toolbar.Final", null) with { Kind = ToolbarKind.Action, Priority = 4 },
Item("radar", "radar", "Ui.Toolbar.Radar", "F9") with { End = true, Priority = 6 },
Item("previous", "chevron-up", "Ui.Toolbar.Previous", "Ctrl+ArrowUp") with { End = true, Priority = 7 },
Item("next", "chevron-down", "Ui.Toolbar.Next", "Ctrl+ArrowDown") with { End = true, Priority = 7 },
Item("settings", "settings", "Pages.Catalog.Toolbar.Settings", null) with { Kind = ToolbarKind.Menu },
];
/// <inheritdoc />
protected override void OnInitialized() =>
_document = CatalogSamples.Document(DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime));
private ToolbarItem Item(string id, string icon, string key, string? shortcut) =>
new(id, icon, T[key]) { Shortcut = shortcut, OnClick = () => Clicked(key) };
private Task Clicked(string key)
{
Toasts.Show(ToastKind.Info, T.Format("Pages.Catalog.Toolbar.Clicked", T[key]));
return Task.CompletedTask;
}
private string? EmailRule(string? value) =>
string.IsNullOrEmpty(value) || value.Contains('@', StringComparison.Ordinal) ? null : T["Auth.Errors.email_invalid"];
private void OnValid() => Toasts.Show(ToastKind.Success, T["Pages.Catalog.Fields.Valid"]);
private void ServerError() => _validation.Add("number", T["Pages.Catalog.Fields.NumberTaken"]);
private void Radar(string text) => Toasts.Show(ToastKind.Info, T.Format("Pages.Catalog.Fields.RadarOpened", text));
private void OpenParty(SampleParty party) => Toasts.Show(ToastKind.Info, T.Format("Pages.Catalog.Fields.PartyOpened", party.Name));
private void CreateParty(string text)
{
_document.Party = new SampleParty("C9999", text);
Toasts.Show(ToastKind.Success, T.Format("Pages.Catalog.Fields.PartyCreated", text));
}
private Task ServiceDrawerAsync() => Drawers.ShowAsync(new DrawerRequest(
T["Pages.Catalog.Windows.DrawerService"], "sidebar",
@<div><p>@T["Pages.Catalog.Windows.DrawerServiceText"]</p><KhStrip Items="Stats" /></div>,
@<button type="button" class="btn primary" @onclick="Drawers.Close">@T["Common.Close"]</button>));
private async Task ConfirmAsync()
{
var yes = await Dialogs.ConfirmAsync(new(T["Ui.Record.DeleteTitle"], T["Ui.Record.DeleteText"], T["Ui.Toolbar.Delete"], T["Common.Cancel"], Danger: true));
Toasts.Show(yes ? ToastKind.Warning : ToastKind.Info, T[yes ? "Pages.Catalog.Windows.Confirmed" : "Pages.Catalog.Windows.Cancelled"]);
}
private static string KindKey(ToastKind kind) => "Pages.Catalog.Windows.Toast." + kind;
private void ShowToast(ToastKind kind) => Toasts.Show(kind, T[KindKey(kind)], T["Pages.Catalog.Windows.ToastText"]);
}
@@ -0,0 +1,194 @@
@page "/sviluppo/documento"
@attribute [Authorize]
@inherits DocumentPage<SampleDocument, SampleLine>
@inject IWebHostEnvironment Environment
@inject TimeProvider Clock
@* A document page built on DocumentPage (issue #29): toolbar, header, tabs with Righe first, shortcuts. Fake data,
development only. *@
<KhPageTitle Text="@T["Pages.Catalog.Document"]" Icon="file" />
@if (!Environment.IsDevelopment() || Record is null)
{
<div class="kh-message"><h1>@T["Pages.Catalog.DevOnly"]</h1></div>
}
else
{
<KhRecordLayout Page="this">
<Heading>
<KhDocHead KindIcon="file" KindLabel="@T["Pages.Catalog.Head.Kind"]" Number="@Record.Number"
PartyName="@Record.Party?.Name" PartyCode="@Record.Party?.Code" PartyLines="PartyLines"
TotalLabel="@T["Pages.Catalog.Head.Total"]" TotalValue="@T.Money(Record.Total)" SubValues="SubValues">
<Facts>
<span>@T["Pages.Catalog.Fields.Date"] <b>@(Record.Date is { } d ? T.Date(d) : null)</b></span>
</Facts>
<State>
@if (Record.Issued)
{
<KhBadge Tone="KhTone.Accent">@T["Pages.Catalog.Panels.Issued"]</KhBadge>
}
else
{
<KhBadge Tone="KhTone.Info">@T["Pages.Catalog.Panels.Draft"]</KhBadge>
}
@if (IsModified)
{
<KhBadge Tone="KhTone.Warning">@T["Pages.Catalog.Modified"]</KhBadge>
}
</State>
<Chips>
<KhChip Icon="coins" Text="@T["Pages.Catalog.Panels.Payment"]" Value="@T["Pages.Catalog.Panels.PaymentValue"]" />
</Chips>
</KhDocHead>
</Heading>
<ChildContent>
@switch (ActiveTab)
{
case TabIds.Lines:
<table class="grid">
<thead>
<tr>
<th scope="col">@T["Pages.Catalog.Lines.Code"]</th>
<th scope="col">@T["Pages.Catalog.Lines.Description"]</th>
<th scope="col" class="num">@T["Pages.Catalog.Lines.Quantity"]</th>
<th scope="col" class="num">@T["Pages.Catalog.Lines.Price"]</th>
<th scope="col" class="num">@T["Pages.Catalog.Lines.Amount"]</th>
</tr>
</thead>
<tbody>
@foreach (var line in Record.Lines)
{
<tr>
<td class="code">@line.Code</td>
<td>@line.Description</td>
<td class="num">@T.Number(line.Quantity ?? 0, 2)</td>
<td class="num"><KhMoney Value="line.Price" /></td>
<td class="num"><KhMoney Value="line.Amount" /></td>
</tr>
}
</tbody>
</table>
break;
case TabIds.Header:
<KhForm Validation="Validation" ReadOnly="IsReadOnly" Layout="KhFormLayout.Groups" @ref="Form">
<KhFieldGroup Title="@T["Pages.Catalog.Fields.Document"]" Icon="file">
<KhTextBox Label="@T["Pages.Catalog.Fields.Number"]" Name="number" Value="@Record.Number" ValueChanged="v => Change(() => Record.Number = v ?? string.Empty)" Required="true" Mono="true" />
<KhDateBox Label="@T["Pages.Catalog.Fields.Date"]" Name="date" Value="Record.Date" ValueChanged="v => Change(() => Record.Date = v)" Required="true" />
<KhHotlink TItem="SampleParty" Label="@T["Pages.Catalog.Fields.Party"]" Name="party" Value="Record.Party" ValueChanged="v => Change(() => Record.Party = v)"
Required="true" Span="12" Search="CatalogSamples.SearchAsync" CodeOf="p => p.Code" DescriptionOf="p => p.Name" />
</KhFieldGroup>
<KhFieldGroup Title="@T["Pages.Catalog.Fields.Conditions"]" Icon="coins">
<KhNumberBox Label="@T["Pages.Catalog.Fields.Discount"]" Name="discount" Value="Record.Discount" ValueChanged="v => Change(() => Record.Discount = v)" Min="0" Max="100" />
<KhTextArea Label="@T["Pages.Catalog.Fields.Notes"]" Name="notes" Value="@Record.Notes" ValueChanged="v => Change(() => Record.Notes = v)" Span="12" Rows="2" />
</KhFieldGroup>
</KhForm>
break;
default:
<div class="pb"><p class="muted">@T["Pages.Catalog.TabPlaceholder"]</p></div>
break;
}
</ChildContent>
</KhRecordLayout>
}
@code {
private int _saved;
/// <inheritdoc />
public override IReadOnlyList<KhTabItem> Tabs => Record is null ? [] : StandardTabs(attachments: 2, links: 1);
/// <inheritdoc />
public override bool IsReadOnly => Record?.Issued == true;
/// <inheritdoc />
protected override IList<SampleLine> Lines => Record?.Lines ?? [];
/// <inheritdoc />
protected override string? NewUrl => "sviluppo/documento";
/// <inheritdoc />
protected override int? AttachmentCount => 2;
/// <inheritdoc />
protected override bool CanMove => true;
private IReadOnlyList<string> PartyLines => [T["Pages.Catalog.Head.Address"], T["Pages.Catalog.Head.Vat"]];
private IReadOnlyList<KhStat> SubValues => Record is null ? [] :
[
new(T["Pages.Catalog.Panels.Taxable"], T.Money(Record.Taxable)),
new(T["Pages.Catalog.Head.VatAmount"], T.Money(Record.Vat)),
];
/// <inheritdoc />
protected override void OnInitialized()
{
base.OnInitialized();
Record = CatalogSamples.Document(Today);
}
/// <inheritdoc />
protected override IEnumerable<ToolbarItem> ContextActions()
{
yield return new ToolbarItem("issue", "send", T["Pages.Catalog.Toolbar.Issue"])
{
Kind = ToolbarKind.Action, Primary = true, Disabled = IsReadOnly || IsModified, OnClick = IssueAsync,
};
}
/// <inheritdoc />
protected override Task<bool> SaveCoreAsync()
{
// A pretend rule of the service: the number must keep the year prefix.
if (Record is null || !Record.Number.StartsWith("2026/", StringComparison.Ordinal))
{
Validation.Add("number", T["Pages.Catalog.Fields.NumberTaken"]);
return Task.FromResult(false);
}
_saved++;
return Task.FromResult(true);
}
/// <inheritdoc />
protected override Task ReloadAsync()
{
Record = CatalogSamples.Document(Today);
return Task.CompletedTask;
}
/// <inheritdoc />
protected override Task MoveAsync(int direction)
{
Toasts.Show(ToastKind.Info, T[direction < 0 ? "Ui.Toolbar.Previous" : "Ui.Toolbar.Next"]);
return Task.CompletedTask;
}
/// <inheritdoc />
protected override Task RadarAsync()
{
Toasts.Show(ToastKind.Info, T["Ui.Toolbar.Radar"]);
return Task.CompletedTask;
}
private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
private void Change(Action change)
{
change();
MarkModified();
}
private Task IssueAsync()
{
if (Record is not null)
{
Record.Issued = true;
Toasts.Show(ToastKind.Success, T["Pages.Catalog.Panels.Issued"]);
}
return Task.CompletedTask;
}
}
@@ -4,6 +4,7 @@
@using Khaemhat.Application.Preferences
@using Khaemhat.Application.Security
@using Khaemhat.Web.Security
@using Khaemhat.Web.Components.Pages.ProfileTabs
@implements IAsyncDisposable
@inject ShellSession Session
@inject ThemeService Theme
@@ -176,6 +177,14 @@
</div>
break;
case AccountSection:
<ProfileAccount Owner="_owner" />
break;
case SecuritySection:
<ProfileSecurity Owner="_owner" CurrentSessionId="CurrentSession" />
break;
case SessionsSection:
<div class="pb">
<p class="muted">@T["Pages.Profile.Sessions.Intro"]</p>
@@ -238,9 +247,16 @@
{
<tr>
<td>
@foreach (var keys in shortcut.Keys)
@if (shortcut.Display is { } display)
{
<kbd>@keys</kbd>
<kbd>@display</kbd>
}
else
{
@foreach (var keys in shortcut.Keys)
{
<kbd>@KeyboardShortcuts.Pretty(keys)</kbd>
}
}
</td>
<td>@T[shortcut.TextKey]</td>
@@ -260,11 +276,15 @@
private const string StartSection = "pagina-iniziale";
private const string ShortcutsSection = "scorciatoie";
private const string SessionsSection = "sessioni";
private const string AccountSection = "dati";
private const string SecuritySection = "sicurezza";
private static readonly (string Id, string Icon, string Key)[] Sections =
[
(AppearanceSection, "palette", "Pages.Profile.Tabs.Appearance"),
(StartSection, "home", "Pages.Profile.Tabs.Start"),
(AccountSection, "user", "Pages.Profile.Tabs.Account"),
(SecuritySection, "lock", "Pages.Profile.Tabs.Security"),
(SessionsSection, "monitor", "Pages.Profile.Tabs.Sessions"),
(ShortcutsSection, "keyboard", "Pages.Profile.Tabs.Shortcuts"),
];
@@ -281,7 +301,7 @@
private SessionOwner? _owner;
private long _currentSessionId;
/// <summary>The section: <c>aspetto</c>, <c>pagina-iniziale</c>, <c>sessioni</c>, <c>scorciatoie</c>.</summary>
/// <summary>The section: <c>aspetto</c>, <c>pagina-iniziale</c>, <c>dati</c>, <c>sicurezza</c>, <c>sessioni</c>, <c>scorciatoie</c>.</summary>
[SupplyParameterFromQuery(Name = "scheda")]
public string? Section { get; set; }
@@ -293,6 +313,8 @@
private bool IsModified => Draft != Session.Preferences;
private long? CurrentSession => _currentSessionId == 0 ? null : _currentSessionId;
private IEnumerable<MenuItem> StartChoices => MenuCatalog.All.Where(i => i.Milestone is null && Session.CanSee(i));
/// <inheritdoc />
@@ -0,0 +1,140 @@
@using Khaemhat.Application.Security
@using Khaemhat.Web.Security
@inject ProfileService Profiles
@inject ShellSession Session
@inject ToastService Toasts
@inject SecurityPolicyOptions Policy
@* "Dati personali" of the profile (SPEC §12, issue #31): the name and e-mail the user may change alone. *@
@if (_info is null)
{
<div class="pb"><p class="muted">@T["Common.Loading"]</p></div>
}
else
{
<form class="fgroups" @onsubmit="SaveAsync" @onsubmit:preventDefault>
<fieldset class="fgroup">
<legend class="fgh"><KhIcon Name="user" /> @T["Pages.Profile.Account.Data"]</legend>
<div class="form">
<div class="f c12">
<label for="kh-p-user">@T["Pages.Profile.Account.UserName"]</label>
<input id="kh-p-user" class="in" value="@_info.UserName" readonly />
</div>
<div class="f c12">
<label for="kh-p-name">@T["Pages.Profile.Account.DisplayName"] <span class="req">*</span></label>
<input id="kh-p-name" class="in @(HasError(ProfileService.DisplayNameInvalid) ? "err" : null)" @bind="_displayName" @bind:event="oninput"
maxlength="@ProfileService.DisplayNameMaxLength" autocomplete="name" required />
</div>
<div class="f c12">
<label for="kh-p-mail">@T["Pages.Profile.Account.Email"]</label>
<input id="kh-p-mail" type="email" class="in @(HasError(ProfileService.EmailInvalid) ? "err" : null)" @bind="_email" @bind:event="oninput"
autocomplete="email" />
<span class="hint">@T["Pages.Profile.Account.EmailHint"]</span>
</div>
@foreach (var message in _messages)
{
<div class="c12 kh-alert err" role="alert">@message</div>
}
<div class="c12 kh-formactions">
<button type="submit" class="btn primary" disabled="@(!IsModified || _busy)"><KhIcon Name="save" /> @T["Pages.Profile.Save"]</button>
</div>
</div>
</fieldset>
<fieldset class="fgroup">
<legend class="fgh"><KhIcon Name="info" /> @T["Pages.Profile.Account.About"]</legend>
<dl class="kh-facts">
<dt>@T["Pages.Profile.Account.Kind"]</dt>
<dd>@T[Session.LevelKey]</dd>
<dt>@T["Pages.Profile.Account.Company"]</dt>
<dd>@(Session.Company?.Name ?? T["Pages.Profile.Sessions.InstanceAccount"])</dd>
<dt>@T["Pages.Profile.Account.LastLogin"]</dt>
<dd>@(_info.LastLoginAt is { } last ? T.DateTime(last, TimeZoneInfo.Local) : T["Pages.Profile.Account.Never"])</dd>
<dt>@T["Pages.Profile.Account.PasswordChanged"]</dt>
<dd>@(_info.PasswordChangedAt is { } changed ? T.DateTime(changed, TimeZoneInfo.Local) : T["Pages.Profile.Account.Never"])</dd>
<dt>@T["Pages.Profile.Account.TwoStep"]</dt>
<dd>
@if (_info.TotpEnabled)
{
<span class="badge green">@T["Pages.Profile.Security.TotpOn"]</span>
}
else
{
<span class="badge amber">@T["Pages.Profile.Security.TotpOff"]</span>
}
</dd>
</dl>
</fieldset>
</form>
}
@code {
private ProfileInfo? _info;
private string? _displayName;
private string? _email;
private IReadOnlyList<string> _errors = [];
private IReadOnlyList<string> _messages = [];
private bool _busy;
private bool _reported;
/// <summary>The account of the session.</summary>
[Parameter, EditorRequired]
public SessionOwner? Owner { get; set; }
/// <summary>The tab of the page, to show the modified mark.</summary>
[CascadingParameter]
public KhTab? Tab { get; set; }
private bool IsModified => _info is not null && (_displayName != _info.DisplayName || (_email ?? string.Empty) != (_info.Email ?? string.Empty));
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
if (Owner is not null)
{
_info = await Profiles.GetAsync(Owner);
_displayName = _info?.DisplayName;
_email = _info?.Email;
}
}
/// <inheritdoc />
protected override void OnAfterRender(bool firstRender)
{
// Only a change of state is reported, so the mark set by another section of the page is left alone.
if (IsModified != _reported)
{
_reported = IsModified;
Tab?.SetModified(_reported);
}
}
private bool HasError(string code) => _errors.Contains(code);
private async Task SaveAsync()
{
if (Owner is null || !IsModified || _busy)
{
return;
}
_busy = true;
try
{
_errors = await Profiles.UpdateAsync(Owner, _displayName, _email);
_messages = LoginFlow.Messages(T, Policy, string.Join(',', _errors));
if (_errors.Count == 0)
{
_info = await Profiles.GetAsync(Owner);
_displayName = _info?.DisplayName;
_email = _info?.Email;
Session.SetDisplayName(_displayName);
Toasts.Show(ToastKind.Success, T["Pages.Profile.Account.Saved"]);
}
}
finally
{
_busy = false;
}
}
}
@@ -0,0 +1,258 @@
@using Khaemhat.Application.Security
@using Khaemhat.Web.Security
@inject ProfileService Profiles
@inject ShellSession Session
@inject ToastService Toasts
@inject DialogService Dialogs
@inject SecurityPolicyOptions Policy
@* "Password e verifica in due passaggi" of the profile (SPEC §7.3, §12, issue #31). A password change closes the other
sessions; turning the verification off and renewing the recovery codes ask for the password again. *@
@if (_info is null)
{
<div class="pb"><p class="muted">@T["Common.Loading"]</p></div>
}
else
{
<div class="fgroups">
@if (_info.HasPassword)
{
<form class="fgroup" @onsubmit="ChangePasswordAsync" @onsubmit:preventDefault>
<div class="fgh"><KhIcon Name="lock" /> @T["Pages.Profile.Security.Password"]</div>
<div class="form">
<div class="f c12">
<label for="kh-s-current">@T["Pages.Profile.Security.Current"]</label>
<input id="kh-s-current" type="password" class="in" @bind="_current" autocomplete="current-password" required />
</div>
<div class="f c12">
<label for="kh-s-new">@T["Pages.Profile.Security.New"]</label>
<input id="kh-s-new" type="password" class="in" @bind="_new" @bind:event="oninput" autocomplete="new-password" required />
<span class="hint">@T.Format("Pages.Profile.Security.Rules", Policy.MinimumLength, Policy.HistorySize)</span>
</div>
<div class="f c12">
<label for="kh-s-repeat">@T["Pages.Profile.Security.Repeat"]</label>
<input id="kh-s-repeat" type="password" class="in @(Mismatch ? "err" : null)" @bind="_repeat" @bind:event="oninput" autocomplete="new-password" required />
@if (Mismatch)
{
<span class="hint err">@T["Pages.Profile.Security.Mismatch"]</span>
}
</div>
@foreach (var message in _passwordMessages)
{
<div class="c12 kh-alert err" role="alert">@message</div>
}
<div class="c12 kh-formactions">
<button type="submit" class="btn primary" disabled="@(!CanChangePassword)"><KhIcon Name="key" /> @T["Pages.Profile.Security.Change"]</button>
</div>
<p class="c12 muted">@T["Pages.Profile.Security.ChangeNote"]</p>
</div>
</form>
}
<section class="fgroup">
<div class="fgh"><KhIcon Name="shield" /> @T["Pages.Profile.Security.TwoStep"]</div>
<div class="pb">
<p>
@if (_info.TotpEnabled)
{
<span class="badge green">@T["Pages.Profile.Security.TotpOn"]</span>
}
else
{
<span class="badge amber">@T["Pages.Profile.Security.TotpOff"]</span>
}
@if (_info.TotpRequired)
{
<span class="badge">@T["Pages.Profile.Security.TotpRequired"]</span>
}
</p>
@if (_recoveryCodes is not null)
{
<div class="callout warn"><KhIcon Name="alert" /> <span>@T["Pages.Profile.Security.CodesOnce"]</span></div>
<ul class="kh-codes">
@foreach (var recovery in _recoveryCodes)
{
<li><code>@recovery</code></li>
}
</ul>
<button type="button" class="btn" @onclick="() => _recoveryCodes = null"><KhIcon Name="check" /> @T["Pages.Profile.Security.CodesDone"]</button>
}
else if (!_info.TotpEnabled && _setup is null)
{
<p class="muted">@T["Pages.Profile.Security.TotpIntro"]</p>
<button type="button" class="btn primary" @onclick="BeginSetupAsync"><KhIcon Name="shield" /> @T["Pages.Profile.Security.Enable"]</button>
}
else if (!_info.TotpEnabled && _setup is not null)
{
<p class="muted">@T["Pages.Profile.Security.SetupText"]</p>
<dl class="kh-secret">
<dt>@T["Auth.TotpSetup.Secret"]</dt>
<dd><code>@Grouped(_setup.Secret)</code></dd>
<dt>@T["Auth.TotpSetup.Phone"]</dt>
<dd><a href="@_setup.ProvisioningUri">@T["Auth.TotpSetup.OpenInApp"]</a></dd>
</dl>
<form class="form plain" @onsubmit="ConfirmSetupAsync" @onsubmit:preventDefault>
<div class="f c6">
<label for="kh-s-code">@T["Auth.TotpSetup.FirstCode"]</label>
<input id="kh-s-code" class="in mono" @bind="_code" inputmode="numeric" autocomplete="one-time-code" maxlength="6" required />
</div>
@if (_codeWrong)
{
<div class="c12 kh-alert err" role="alert">@T["Auth.Errors.totp_invalid"]</div>
}
<div class="c12 kh-formactions">
<button type="button" class="btn ghost" @onclick="() => _setup = null">@T["Common.Cancel"]</button>
<button type="submit" class="btn primary"><KhIcon Name="check" /> @T["Auth.TotpSetup.Submit"]</button>
</div>
</form>
}
else
{
<p class="muted">@T.Format("Pages.Profile.Security.CodesLeft", _info.RecoveryCodesLeft)</p>
<form class="form plain" @onsubmit:preventDefault>
<div class="f c8">
<label for="kh-s-confirm">@T["Pages.Profile.Security.ConfirmPassword"]</label>
<input id="kh-s-confirm" type="password" class="in" @bind="_confirm" @bind:event="oninput" autocomplete="current-password" />
</div>
@foreach (var message in _totpMessages)
{
<div class="c12 kh-alert err" role="alert">@message</div>
}
<div class="c12 kh-formactions">
<button type="button" class="btn" disabled="@string.IsNullOrEmpty(_confirm)" @onclick="RenewCodesAsync"><KhIcon Name="refresh" /> @T["Pages.Profile.Security.Renew"]</button>
@if (!_info.TotpRequired)
{
<button type="button" class="btn danger" disabled="@string.IsNullOrEmpty(_confirm)" @onclick="DisableAsync"><KhIcon Name="x" /> @T["Pages.Profile.Security.Disable"]</button>
}
</div>
</form>
}
</div>
</section>
</div>
}
@code {
private ProfileInfo? _info;
private string? _current;
private string? _new;
private string? _repeat;
private string? _code;
private string? _confirm;
private bool _codeWrong;
private bool _busy;
private TotpSetup? _setup;
private IReadOnlyList<string>? _recoveryCodes;
private IReadOnlyList<string> _passwordMessages = [];
private IReadOnlyList<string> _totpMessages = [];
/// <summary>The account of the session.</summary>
[Parameter, EditorRequired]
public SessionOwner? Owner { get; set; }
/// <summary>The session that stays open after a password change.</summary>
[Parameter]
public long? CurrentSessionId { get; set; }
private bool Mismatch => !string.IsNullOrEmpty(_repeat) && _repeat != _new;
private bool CanChangePassword => !_busy && !string.IsNullOrEmpty(_current) && !string.IsNullOrEmpty(_new) && _new == _repeat;
/// <inheritdoc />
protected override Task OnInitializedAsync() => ReloadAsync();
private async Task ReloadAsync() => _info = Owner is null ? null : await Profiles.GetAsync(Owner);
private async Task ChangePasswordAsync()
{
if (Owner is null || !CanChangePassword)
{
return;
}
_busy = true;
try
{
var errors = await Profiles.ChangePasswordAsync(Owner, CurrentSessionId, _current!, _new!);
_passwordMessages = LoginFlow.Messages(T, Policy, string.Join(',', errors));
if (errors.Count == 0)
{
_current = _new = _repeat = null;
await ReloadAsync();
Toasts.Show(ToastKind.Success, T["Pages.Profile.Security.Changed"], T["Pages.Profile.Security.ChangedText"]);
}
}
finally
{
_busy = false;
}
}
private async Task BeginSetupAsync()
{
if (Owner is not null)
{
_codeWrong = false;
_setup = await Profiles.BeginTotpSetupAsync(Owner, Session.Company?.Code);
}
}
private async Task ConfirmSetupAsync()
{
if (Owner is null || string.IsNullOrWhiteSpace(_code))
{
return;
}
var codes = await Profiles.ConfirmTotpSetupAsync(Owner, _code);
_code = null;
_codeWrong = codes is null;
if (codes is not null)
{
_setup = null;
_recoveryCodes = codes;
await ReloadAsync();
Toasts.Show(ToastKind.Success, T["Pages.Profile.Security.Enabled"]);
}
}
private async Task RenewCodesAsync()
{
if (Owner is null || string.IsNullOrEmpty(_confirm))
{
return;
}
var codes = await Profiles.RenewRecoveryCodesAsync(Owner, _confirm);
_confirm = null;
_totpMessages = codes is null ? LoginFlow.Messages(T, Policy, SecurityErrors.CurrentPasswordWrong) : [];
if (codes is not null)
{
_recoveryCodes = codes;
await ReloadAsync();
}
}
private async Task DisableAsync()
{
if (Owner is null || string.IsNullOrEmpty(_confirm)
|| !await Dialogs.ConfirmAsync(new(T["Pages.Profile.Security.DisableTitle"], T["Pages.Profile.Security.DisableText"],
T["Pages.Profile.Security.Disable"], T["Common.Cancel"], Danger: true)))
{
return;
}
var errors = await Profiles.DisableTotpAsync(Owner, _confirm);
_confirm = null;
_totpMessages = LoginFlow.Messages(T, Policy, string.Join(',', errors));
if (errors.Count == 0)
{
await ReloadAsync();
Toasts.Show(ToastKind.Warning, T["Pages.Profile.Security.Disabled"]);
}
}
private static string Grouped(string secret) =>
string.Join(' ', Enumerable.Range(0, (secret.Length + 3) / 4).Select(i => secret.Substring(i * 4, Math.Min(4, secret.Length - (i * 4)))));
}
@@ -0,0 +1,22 @@
@* A state badge with its dot (SPEC §10.7): Emessa, Pagata, Scaduta... *@
<span class="badge @ToneClass">@ChildContent</span>
@code {
/// <summary>The tone.</summary>
[Parameter]
public KhTone Tone { get; set; }
/// <summary>The text.</summary>
[Parameter]
public RenderFragment? ChildContent { get; set; }
private string ToneClass => Tone switch
{
KhTone.Accent => "accent",
KhTone.Info => "blue",
KhTone.Ok => "green",
KhTone.Warning => "amber",
KhTone.Error => "red",
_ => "gray",
};
}
@@ -0,0 +1,17 @@
@inherits KhInputBase<bool>
@* A check box with its text on the right (SPEC §10.7). In the grid it lines up with the other fields. *@
<KhField For="@InputId" Hint="@Hint" Messages="Messages" Span="Span">
<label class="chk kh-check">
<input id="@InputId" type="checkbox" checked="@Value" disabled="@(Disabled || IsReadOnly)" aria-describedby="@DescribedBy"
@onchange="OnChangeAsync" @attributes="Attributes" />
@Label
</label>
</KhField>
@code {
/// <inheritdoc />
protected override bool IsEmpty(bool value) => !value;
private Task OnChangeAsync(ChangeEventArgs e) => SetValueAsync(e.Value is true);
}
@@ -0,0 +1,57 @@
@* A chip (SPEC §10.5.2, §10.7). Info chips summarise a condition: icon, a short label and a bold value ("Pagamento
RB 60 gg"). With OnRemove it becomes a filter chip with a remove button. *@
@if (OnRemove.HasDelegate)
{
<span class="chip">
@Text @Value
<button type="button" class="x kh-chipx" aria-label="@T.Format("Ui.Chip.Remove", Text + " " + Value)" @onclick="OnRemove"><KhIcon Name="x" Class="sm" /></button>
</span>
}
else
{
<span class="ichip @ToneClass" title="@Title">
@if (Icon is not null)
{
<KhIcon Name="@Icon" />
}
@Text
@if (Value is not null)
{
<b>@Value</b>
}
</span>
}
@code {
/// <summary>The icon.</summary>
[Parameter]
public string? Icon { get; set; }
/// <summary>The label.</summary>
[Parameter]
public string? Text { get; set; }
/// <summary>The value, in bold.</summary>
[Parameter]
public string? Value { get; set; }
/// <summary>A tooltip with the details.</summary>
[Parameter]
public string? Title { get; set; }
/// <summary>The tone: accent, warning, error.</summary>
[Parameter]
public KhTone Tone { get; set; }
/// <summary>Makes it a removable filter chip.</summary>
[Parameter]
public EventCallback OnRemove { get; set; }
private string? ToneClass => Tone switch
{
KhTone.Accent => "acc",
KhTone.Warning => "warn",
KhTone.Error => "err",
_ => null,
};
}
@@ -0,0 +1,47 @@
@* A contextual action of a document (SPEC §10.4): icon and a short label (three words at most), the main one filled.
Labels never wrap. *@
<button type="button" class="ctx @ToneClass" disabled="@Disabled" title="@(Shortcut is null ? null : KeyboardShortcuts.Pretty(Shortcut))" @onclick="OnClick" @attributes="Attributes">
<KhIcon Name="@Icon" /> @Text
</button>
@code {
/// <summary>The icon.</summary>
[Parameter, EditorRequired]
public string Icon { get; set; } = string.Empty;
/// <summary>The label.</summary>
[Parameter, EditorRequired]
public string Text { get; set; } = string.Empty;
/// <summary>The main action of the document.</summary>
[Parameter]
public bool Primary { get; set; }
/// <summary>The colour.</summary>
[Parameter]
public KhTone Tone { get; set; }
/// <summary>Not usable now.</summary>
[Parameter]
public bool Disabled { get; set; }
/// <summary>The shortcut, in the tooltip.</summary>
[Parameter]
public string? Shortcut { get; set; }
/// <summary>What it does.</summary>
[Parameter]
public EventCallback OnClick { get; set; }
/// <summary>Other attributes.</summary>
[Parameter(CaptureUnmatchedValues = true)]
public IReadOnlyDictionary<string, object>? Attributes { get; set; }
private string? ToneClass => Primary ? "primary" : Tone switch
{
KhTone.Ok => "ok",
KhTone.Warning => "warn",
KhTone.Error => "danger",
_ => null,
};
}
@@ -0,0 +1,114 @@
@inherits KhInputBase<DateOnly?>
@inject TimeProvider Clock
@* A date as gg/mm/aaaa (SPEC §10.7): short forms (5, 5/3, 050326), T today, F end of month, I start of month, + and -
one day (typed as text, or a key press when the field holds a whole date), arrows up and down one day. *@
<KhField Label="@Label" For="@InputId" Required="Required" Hint="@Hint" Messages="Messages" Span="Span">
<span class="in kh-datebox @(Messages.Count > 0 ? "err" : null) @(IsReadOnly ? "ro" : null)">
<input id="@InputId" value="@_text" placeholder="@T["Ui.Date.Placeholder"]" inputmode="numeric" maxlength="10"
readonly="@IsReadOnly" disabled="@Disabled" aria-required="@AriaRequired" aria-invalid="@AriaInvalid"
aria-describedby="@DescribedBy" data-kh-prevent="@(IsReadOnly ? null : "ArrowUp ArrowDown")" data-kh-datestep
@onchange="OnChangeAsync" @onkeydown="OnKeyDownAsync" @attributes="Attributes" @ref="_input" />
<KhIcon Name="calendar" Class="sm" />
</span>
</KhField>
@code {
private string _text = string.Empty;
private DateOnly? _shown;
private bool _first = true;
private ElementReference _input;
/// <summary>The first date accepted.</summary>
[Parameter]
public DateOnly? Min { get; set; }
/// <summary>The last date accepted.</summary>
[Parameter]
public DateOnly? Max { get; set; }
[Inject]
private IJSRuntime JS { get; set; } = default!;
private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
/// <inheritdoc />
protected override void OnParametersSet()
{
base.OnParametersSet();
if (_first || (ParseError is null && Value != _shown))
{
_first = false;
_shown = Value;
_text = Value is { } date ? T.Date(date) : string.Empty;
}
}
/// <inheritdoc />
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JS.InvokeVoidAsync("khaemhat.preventKeys", _input);
}
}
/// <inheritdoc />
public override IEnumerable<string> Validate()
{
foreach (var message in base.Validate())
{
yield return message;
yield break;
}
if (Value is { } v && Min is { } min && v < min)
{
yield return T.Format("Ui.Validation.DateMin", T.Date(min));
}
else if (Value is { } w && Max is { } max && w > max)
{
yield return T.Format("Ui.Validation.DateMax", T.Date(max));
}
}
private async Task OnChangeAsync(ChangeEventArgs e)
{
_text = e.Value as string ?? string.Empty;
StateHasChanged();
await Task.Yield();
await ApplyAsync(_text);
}
private async Task OnKeyDownAsync(KeyboardEventArgs e)
{
if (IsReadOnly || e.CtrlKey || e.AltKey)
{
return;
}
var step = e.Key switch
{
"ArrowUp" => "+",
"ArrowDown" => "-",
_ => null,
};
if (step is not null)
{
await ApplyAsync(step);
}
}
private async Task ApplyAsync(string text)
{
if (!ItalianDate.TryParse(text, Today, Value, out var date))
{
ParseError = T["Ui.Validation.Date"];
return;
}
_shown = date;
_text = date is { } d ? T.Date(d) : string.Empty;
await SetValueAsync(date);
}
}
@@ -0,0 +1,82 @@
@inject IJSRuntime JS
@* A modal dialog (SPEC §10.7): title with icon, content, buttons at the bottom right. Escape and the close button
call OnClose; the focus moves into the dialog when it opens. *@
@if (Open)
{
<div class="overlay" @onkeydown="OnKeyDownAsync">
<div class="dialog kh-dialog @SizeClass" role="dialog" aria-modal="true" aria-labelledby="@(_id + "-t")" @ref="_dialog">
<div class="dh">
@if (Icon is not null)
{
<KhIcon Name="@Icon" />
}
<span class="grow" id="@(_id + "-t")">@Title</span>
<button type="button" class="ib kh-close" aria-label="@T["Common.Close"]" @onclick="CloseAsync"><KhIcon Name="x" /></button>
</div>
<div class="db">@ChildContent</div>
@if (Footer is not null)
{
<div class="df">@Footer</div>
}
</div>
</div>
}
@code {
private static int _next;
private readonly string _id = "kh-dlg" + Interlocked.Increment(ref _next).ToString(System.Globalization.CultureInfo.InvariantCulture);
private ElementReference _dialog;
private bool _wasOpen;
/// <summary>Whether the dialog is shown.</summary>
[Parameter]
public bool Open { get; set; }
/// <summary>The title.</summary>
[Parameter]
public string? Title { get; set; }
/// <summary>The icon before the title.</summary>
[Parameter]
public string? Icon { get; set; }
/// <summary>The width: <c>sm</c> (420 px), <c>md</c> (640 px), <c>lg</c> (860 px).</summary>
[Parameter]
public string Size { get; set; } = "md";
/// <summary>Called by Escape and the close button.</summary>
[Parameter]
public EventCallback OnClose { get; set; }
/// <summary>The content.</summary>
[Parameter]
public RenderFragment? ChildContent { get; set; }
/// <summary>The buttons.</summary>
[Parameter]
public RenderFragment? Footer { get; set; }
private string SizeClass => "kh-" + Size;
/// <inheritdoc />
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (Open && !_wasOpen)
{
await JS.InvokeVoidAsync("khaemhat.focusFirst", _dialog);
}
_wasOpen = Open;
}
private async Task OnKeyDownAsync(KeyboardEventArgs e)
{
if (e.Key == "Escape")
{
await CloseAsync();
}
}
private Task CloseAsync() => OnClose.InvokeAsync();
}
@@ -0,0 +1,131 @@
@* The header of a document or master record (SPEC §10.5.2, mockups 020, 021, 014) in three blocks: on the left the
kind (icon, label, big number, meta line, state badges); in the middle the counterpart (initials, name with code,
detail lines, condition chips); on the right the total with three sub-values, or the KPIs of a master record. *@
<div class="dochead kh-dochead @Class">
<div>
<div class="kind">
<span class="kb" aria-hidden="true"><KhIcon Name="@KindIcon" /></span>
<div>
<div class="kl">@KindLabel</div>
<div class="kn">@Number</div>
</div>
</div>
@if (Facts is not null || State is not null)
{
<div class="meta">@Facts @State</div>
}
</div>
<div>
@if (Party is not null)
{
@Party
}
else if (PartyName is not null)
{
<div class="party">
<span class="av" aria-hidden="true">@Initials</span>
<div class="kh-min0">
<div class="pn">
<span class="kh-ellipsis">@PartyName</span>
@if (PartyCode is not null)
{
<span class="code">@PartyCode</span>
}
</div>
@foreach (var line in PartyLines ?? [])
{
<div class="ps">@line</div>
}
</div>
</div>
}
@if (Chips is not null)
{
<div class="chips">@Chips</div>
}
</div>
<div class="tot">
@if (Totals is not null)
{
@Totals
}
else
{
<span class="tl">@TotalLabel</span>
<span class="tv">@TotalValue</span>
@if (SubValues is { Count: > 0 })
{
<span class="ts">
@foreach (var sub in SubValues)
{
<span>@sub.Label <b>@sub.Value</b></span>
}
</span>
}
}
</div>
</div>
@code {
/// <summary>The icon of the kind.</summary>
[Parameter]
public string KindIcon { get; set; } = "file";
/// <summary>The kind: "Fattura immediata · TD01", "Cliente".</summary>
[Parameter]
public string? KindLabel { get; set; }
/// <summary>The number or code, big.</summary>
[Parameter]
public string? Number { get; set; }
/// <summary>The meta line: date, section, register.</summary>
[Parameter]
public RenderFragment? Facts { get; set; }
/// <summary>The state badges.</summary>
[Parameter]
public RenderFragment? State { get; set; }
/// <summary>The counterpart name.</summary>
[Parameter]
public string? PartyName { get; set; }
/// <summary>The counterpart code.</summary>
[Parameter]
public string? PartyCode { get; set; }
/// <summary>The lines under the name: address, VAT number, PEC.</summary>
[Parameter]
public IReadOnlyList<string>? PartyLines { get; set; }
/// <summary>The whole middle block, in place of the counterpart parameters.</summary>
[Parameter]
public RenderFragment? Party { get; set; }
/// <summary>The condition chips (KhChip).</summary>
[Parameter]
public RenderFragment? Chips { get; set; }
/// <summary>The label of the total.</summary>
[Parameter]
public string? TotalLabel { get; set; }
/// <summary>The total, formatted.</summary>
[Parameter]
public string? TotalValue { get; set; }
/// <summary>The three values under the total (taxable, VAT, stamp...).</summary>
[Parameter]
public IReadOnlyList<KhStat>? SubValues { get; set; }
/// <summary>The whole right block, in place of the total parameters (KPIs of a master record).</summary>
[Parameter]
public RenderFragment? Totals { get; set; }
/// <summary>Extra classes.</summary>
[Parameter]
public string? Class { get; set; }
private string Initials => ShellSession.InitialsOf(PartyName ?? string.Empty);
}
@@ -0,0 +1,78 @@
@inject IJSRuntime JS
@* A side panel from the right (SPEC §10.7): details, attachments, the dashboard "Personalizza". Not modal: the page
stays usable; Escape and the close button call OnClose. *@
@if (Open)
{
<aside class="drawer kh-drawer @(Wide ? "wide" : null)" role="complementary" aria-labelledby="@(_id + "-t")" @onkeydown="OnKeyDownAsync" @ref="_drawer">
<div class="dh">
@if (Icon is not null)
{
<KhIcon Name="@Icon" />
}
<span class="grow" id="@(_id + "-t")">@Title</span>
<button type="button" class="ib kh-close" aria-label="@T["Common.Close"]" @onclick="CloseAsync"><KhIcon Name="x" /></button>
</div>
<div class="db">@ChildContent</div>
@if (Footer is not null)
{
<div class="df">@Footer</div>
}
</aside>
}
@code {
private static int _next;
private readonly string _id = "kh-drw" + Interlocked.Increment(ref _next).ToString(System.Globalization.CultureInfo.InvariantCulture);
private ElementReference _drawer;
private bool _wasOpen;
/// <summary>Whether the panel is shown.</summary>
[Parameter]
public bool Open { get; set; }
/// <summary>The title.</summary>
[Parameter]
public string? Title { get; set; }
/// <summary>The icon before the title.</summary>
[Parameter]
public string? Icon { get; set; }
/// <summary>A wider panel (560 px).</summary>
[Parameter]
public bool Wide { get; set; }
/// <summary>Called by Escape and the close button.</summary>
[Parameter]
public EventCallback OnClose { get; set; }
/// <summary>The content.</summary>
[Parameter]
public RenderFragment? ChildContent { get; set; }
/// <summary>The buttons.</summary>
[Parameter]
public RenderFragment? Footer { get; set; }
/// <inheritdoc />
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (Open && !_wasOpen)
{
await JS.InvokeVoidAsync("khaemhat.focusFirst", _drawer);
}
_wasOpen = Open;
}
private async Task OnKeyDownAsync(KeyboardEventArgs e)
{
if (e.Key == "Escape")
{
await CloseAsync();
}
}
private Task CloseAsync() => OnClose.InvokeAsync();
}
@@ -0,0 +1,20 @@
@implements IDisposable
@inject DrawerService Drawers
@* Shows the side panel opened with DrawerService (SPEC §10.7). *@
@if (Drawers.Current is { } request)
{
<KhDrawer Open="true" Title="@request.Title" Icon="@request.Icon" Wide="request.Wide" OnClose="Drawers.Close" Footer="request.Footer">
@request.Content
</KhDrawer>
}
@code {
/// <inheritdoc />
protected override void OnInitialized() => Drawers.Changed += OnChanged;
/// <inheritdoc />
public void Dispose() => Drawers.Changed -= OnChanged;
private void OnChanged() => _ = InvokeAsync(StateHasChanged);
}
@@ -0,0 +1,57 @@
@* A field of the 12-column form grid (SPEC §10.5.4): label above, asterisk when required, the input, the hint and the
messages under it. The input components use it; a page can wrap any custom input with it. *@
<div class="f @SpanClass">
@if (Label is not null)
{
<label for="@For">
@Label
@if (Required)
{
<span class="req" aria-hidden="true">*</span>
}
</label>
}
@ChildContent
@if (Messages is { Count: > 0 })
{
<span class="hint err" id="@DescribedBy" role="alert">@string.Join(" ", Messages)</span>
}
else if (Hint is not null)
{
<span class="hint" id="@DescribedBy">@Hint</span>
}
</div>
@code {
/// <summary>The label.</summary>
[Parameter]
public string? Label { get; set; }
/// <summary>The id of the input the label belongs to.</summary>
[Parameter]
public string? For { get; set; }
/// <summary>Shows the required mark.</summary>
[Parameter]
public bool Required { get; set; }
/// <summary>A suggestion under the field.</summary>
[Parameter]
public string? Hint { get; set; }
/// <summary>The messages of the field.</summary>
[Parameter]
public IReadOnlyList<string>? Messages { get; set; }
/// <summary>The columns taken (1-12); 0 leaves the width to the container.</summary>
[Parameter]
public int Span { get; set; } = 6;
/// <summary>The input.</summary>
[Parameter]
public RenderFragment? ChildContent { get; set; }
private string? SpanClass => Span is > 0 and <= 12 ? "c" + Span.ToString(System.Globalization.CultureInfo.InvariantCulture) : null;
private string? DescribedBy => For is null ? null : For + "-d";
}
@@ -0,0 +1,37 @@
@* A group of fields (SPEC §10.5.4): a titled box with its own 12-column grid. Inside a KhForm with Layout Groups the
groups stand side by side; Wide takes the whole row. *@
<section class="fgroup @(Wide ? "wide" : null) @Class" aria-labelledby="@_id">
<div class="fgh" id="@_id">
@if (Icon is not null)
{
<KhIcon Name="@Icon" />
}
@Title
</div>
<div class="form">@ChildContent</div>
</section>
@code {
private static int _next;
private readonly string _id = "kh-fg" + Interlocked.Increment(ref _next).ToString(System.Globalization.CultureInfo.InvariantCulture);
/// <summary>The title.</summary>
[Parameter, EditorRequired]
public string Title { get; set; } = string.Empty;
/// <summary>The icon.</summary>
[Parameter]
public string? Icon { get; set; }
/// <summary>Takes the whole row.</summary>
[Parameter]
public bool Wide { get; set; }
/// <summary>Extra classes.</summary>
[Parameter]
public string? Class { get; set; }
/// <summary>The fields.</summary>
[Parameter]
public RenderFragment? ChildContent { get; set; }
}
+146
View File
@@ -0,0 +1,146 @@
@implements IDisposable
@inject IJSRuntime JS
@* A form (SPEC §10.5.4, §10.5.6): the fields check themselves on submit, the messages appear next to each field and
in a summary at the top whose entries move the focus to the field. Read-only applies to every field inside. *@
<form class="@FormClass" novalidate @onsubmit="SubmitAsync" @onsubmit:preventDefault>
<CascadingValue Value="_context">
@if (ShowSummary && Summary.Count > 0)
{
<div class="kh-vsum @(Layout == KhFormLayout.Groups ? "wide" : "c12")" role="alert" tabindex="-1" @ref="_summary">
<KhIcon Name="alert" />
<div>
<b>@T.Format("Ui.Validation.Summary", Summary.Count)</b>
<ul>
@foreach (var message in Summary)
{
<li>
@if (message.InputId is not null)
{
<button type="button" class="kh-link" @onclick="() => FocusAsync(message.InputId)">@(message.Label is null ? message.Message : message.Label + ": " + message.Message)</button>
}
else
{
@message.Message
}
</li>
}
</ul>
</div>
</div>
}
@ChildContent
</CascadingValue>
</form>
@code {
private KhFormContext _context = default!;
private KhValidation? _subscribed;
private ElementReference _summary;
private bool _focusSummary;
/// <summary>The messages; give one to add the messages the services return. A new one is made otherwise.</summary>
[Parameter]
public KhValidation? Validation { get; set; }
/// <summary>Every field is read-only.</summary>
[Parameter]
public bool ReadOnly { get; set; }
/// <summary>The arrangement of the children.</summary>
[Parameter]
public KhFormLayout Layout { get; set; } = KhFormLayout.Grid;
/// <summary>Shows the summary of the messages.</summary>
[Parameter]
public bool ShowSummary { get; set; } = true;
/// <summary>Extra classes.</summary>
[Parameter]
public string? Class { get; set; }
/// <summary>Called when the fields are valid.</summary>
[Parameter]
public EventCallback OnValidSubmit { get; set; }
/// <summary>The fields.</summary>
[Parameter]
public RenderFragment? ChildContent { get; set; }
/// <summary>The context given to the fields.</summary>
public KhFormContext Context => _context;
private string FormClass => Layout switch
{
KhFormLayout.Groups => "fgroups " + Class,
KhFormLayout.Plain => "form plain " + Class,
_ => "form " + Class,
};
// The messages with the label and input of their field, also those the page added by name.
private IReadOnlyList<KhValidationMessage> Summary =>
[.. _context.Validation.Messages.Select(m => m.InputId is null && _context.Find(m.Field) is { } f ? m with { Label = f.Label, InputId = f.InputId } : m)];
/// <inheritdoc />
protected override void OnParametersSet()
{
var validation = Validation ?? _subscribed ?? new KhValidation();
if (!ReferenceEquals(validation, _subscribed))
{
if (_subscribed is not null)
{
_subscribed.Changed -= OnChanged;
}
validation.Changed += OnChanged;
_subscribed = validation;
_context = new KhFormContext(validation);
}
_context.ReadOnly = ReadOnly;
}
/// <summary>Checks the fields as on submit, without calling <see cref="OnValidSubmit"/>.</summary>
/// <returns>Whether the form is valid.</returns>
public bool Validate()
{
var valid = _context.Validate();
_focusSummary = !valid;
StateHasChanged();
return valid;
}
/// <inheritdoc />
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (_focusSummary && Summary.Count > 0)
{
_focusSummary = false;
await _summary.FocusAsync();
}
}
private async Task SubmitAsync()
{
if (ReadOnly || !Validate())
{
return;
}
await OnValidSubmit.InvokeAsync();
_focusSummary = !_context.Validation.IsValid;
}
private async Task FocusAsync(string inputId) => await JS.InvokeVoidAsync("khaemhat.focus", "#" + inputId);
private void OnChanged() => _ = InvokeAsync(StateHasChanged);
/// <inheritdoc />
public void Dispose()
{
if (_subscribed is not null)
{
_subscribed.Changed -= OnChanged;
}
}
}
@@ -0,0 +1,300 @@
@typeparam TItem
@inherits KhInputBase<TItem>
@implements IAsyncDisposable
@inject IJSRuntime JS
@* A link to another record (SPEC §10.5.4, §10.7): the code in evidence, the description beside it, incremental search
while typing, F4 or the magnifier opens the radar, Ctrl+Enter or the arrow opens the record, and "Crea" adds a new
one from the text typed. Leaving the field with a code resolves it; an unknown code is an error. *@
<KhField Label="@Label" For="@InputId" Required="Required" Hint="@Hint" Messages="Messages" Span="Span">
<div class="kh-hotlink">
<span class="in @(Messages.Count > 0 ? "err" : null) @(IsReadOnly ? "ro" : null)">
<input id="@InputId" class="code" value="@_text" autocomplete="off" role="combobox" aria-autocomplete="list"
aria-expanded="@(_open ? "true" : "false")" aria-controls="@ListId" aria-activedescendant="@ActiveId"
readonly="@IsReadOnly" disabled="@Disabled" aria-required="@AriaRequired" aria-invalid="@AriaInvalid"
aria-describedby="@DescribedBy" data-kh-prevent="@PreventedKeys" placeholder="@Placeholder"
@oninput="OnInput" @onchange="OnChangeAsync" @onkeydown="OnKeyDownAsync" @onblur="Close" @ref="_input" @attributes="Attributes" />
<span class="desc">@(Value is { } item && !_typing ? DescriptionOf(item) : null)</span>
<span class="lk">
@if (OnRadar.HasDelegate && !IsReadOnly)
{
<button type="button" class="kh-lk" title="@T["Ui.Hotlink.Search"]" aria-label="@T["Ui.Hotlink.Search"]" tabindex="-1" @onclick="RadarAsync"><KhIcon Name="search" /></button>
}
@if (OnOpen.HasDelegate && Value is not null)
{
<button type="button" class="kh-lk" title="@T["Ui.Hotlink.Open"]" aria-label="@T["Ui.Hotlink.Open"]" tabindex="-1" @onclick="OpenAsync"><KhIcon Name="external" /></button>
}
</span>
</span>
@if (_open)
{
<ul class="kh-hits" id="@ListId" role="listbox" @onmousedown:preventDefault>
@for (var i = 0; i < _hits.Count; i++)
{
var index = i;
var hit = _hits[i];
<li id="@(ListId + "-" + index)" role="option" aria-selected="@(index == _active ? "true" : "false")" class="@(index == _active ? "on" : null)"
@onclick="() => SelectAsync(hit)">
<span class="code">@CodeOf(hit)</span> <span class="desc">@DescriptionOf(hit)</span>
</li>
}
@if (_hits.Count == 0 && !_searching)
{
<li class="none" role="presentation">@T["Ui.Hotlink.None"]</li>
}
@if (CanCreate)
{
<li id="@(ListId + "-new")" role="option" aria-selected="@(_active == _hits.Count ? "true" : "false")" class="new @(_active == _hits.Count ? "on" : null)"
@onclick="CreateAsync">
<KhIcon Name="plus" Class="sm" /> @T.Format("Ui.Hotlink.Create", _text)
</li>
}
</ul>
}
</div>
</KhField>
@code {
private string _text = string.Empty;
private TItem? _shown;
private bool _first = true;
private bool _open;
private bool _typing;
private bool _searching;
private int _active;
private IReadOnlyList<TItem> _hits = [];
private CancellationTokenSource? _search;
private ElementReference _input;
/// <summary>Finds the records matching a text (code or description), a few at most.</summary>
[Parameter, EditorRequired]
public Func<string, CancellationToken, Task<IReadOnlyList<TItem>>> Search { get; set; } = default!;
/// <summary>The code of a record.</summary>
[Parameter, EditorRequired]
public Func<TItem, string> CodeOf { get; set; } = default!;
/// <summary>The description of a record.</summary>
[Parameter, EditorRequired]
public Func<TItem, string> DescriptionOf { get; set; } = default!;
/// <summary>Opens the radar to choose (F4), with the text typed.</summary>
[Parameter]
public EventCallback<string> OnRadar { get; set; }
/// <summary>Opens the chosen record (Ctrl+Enter).</summary>
[Parameter]
public EventCallback<TItem> OnOpen { get; set; }
/// <summary>Creates a record from the text typed; the page then sets the value.</summary>
[Parameter]
public EventCallback<string> OnCreate { get; set; }
/// <summary>The text shown while empty.</summary>
[Parameter]
public string? Placeholder { get; set; }
/// <summary>The wait after the last key before searching.</summary>
[Parameter]
public int DelayMilliseconds { get; set; } = 200;
private string ListId => InputId + "-l";
private string? ActiveId => !_open ? null : _active < _hits.Count ? ListId + "-" + _active : CanCreate ? ListId + "-new" : null;
private bool CanCreate => OnCreate.HasDelegate && _typing && !string.IsNullOrWhiteSpace(_text);
private string? PreventedKeys => IsReadOnly ? null : _open ? "ArrowUp ArrowDown Enter Ctrl+Enter F4" : "ArrowDown Ctrl+Enter F4";
/// <inheritdoc />
protected override void OnParametersSet()
{
base.OnParametersSet();
if (_first || (!_typing && !EqualityComparer<TItem>.Default.Equals(Value!, _shown!)))
{
_first = false;
_shown = Value;
_text = Value is { } item ? CodeOf(item) : string.Empty;
}
}
/// <inheritdoc />
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JS.InvokeVoidAsync("khaemhat.preventKeys", _input);
}
}
private void OnInput(ChangeEventArgs e)
{
_text = e.Value as string ?? string.Empty;
_typing = true;
ParseError = null;
_ = SearchAsync(_text);
}
private async Task SearchAsync(string text)
{
if (_search is not null)
{
await _search.CancelAsync();
_search.Dispose();
}
var cancel = new CancellationTokenSource();
_search = cancel;
if (string.IsNullOrWhiteSpace(text))
{
_open = false;
return;
}
try
{
await Task.Delay(DelayMilliseconds, cancel.Token);
_searching = true;
var hits = await Search(text.Trim(), cancel.Token);
if (cancel.IsCancellationRequested)
{
return;
}
_hits = hits;
_active = 0;
_open = true;
_searching = false;
await InvokeAsync(StateHasChanged);
}
catch (OperationCanceledException)
{
// A newer search took over.
}
}
private async Task OnKeyDownAsync(KeyboardEventArgs e)
{
if (IsReadOnly)
{
return;
}
var count = _hits.Count + (CanCreate ? 1 : 0);
switch (e.Key)
{
case "ArrowDown" when !_open:
await SearchNowAsync();
break;
case "ArrowDown" when count > 0:
_active = (_active + 1) % count;
break;
case "ArrowUp" when _open && count > 0:
_active = (_active - 1 + count) % count;
break;
case "Enter" when e.CtrlKey:
await OpenAsync();
break;
case "Enter" when _open && _active < _hits.Count:
await SelectAsync(_hits[_active]);
break;
case "Enter" when _open && CanCreate:
await CreateAsync();
break;
case "Escape" when _open || _typing:
Restore();
break;
case "F4":
await RadarAsync();
break;
}
}
private async Task SearchNowAsync()
{
_searching = true;
_hits = await Search(_text.Trim(), CancellationToken.None);
_searching = false;
_active = 0;
_open = true;
}
// Leaving the field after typing: the exact code, or the only match, is taken; an empty text clears the value.
private async Task OnChangeAsync(ChangeEventArgs e)
{
if (!_typing)
{
return;
}
var text = (e.Value as string ?? string.Empty).Trim();
if (text.Length == 0)
{
await SelectAsync(default);
return;
}
var hits = await Search(text, CancellationToken.None);
var match = hits.FirstOrDefault(h => string.Equals(CodeOf(h), text, StringComparison.OrdinalIgnoreCase));
if (match is not null || hits.Count == 1)
{
await SelectAsync(match ?? hits[0]);
}
else
{
ParseError = T.Format("Ui.Hotlink.NotFound", text);
}
}
private async Task SelectAsync(TItem? item)
{
_typing = false;
_open = false;
_shown = item;
_text = item is { } chosen ? CodeOf(chosen) : string.Empty;
await SetValueAsync(item);
}
private void Restore()
{
_typing = false;
_open = false;
ParseError = null;
_text = Value is { } item ? CodeOf(item) : string.Empty;
}
private void Close() => _open = false;
private async Task RadarAsync()
{
_open = false;
await OnRadar.InvokeAsync(_typing ? _text : string.Empty);
}
private async Task OpenAsync()
{
if (Value is { } item)
{
await OnOpen.InvokeAsync(item);
}
}
private async Task CreateAsync()
{
var text = _text.Trim();
Restore();
await OnCreate.InvokeAsync(text);
}
/// <inheritdoc />
public async ValueTask DisposeAsync()
{
if (_search is not null)
{
await _search.CancelAsync();
_search.Dispose();
}
Dispose();
}
}
@@ -0,0 +1,73 @@
@* A 32x32 icon command (SPEC §10.4): no label, a tooltip with the name and the shortcut, an optional counter. *@
@if (Href is not null && !Disabled)
{
<a class="ib @Classes" href="@Href" aria-label="@Text" @attributes="Attributes">@Inner</a>
}
else
{
<button type="button" class="ib @Classes" aria-label="@Text" aria-pressed="@(Active ? "true" : null)" disabled="@Disabled"
@onclick="OnClick" @attributes="Attributes">@Inner</button>
}
@code {
/// <summary>The icon.</summary>
[Parameter, EditorRequired]
public string Icon { get; set; } = string.Empty;
/// <summary>The name: tooltip and accessible name.</summary>
[Parameter, EditorRequired]
public string Text { get; set; } = string.Empty;
/// <summary>The shortcut shown in the tooltip.</summary>
[Parameter]
public string? Shortcut { get; set; }
/// <summary>A counter badge.</summary>
[Parameter]
public int? Count { get; set; }
/// <summary>Filled with the accent (Save).</summary>
[Parameter]
public bool Primary { get; set; }
/// <summary>Destructive.</summary>
[Parameter]
public bool Danger { get; set; }
/// <summary>Toggled on.</summary>
[Parameter]
public bool Active { get; set; }
/// <summary>Not usable now.</summary>
[Parameter]
public bool Disabled { get; set; }
/// <summary>What it does.</summary>
[Parameter]
public EventCallback OnClick { get; set; }
/// <summary>Makes it a link.</summary>
[Parameter]
public string? Href { get; set; }
/// <summary>Other attributes.</summary>
[Parameter(CaptureUnmatchedValues = true)]
public IReadOnlyDictionary<string, object>? Attributes { get; set; }
private string Classes => string.Join(' ', new[] { Primary ? "primary" : null, Danger ? "danger" : null, Active ? "on" : null, Disabled ? "disabled" : null }.Where(c => c is not null));
private RenderFragment Inner => @<text>
<KhIcon Name="@Icon" />
@if (Count is > 0)
{
<span class="cnt" aria-hidden="true">@(Count > 99 ? "99+" : Count)</span>
}
<span class="tip" role="tooltip">
@Text
@if (Shortcut is not null)
{
<kbd>@KeyboardShortcuts.Pretty(Shortcut)</kbd>
}
</span>
</text>;
}
@@ -0,0 +1,203 @@
@implements IAsyncDisposable
@inject IJSRuntime JS
@inject NavigationManager Navigation
@* The command bar of a page (SPEC §10.4, mockup 020): icon groups on the left, at most four contextual actions, the
right group (radar, previous, next) and the "⋯" menu with the rest. The bar always stays on one line: when it is too
narrow the commands with the highest priority move into the menu (measured in the browser, khaemhat.watchToolbar). *@
<div class="toolbar icons kh-toolbar @Class" role="toolbar" aria-label="@Label" @ref="_bar">
@{ var first = true; }
@foreach (var group in Start.GroupBy(i => i.Group))
{
if (!first)
{
<span class="sep" aria-hidden="true"></span>
}
first = false;
<div class="grp" data-ovf-group>
@foreach (var item in group)
{
@Icon(item)
}
</div>
}
@if (Actions.Count > 0)
{
<span class="sep" aria-hidden="true"></span>
<div class="grp kh-actionsgrp" data-ovf-group>
@foreach (var item in Actions.Take(MaxActions))
{
<KhContextAction Icon="@item.Icon" Text="@item.Text" Primary="item.Primary" Tone="item.Tone" Disabled="item.Disabled"
Shortcut="@item.Shortcut" OnClick="() => RunAsync(item)" data-ovf="@PriorityOf(item)" data-id="@item.Id" />
}
</div>
}
<span class="grow"></span>
@foreach (var item in End)
{
@Icon(item)
}
<div class="pop kh-morewrap">
<KhIconButton Icon="more" Text="@T["Ui.Toolbar.More"]" Active="_menu" OnClick="ToggleMenu" aria-haspopup="menu" aria-expanded="@(_menu ? "true" : "false")" />
@if (_menu)
{
<div class="kh-catch" @onclick="CloseMenu"></div>
<div class="popmenu kh-moremenu" role="menu" @onkeydown="OnMenuKey" @ref="_menuRef">
@foreach (var item in MenuItems)
{
<button type="button" role="menuitem" class="mi @(item.Danger ? "danger" : null)" disabled="@item.Disabled" @onclick="() => RunAsync(item)">
<KhIcon Name="@item.Icon" /><span class="grow">@item.Text</span>
@if (item.Shortcut is not null)
{
<span class="k">@KeyboardShortcuts.Pretty(item.Shortcut)</span>
}
</button>
}
@if (MenuItems.Count == 0)
{
<div class="fh">@T["Ui.Toolbar.Empty"]</div>
}
</div>
}
</div>
</div>
@code {
private ElementReference _bar;
private ElementReference _menuRef;
private bool _placeMenu;
private DotNetObjectReference<KhIconToolbar>? _self;
private HashSet<string> _overflow = new(StringComparer.Ordinal);
private bool _menu;
private bool _watching;
/// <summary>The most contextual actions shown on the bar (SPEC §10.4).</summary>
public const int MaxActions = 4;
/// <summary>The commands.</summary>
[Parameter, EditorRequired]
public IReadOnlyList<ToolbarItem> Items { get; set; } = [];
/// <summary>The accessible name of the bar.</summary>
[Parameter]
public string? Label { get; set; }
/// <summary>Extra classes.</summary>
[Parameter]
public string? Class { get; set; }
private IEnumerable<ToolbarItem> Start => Items.Where(i => i.Kind == ToolbarKind.Icon && !i.End);
private IEnumerable<ToolbarItem> End => Items.Where(i => i.Kind == ToolbarKind.Icon && i.End);
private List<ToolbarItem> Actions => [.. Items.Where(i => i.Kind == ToolbarKind.Action)];
// The menu: what does not fit, the fifth action onwards, and the commands that live only there.
private List<ToolbarItem> MenuItems =>
[
.. Items.Where(i => i.Kind != ToolbarKind.Menu && _overflow.Contains(i.Id)),
.. Actions.Skip(MaxActions),
.. Items.Where(i => i.Kind == ToolbarKind.Menu),
];
/// <summary>The ids of the commands moved into the menu, for the tests.</summary>
public IReadOnlyCollection<string> Overflow => _overflow;
private static string? PriorityOf(ToolbarItem item) =>
item.Priority > 0 ? item.Priority.ToString(System.Globalization.CultureInfo.InvariantCulture) : null;
private RenderFragment Icon(ToolbarItem item) =>
@<KhIconButton Icon="@item.Icon" Text="@item.Text" Shortcut="@item.Shortcut" Count="item.Count" Primary="item.Primary" Danger="item.Danger"
Active="item.Active" Disabled="item.Disabled" Href="@item.Href" OnClick="() => RunAsync(item)"
data-ovf="@PriorityOf(item)" data-id="@item.Id" />;
/// <inheritdoc />
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!_watching)
{
_watching = true;
_self = DotNetObjectReference.Create(this);
await JS.InvokeVoidAsync("khaemhat.watchToolbar", _bar, _self);
}
else
{
await JS.InvokeVoidAsync("khaemhat.fitToolbar", _bar);
}
// The menu is placed against the window, so a container that clips its content cannot cut it.
if (_placeMenu && _menu)
{
_placeMenu = false;
await JS.InvokeVoidAsync("khaemhat.placeMenu", _menuRef);
}
}
/// <summary>Called by the browser with the commands that do not fit.</summary>
/// <param name="ids">The ids moved into the menu.</param>
[JSInvokable]
public void SetOverflow(string[] ids)
{
var next = new HashSet<string>(ids ?? [], StringComparer.Ordinal);
if (!next.SetEquals(_overflow))
{
_overflow = next;
StateHasChanged();
}
}
private void ToggleMenu()
{
_menu = !_menu;
_placeMenu = _menu;
}
private void CloseMenu() => _menu = false;
private void OnMenuKey(KeyboardEventArgs e)
{
if (e.Key == "Escape")
{
_menu = false;
}
}
private async Task RunAsync(ToolbarItem item)
{
_menu = false;
if (item.Disabled)
{
return;
}
if (item.Href is not null)
{
Navigation.NavigateTo(item.Href);
}
else if (item.OnClick is not null)
{
await item.OnClick();
}
}
/// <inheritdoc />
public async ValueTask DisposeAsync()
{
if (_self is null)
{
return;
}
try
{
await JS.InvokeVoidAsync("khaemhat.unwatchToolbar", _bar);
}
catch (JSDisconnectedException)
{
// The page is gone with the circuit.
}
_self.Dispose();
}
}
@@ -0,0 +1,20 @@
@* An amount in euro in the Italian format with tabular figures (SPEC §10.7); negative amounts in red when asked. *@
<span class="kh-money @(Value < 0 && RedWhenNegative ? "neg" : null) @Class">@(Value is { } v ? T.Money(v) : Empty)</span>
@code {
/// <summary>The amount.</summary>
[Parameter]
public decimal? Value { get; set; }
/// <summary>Shows negative amounts in red.</summary>
[Parameter]
public bool RedWhenNegative { get; set; }
/// <summary>The text when there is no amount.</summary>
[Parameter]
public string? Empty { get; set; }
/// <summary>Extra classes.</summary>
[Parameter]
public string? Class { get; set; }
}
@@ -0,0 +1,81 @@
@inherits KhInputBase<decimal?>
@* A number in the Italian format (SPEC §10.7): comma for decimals, point for thousands, and the inline calculation
when the text starts with "=" (=10*3 gives 30). The value is rounded to the decimals of the field. *@
<KhField Label="@Label" For="@InputId" Required="Required" Hint="@Hint" Messages="Messages" Span="Span">
<input id="@InputId" class="@InputClass num" inputmode="decimal" value="@_text" placeholder="@Placeholder"
readonly="@IsReadOnly" disabled="@Disabled" aria-required="@AriaRequired" aria-invalid="@AriaInvalid"
aria-describedby="@DescribedBy" @onchange="OnChangeAsync" @attributes="Attributes" />
</KhField>
@code {
private string _text = string.Empty;
private decimal? _shown;
private bool _first = true;
/// <summary>The decimals kept and shown.</summary>
[Parameter]
public int Decimals { get; set; } = 2;
/// <summary>The smallest value accepted.</summary>
[Parameter]
public decimal? Min { get; set; }
/// <summary>The largest value accepted.</summary>
[Parameter]
public decimal? Max { get; set; }
/// <summary>The text shown while empty.</summary>
[Parameter]
public string? Placeholder { get; set; }
/// <inheritdoc />
protected override void OnParametersSet()
{
base.OnParametersSet();
if (_first || (ParseError is null && Value != _shown))
{
_first = false;
_shown = Value;
_text = ItalianNumber.Format(Value, Decimals, T.Culture);
}
}
/// <inheritdoc />
public override IEnumerable<string> Validate()
{
foreach (var message in base.Validate())
{
yield return message;
yield break;
}
if (Value is { } v && Min is { } min && v < min)
{
yield return T.Format("Ui.Validation.Min", T.Number(min, Decimals));
}
else if (Value is { } w && Max is { } max && w > max)
{
yield return T.Format("Ui.Validation.Max", T.Number(max, Decimals));
}
}
private async Task OnChangeAsync(ChangeEventArgs e)
{
// Render the typed text first: the browser holds it already, so the formatted text below differs from the last
// render and reaches the page even when the value does not change (=1+1 over 2,00).
_text = e.Value as string ?? string.Empty;
StateHasChanged();
await Task.Yield();
if (!ItalianNumber.TryParse(_text, out var value))
{
ParseError = T["Ui.Validation.Number"];
return;
}
value = value is { } v ? Math.Round(v, Decimals, MidpointRounding.AwayFromZero) : null;
_shown = value;
_text = ItalianNumber.Format(value, Decimals, T.Culture);
await SetValueAsync(value);
}
}
@@ -0,0 +1,53 @@
@* A panel with a header (SPEC §10.7): icon, title, actions on the right, an optional link. *@
<section class="panel @Class" aria-label="@Title">
@if (Title is not null || Actions is not null)
{
<div class="ph">
@if (Icon is not null)
{
<KhIcon Name="@Icon" />
}
<span class="grow">@Title</span>
@Actions
@if (LinkHref is not null)
{
<a class="lnk" href="@LinkHref">@LinkText</a>
}
</div>
}
<div class="pb @(Tight ? "tight" : null)">@ChildContent</div>
</section>
@code {
/// <summary>The title.</summary>
[Parameter]
public string? Title { get; set; }
/// <summary>The icon before the title.</summary>
[Parameter]
public string? Icon { get; set; }
/// <summary>Buttons on the right of the header.</summary>
[Parameter]
public RenderFragment? Actions { get; set; }
/// <summary>A link on the right of the header ("Vedi tutti").</summary>
[Parameter]
public string? LinkHref { get; set; }
/// <summary>The text of the link.</summary>
[Parameter]
public string? LinkText { get; set; }
/// <summary>No padding around the content (a grid, a list).</summary>
[Parameter]
public bool Tight { get; set; }
/// <summary>Extra classes.</summary>
[Parameter]
public string? Class { get; set; }
/// <summary>The content.</summary>
[Parameter]
public RenderFragment? ChildContent { get; set; }
}
@@ -0,0 +1,24 @@
@* The frame of a record page (SPEC §10.5, mockups 020, 021): toolbar, header, tabs and the content of the active tab.
The page derives from DocumentPage or MasterDataPage and passes itself as Page. *@
<div class="kh-record">
<KhIconToolbar Items="Page.Toolbar" Label="@T["Ui.Toolbar.Label"]" />
@Heading
<section class="panel kh-recordbody">
<KhTabs Items="Page.Tabs" Active="@Page.ActiveTab" ActiveChanged="Page.ShowTabAsync" Label="@T["Ui.Record.TabsLabel"]" />
<div class="kh-recordtab" role="tabpanel">@ChildContent</div>
</section>
</div>
@code {
/// <summary>The page.</summary>
[Parameter, EditorRequired]
public IRecordPage Page { get; set; } = default!;
/// <summary>The header (KhDocHead).</summary>
[Parameter]
public RenderFragment? Heading { get; set; }
/// <summary>The content of the active tab.</summary>
[Parameter]
public RenderFragment? ChildContent { get; set; }
}
@@ -0,0 +1,49 @@
@using System.Globalization
@typeparam TValue
@inherits KhInputBase<TValue>
@* A choice from a short list (SPEC §10.7). Long lists of records use KhHotlink. *@
<KhField Label="@Label" For="@InputId" Required="Required" Hint="@Hint" Messages="Messages" Span="Span">
<select id="@InputId" class="@InputClass" disabled="@(Disabled || IsReadOnly)" aria-required="@AriaRequired" aria-invalid="@AriaInvalid"
aria-describedby="@DescribedBy" @onchange="OnChangeAsync" @attributes="Attributes">
@if (Empty is not null || Selected < 0)
{
<option value="-1" selected="@(Selected < 0)">@(Empty ?? string.Empty)</option>
}
@for (var i = 0; i < Options.Count; i++)
{
<option value="@i.ToString(CultureInfo.InvariantCulture)" selected="@(i == Selected)">@Options[i].Text</option>
}
</select>
</KhField>
@code {
/// <summary>The choices.</summary>
[Parameter, EditorRequired]
public IReadOnlyList<KhOption<TValue>> Options { get; set; } = [];
/// <summary>The text of the empty choice; <see langword="null"/> shows none when a value is chosen.</summary>
[Parameter]
public string? Empty { get; set; }
private int Selected
{
get
{
for (var i = 0; i < Options.Count; i++)
{
if (EqualityComparer<TValue>.Default.Equals(Options[i].Value, Value!))
{
return i;
}
}
return -1;
}
}
private Task OnChangeAsync(ChangeEventArgs e) =>
int.TryParse(e.Value as string, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var index) && index >= 0 && index < Options.Count
? SetValueAsync(Options[index].Value)
: SetValueAsync(default);
}
@@ -0,0 +1,62 @@
@* The steps of a procedure (SPEC §10.7): horizontal over a wizard, or vertical (KhVSteps style) beside it. Steps
before Current are done. *@
@if (Vertical)
{
<ol class="vsteps kh-steps" aria-label="@Label">
@for (var i = 0; i < Items.Count; i++)
{
var step = Items[i];
<li class="vstep @StateOf(i)" aria-current="@(i == Current ? "step" : null)">
<span class="n">@NumberOf(i)</span>
<span>
@step.Title
@if (step.Detail is not null)
{
<span class="vs">@step.Detail</span>
}
</span>
</li>
}
</ol>
}
else
{
<ol class="steps kh-steps" aria-label="@Label">
@for (var i = 0; i < Items.Count; i++)
{
var step = Items[i];
<li class="step @StateOf(i)" aria-current="@(i == Current ? "step" : null)">
<span class="n">@NumberOf(i)</span>
@step.Title
@if (i < Items.Count - 1)
{
<span class="ln" aria-hidden="true"></span>
}
</li>
}
</ol>
}
@code {
private RenderFragment NumberOf(int index) => index < Current
? builder => { builder.OpenComponent<KhIcon>(0); builder.AddAttribute(1, nameof(KhIcon.Name), "check"); builder.AddAttribute(2, nameof(KhIcon.Class), "sm"); builder.CloseComponent(); }
: builder => builder.AddContent(0, index + 1);
/// <summary>The steps.</summary>
[Parameter, EditorRequired]
public IReadOnlyList<KhStep> Items { get; set; } = [];
/// <summary>The index of the current step.</summary>
[Parameter]
public int Current { get; set; }
/// <summary>Vertical layout.</summary>
[Parameter]
public bool Vertical { get; set; }
/// <summary>The accessible name.</summary>
[Parameter]
public string? Label { get; set; }
private string? StateOf(int index) => index < Current ? "done" : index == Current ? "on" : null;
}
@@ -0,0 +1,32 @@
@* A strip of figures side by side (SPEC §10.7): totals over a list, the state of a procedure. *@
<div class="strip @Class" role="group" aria-label="@Label">
@foreach (var stat in Items)
{
<div>
<span class="sl">@stat.Label</span>
<span class="sv @ToneClass(stat.Tone)">@stat.Value</span>
</div>
}
</div>
@code {
/// <summary>The figures.</summary>
[Parameter, EditorRequired]
public IReadOnlyList<KhStat> Items { get; set; } = [];
/// <summary>The accessible name of the strip.</summary>
[Parameter]
public string? Label { get; set; }
/// <summary>Extra classes.</summary>
[Parameter]
public string? Class { get; set; }
private static string? ToneClass(KhTone tone) => tone switch
{
KhTone.Ok => "ok",
KhTone.Warning => "warn",
KhTone.Error => "err",
_ => null,
};
}
@@ -0,0 +1,25 @@
@inherits KhInputBase<bool>
@* An on/off switch (SPEC §10.7): a button with role switch, operable with Space and Enter. *@
<KhField Label="@Label" For="@InputId" Hint="@Hint" Messages="Messages" Span="Span">
<button id="@InputId" type="button" role="switch" class="kh-switch" aria-checked="@(Value ? "true" : "false")"
disabled="@(Disabled || IsReadOnly)" aria-describedby="@DescribedBy" @onclick="ToggleAsync" @attributes="Attributes">
<span class="switch @(Value ? "on" : null)" aria-hidden="true"></span>
<span>@(Value ? OnText ?? T["Common.On"] : OffText ?? T["Common.Off"])</span>
</button>
</KhField>
@code {
/// <summary>The text when on; defaults to "Attivo".</summary>
[Parameter]
public string? OnText { get; set; }
/// <summary>The text when off; defaults to "Disattivo".</summary>
[Parameter]
public string? OffText { get; set; }
/// <inheritdoc />
protected override bool IsEmpty(bool value) => !value;
private Task ToggleAsync() => SetValueAsync(!Value);
}
+108
View File
@@ -0,0 +1,108 @@
@implements IDisposable
@inject KeyboardShortcutService Keys
@* The tabs of a page (SPEC §10.5.3): icon, text, counter; Alt+1..9 picks the tab by position while the page is the
active one. With HrefOf the tabs are links (the address keeps the tab), otherwise buttons. *@
<div class="tabs i @Class" role="tablist" aria-label="@Label">
@for (var i = 0; i < Items.Count; i++)
{
var item = Items[i];
var active = item.Id == Active;
var key = i < 9 ? "Alt+" + (i + 1).ToString(System.Globalization.CultureInfo.InvariantCulture) : null;
if (HrefOf is not null)
{
<a class="tab @(active ? "active" : null)" role="tab" aria-selected="@(active ? "true" : "false")" href="@HrefOf(item)" title="@key">
<KhIcon Name="@item.Icon" /> @item.Text
@if (item.Count is { } n)
{
<span class="n">@n</span>
}
</a>
}
else
{
<button type="button" class="tab @(active ? "active" : null)" role="tab" aria-selected="@(active ? "true" : "false")" title="@key"
tabindex="@(active ? 0 : -1)" @onclick="() => SelectAsync(item)">
<KhIcon Name="@item.Icon" /> @item.Text
@if (item.Count is { } n)
{
<span class="n">@n</span>
}
</button>
}
}
</div>
@code {
/// <summary>The tabs.</summary>
[Parameter, EditorRequired]
public IReadOnlyList<KhTabItem> Items { get; set; } = [];
/// <summary>The id of the active tab.</summary>
[Parameter]
public string? Active { get; set; }
/// <summary>Called when the user picks a tab.</summary>
[Parameter]
public EventCallback<string> ActiveChanged { get; set; }
/// <summary>Makes the tabs links: the address of each tab.</summary>
[Parameter]
public Func<KhTabItem, string>? HrefOf { get; set; }
/// <summary>Alt+1..9 picks the tabs (one tab bar per page should have it).</summary>
[Parameter]
public bool Shortcuts { get; set; } = true;
/// <summary>The accessible name of the tab bar.</summary>
[Parameter]
public string? Label { get; set; }
/// <summary>Extra classes.</summary>
[Parameter]
public string? Class { get; set; }
/// <summary>The tab of the shell holding the page: the shortcuts work only while it is active.</summary>
[CascadingParameter]
public KhTab? Tab { get; set; }
[Inject]
private NavigationManager Navigation { get; set; } = default!;
/// <inheritdoc />
protected override void OnInitialized() => Keys.PagePressed += OnShortcutAsync;
private async Task SelectAsync(KhTabItem item)
{
if (item.Id != Active)
{
Active = item.Id;
await ActiveChanged.InvokeAsync(item.Id);
}
}
private async Task OnShortcutAsync(string command)
{
if (!Shortcuts || (Tab is not null && !Tab.IsActive) || !KeyboardShortcuts.TryGetTabNumber(command, out var number) || number > Items.Count)
{
return;
}
var item = Items[number - 1];
await InvokeAsync(async () =>
{
if (HrefOf is not null)
{
Navigation.NavigateTo(HrefOf(item));
}
else
{
await SelectAsync(item);
StateHasChanged();
}
});
}
/// <inheritdoc />
public void Dispose() => Keys.PagePressed -= OnShortcutAsync;
}
@@ -0,0 +1,24 @@
@inherits KhInputBase<string>
@* A text on several lines (SPEC §10.7). *@
<KhField Label="@Label" For="@InputId" Required="Required" Hint="@Hint" Messages="Messages" Span="Span">
<textarea id="@InputId" class="@InputClass" rows="@Rows" placeholder="@Placeholder" maxlength="@MaxLength" readonly="@IsReadOnly"
disabled="@Disabled" aria-required="@AriaRequired" aria-invalid="@AriaInvalid" aria-describedby="@DescribedBy"
value="@Value" @onchange="OnChangeAsync" @attributes="Attributes"></textarea>
</KhField>
@code {
/// <summary>The visible lines.</summary>
[Parameter]
public int Rows { get; set; } = 3;
/// <summary>The text shown while empty.</summary>
[Parameter]
public string? Placeholder { get; set; }
/// <summary>The longest text.</summary>
[Parameter]
public int? MaxLength { get; set; }
private Task OnChangeAsync(ChangeEventArgs e) => SetValueAsync(e.Value as string);
}
@@ -0,0 +1,28 @@
@inherits KhInputBase<string>
@* A text field (SPEC §10.7). Mono shows codes in the code font. *@
<KhField Label="@Label" For="@InputId" Required="Required" Hint="@Hint" Messages="Messages" Span="Span">
<input id="@InputId" class="@InputClass @(Mono ? "mono" : null)" type="@Type" value="@Value" placeholder="@Placeholder"
maxlength="@MaxLength" readonly="@IsReadOnly" disabled="@Disabled" aria-required="@AriaRequired" aria-invalid="@AriaInvalid"
aria-describedby="@DescribedBy" @onchange="OnChangeAsync" @attributes="Attributes" />
</KhField>
@code {
/// <summary>The input type: <c>text</c>, <c>email</c>, <c>tel</c>, <c>url</c>, <c>password</c>.</summary>
[Parameter]
public string Type { get; set; } = "text";
/// <summary>The text shown while empty.</summary>
[Parameter]
public string? Placeholder { get; set; }
/// <summary>The longest text.</summary>
[Parameter]
public int? MaxLength { get; set; }
/// <summary>Shows the value in the code font.</summary>
[Parameter]
public bool Mono { get; set; }
private Task OnChangeAsync(ChangeEventArgs e) => SetValueAsync(e.Value as string);
}
@@ -0,0 +1,60 @@
@* A KPI tile (SPEC §10.7): title with icon, big value, a detail line, a coloured edge for the tone. With Href the
whole tile is a link. *@
@if (Href is not null)
{
<a class="tile kh-tilelink @ToneClass" href="@Href">@Body</a>
}
else
{
<div class="tile @ToneClass">@Body</div>
}
@code {
/// <summary>The title.</summary>
[Parameter, EditorRequired]
public string Title { get; set; } = string.Empty;
/// <summary>The icon.</summary>
[Parameter]
public string? Icon { get; set; }
/// <summary>The value.</summary>
[Parameter]
public string? Value { get; set; }
/// <summary>The line under the value.</summary>
[Parameter]
public RenderFragment? Detail { get; set; }
/// <summary>The tone of the edge.</summary>
[Parameter]
public KhTone Tone { get; set; }
/// <summary>Makes the tile a link.</summary>
[Parameter]
public string? Href { get; set; }
private string? ToneClass => Tone switch
{
KhTone.Ok => "ok",
KhTone.Warning => "warn",
KhTone.Error => "err",
KhTone.Accent => "acc",
_ => null,
};
private RenderFragment Body => @<text>
<span class="t">
@if (Icon is not null)
{
<KhIcon Name="@Icon" Class="sm" />
}
@Title
</span>
<span class="v">@Value</span>
@if (Detail is not null)
{
<span class="d">@Detail</span>
}
</text>;
}
@@ -0,0 +1,16 @@
@* The vertical steps of a wizard (SPEC §10.7): KhSteps laid out in a column, with a line under each title. *@
<KhSteps Items="Items" Current="Current" Label="@Label" Vertical="true" />
@code {
/// <summary>The steps.</summary>
[Parameter, EditorRequired]
public IReadOnlyList<KhStep> Items { get; set; } = [];
/// <summary>The index of the current step.</summary>
[Parameter]
public int Current { get; set; }
/// <summary>The accessible name.</summary>
[Parameter]
public string? Label { get; set; }
}
+2 -1
View File
@@ -1,4 +1,4 @@
@using System.Net.Http
@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@@ -18,4 +18,5 @@
@using Khaemhat.Web.Shell
@using Khaemhat.Web.Components.Shell
@using Khaemhat.Web.Components.Ui
@using Khaemhat.Web.Ui
@inject ITexts T
@@ -114,6 +114,7 @@ internal static class KhaemhatServices
services.AddSingleton<SessionStore>();
services.AddSingleton<NotificationDispatcher>();
services.AddSingleton<SignInService>();
services.AddSingleton<ProfileService>();
// Companies and start.
services.AddSingleton<ICompanySeeder, PredefinedRolesSeeder>();
@@ -144,6 +145,7 @@ internal static class KhaemhatServices
services.AddScoped<KeyboardShortcutService>();
services.AddScoped<ToastService>();
services.AddScoped<DialogService>();
services.AddScoped<DrawerService>();
return services;
}
}
@@ -78,6 +78,9 @@
"level_too_low": "Il tuo livello di accesso non consente questa operazione.",
"permission_denied": "Il tuo profilo non ha il permesso per questa operazione.",
"module_not_licensed": "Il modulo non è compreso nella licenza.",
"display_name_invalid": "Il nome è obbligatorio e non può superare 100 caratteri.",
"email_invalid": "L'indirizzo e-mail non è valido.",
"totp_required": "La verifica in due passaggi è obbligatoria per il tuo account e non si può disattivare.",
"Other": "Accesso non riuscito."
}
}
+178 -3
View File
@@ -50,12 +50,14 @@
},
"Profile": {
"Title": "Il mio profilo",
"Subtitle": "Aspetto, pagina iniziale e scorciatoie da tastiera. Le scelte valgono solo per il tuo account.",
"Subtitle": "Dati personali, sicurezza, aspetto, pagina iniziale e scorciatoie da tastiera. Le scelte valgono solo per il tuo account.",
"Tabs": {
"Appearance": "Aspetto",
"Start": "Pagina iniziale",
"Shortcuts": "Scorciatoie",
"Sessions": "Sessioni"
"Account": "Dati personali",
"Security": "Password e 2FA",
"Sessions": "Sessioni",
"Shortcuts": "Scorciatoie"
},
"Theme": {
"_": "Tema",
@@ -141,6 +143,179 @@
"Revoked": "Sessione chiusa",
"RevokedMany": "Sessioni chiuse: {0}",
"None": "Nessuna altra sessione attiva."
},
"Account": {
"Data": "Dati personali",
"UserName": "Nome utente",
"DisplayName": "Nome visualizzato",
"Email": "E-mail",
"EmailHint": "Serve per il recupero della password e per le notifiche.",
"About": "Account",
"Kind": "Tipo di account",
"Company": "Azienda",
"LastLogin": "Ultimo accesso",
"PasswordChanged": "Password cambiata il",
"TwoStep": "Verifica in due passaggi",
"Never": "Mai",
"Saved": "Dati personali salvati"
},
"Security": {
"Password": "Password",
"Current": "Password attuale",
"New": "Nuova password",
"Repeat": "Ripeti la nuova password",
"Rules": "Almeno {0} caratteri e tre tipi tra minuscole, maiuscole, cifre e simboli; diversa dalle ultime {1}.",
"Mismatch": "Le due password non coincidono.",
"Change": "Cambia password",
"ChangeNote": "Dopo il cambio le altre sessioni aperte con il tuo account vengono chiuse.",
"Changed": "Password cambiata",
"ChangedText": "Le altre sessioni sono state chiuse.",
"TwoStep": "Verifica in due passaggi",
"TotpOn": "Attiva",
"TotpOff": "Non attiva",
"TotpRequired": "Obbligatoria",
"TotpIntro": "Oltre alla password, all'accesso viene chiesto un codice generato da un'app sul telefono (Google Authenticator, Microsoft Authenticator, Aegis...).",
"Enable": "Attiva la verifica",
"SetupText": "Aggiungi l'account nell'app con il codice segreto o con il collegamento, poi scrivi il primo codice che l'app mostra.",
"Enabled": "Verifica in due passaggi attivata",
"CodesOnce": "Conserva questi codici di recupero in un posto sicuro: ognuno sostituisce una volta il codice dell'app e non verranno mostrati di nuovo.",
"CodesDone": "Li ho conservati",
"CodesLeft": "Codici di recupero ancora utilizzabili: {0}.",
"ConfirmPassword": "Password attuale, per confermare",
"Renew": "Nuovi codici di recupero",
"Disable": "Disattiva la verifica",
"DisableTitle": "Disattivare la verifica in due passaggi?",
"DisableText": "All'accesso basterà la password. I codici di recupero non varranno più.",
"Disabled": "Verifica in due passaggi disattivata"
}
},
"Catalog": {
"Title": "Catalogo componenti",
"Subtitle": "I componenti Kh con tutti gli stati. Pagina di sviluppo: i dati sono finti.",
"DevOnly": "Questa pagina esiste solo nell'ambiente di sviluppo.",
"OpenDocument": "Documento di prova",
"Document": "Documento di prova",
"Modified": "Modificato",
"TabPlaceholder": "Il contenuto di questa scheda arriva con i documenti veri.",
"Sections": {
"Fields": "Campi",
"Panels": "Pannelli",
"Navigation": "Navigazione",
"Windows": "Finestre",
"Toolbar": "Toolbar e intestazione"
},
"Fields": {
"Document": "Documento",
"Conditions": "Condizioni",
"States": "Stati e verifica",
"Number": "Numero",
"NumberTaken": "Il numero è già usato da un altro documento (messaggio dal servizio).",
"Date": "Data",
"DateHint": "T oggi, F fine mese, + e - un giorno",
"Kind": "Tipo documento",
"KindInvoice": "TD01 · Fattura",
"KindCredit": "TD04 · Nota di credito",
"KindDeferred": "TD24 · Fattura differita",
"Party": "Cliente",
"PartyHint": "Scrivi codice o nome; F4 radar, Ctrl+Invio apre",
"Discount": "Sconto %",
"DiscountHint": "Da 0 a 100",
"Amount": "Importo",
"AmountHint": "Prova un calcolo: =10*3",
"Email": "E-mail",
"Split": "Scissione dei pagamenti",
"Stamp": "Bollo virtuale",
"Notes": "Note",
"Disabled": "Campo disattivato",
"DisabledValue": "Non modificabile",
"Validate": "Verifica",
"ServerError": "Errore dal servizio",
"ClearMessages": "Togli i messaggi",
"ReadOnly": "Sola lettura",
"Valid": "Tutti i campi sono validi",
"RadarOpened": "Qui si apre il radar dei clienti con il testo: {0}",
"PartyOpened": "Qui si apre la scheda di {0}",
"PartyCreated": "Creato il cliente {0}"
},
"Panels": {
"Revenue": "Fatturato dell'anno",
"RevenueDetail": "Rispetto all'anno scorso: +8%",
"Collected": "Incassato",
"Expiring": "In scadenza",
"Overdue": "Scaduto",
"Strip": "Riepilogo",
"Documents": "Documenti",
"Taxable": "Imponibile",
"Panel": "Pannello",
"Link": "Vedi tutti",
"Draft": "Bozza",
"Sent": "Inviata",
"Paid": "Pagata",
"Issued": "Emessa",
"Payment": "Pagamento",
"PaymentValue": "RB 60 gg",
"PriceList": "Listino",
"PriceListValue": "Rivenditori",
"Credit": "Fido superato",
"Blocked": "Cliente bloccato",
"Filter": "Stato:",
"FilterValue": "Da pagare"
},
"Navigation": {
"Tabs": "Schede",
"TabShown": "Scheda mostrata: {0}",
"Steps": "Passi",
"Step1": "Scegli i dati",
"Step1Detail": "Periodo e registri",
"Step2": "Controlla",
"Step2Detail": "Anteprima dei totali",
"Step3": "Conferma",
"Step3Detail": "Registrazione definitiva"
},
"Windows": {
"Title": "Dialoghi, pannelli, conferme e avvisi",
"Dialog": "Dialogo",
"DialogText": "Un dialogo modale: Esc chiude, il fuoco entra nel primo campo.",
"Drawer": "Pannello laterale",
"DrawerText": "Un pannello laterale non modale: la pagina resta usabile.",
"DrawerService": "Pannello da codice",
"DrawerServiceText": "Aperto con DrawerService da qualunque punto del codice.",
"Confirm": "Conferma",
"Confirmed": "Confermato",
"Cancelled": "Annullato",
"ToastText": "Un avviso breve in basso a destra.",
"Toast": {
"Info": "Informazione",
"Success": "Fatto",
"Warning": "Attenzione",
"Error": "Errore"
}
},
"Toolbar": {
"Intro": "Trascina il bordo destro del riquadro per stringere la toolbar: i comandi meno usati passano nel menu ⋯ senza andare a capo.",
"Issue": "Conferma ed emetti",
"Xml": "XML SDI",
"Post": "Contabilizza",
"Ddt": "Genera DDT",
"Final": "Rendi definitiva",
"Settings": "Impostazioni del documento",
"Clicked": "Comando: {0}"
},
"Head": {
"Kind": "Fattura immediata · TD01",
"Section": "Sezionale",
"Total": "Totale documento",
"VatAmount": "IVA",
"Stamp": "Bollo",
"Address": "Via di Prova 1, 00100 Roma (RM)",
"Vat": "P.IVA 00000000000"
},
"Lines": {
"Code": "Articolo",
"Description": "Descrizione",
"Quantity": "Quantità",
"Price": "Prezzo",
"Amount": "Importo"
}
}
}
+2 -1
View File
@@ -197,7 +197,8 @@
"Radar": "Radar",
"PreviousRecord": "Record precedente",
"NextRecord": "Record successivo",
"Balance": "Quadra la registrazione"
"Balance": "Quadra la registrazione",
"PageTab": "Scheda della pagina per posizione"
},
"Error": {
"Unexpected": "Si è verificato un errore imprevisto.",
+67
View File
@@ -0,0 +1,67 @@
{
"Ui": {
"Validation": {
"Required": "Campo obbligatorio.",
"Number": "Non è un numero valido: usa la virgola per i decimali oppure un calcolo come =10*3.",
"Date": "Non è una data valida: scrivi gg/mm/aaaa, oppure T per oggi, F per fine mese.",
"Min": "Il valore minimo è {0}.",
"Max": "Il valore massimo è {0}.",
"DateMin": "La data non può essere prima del {0}.",
"DateMax": "La data non può essere dopo il {0}.",
"Summary": "Da correggere prima di salvare: {0}"
},
"Date": {
"Placeholder": "gg/mm/aaaa"
},
"Hotlink": {
"Search": "Cerca nel radar (F4)",
"Open": "Apri la scheda (Ctrl+Invio)",
"None": "Nessun risultato",
"Create": "Crea «{0}»",
"NotFound": "Il codice «{0}» non esiste."
},
"Chip": {
"Remove": "Togli il filtro {0}"
},
"Toolbar": {
"Label": "Comandi",
"More": "Altri comandi",
"Empty": "Nessun altro comando",
"New": "Nuovo",
"Save": "Salva",
"Cancel": "Annulla le modifiche",
"Delete": "Elimina",
"Duplicate": "Duplica",
"Print": "Stampa",
"Email": "Invia per e-mail",
"Export": "Genera file",
"Attachments": "Allegati",
"History": "Storico",
"Links": "Collegamenti",
"Radar": "Radar",
"Previous": "Precedente",
"Next": "Successivo"
},
"Record": {
"TabsLabel": "Sezioni",
"Invalid": "Ci sono dati da correggere: vedi i messaggi accanto ai campi.",
"Saved": "Salvato",
"Deleted": "Eliminato",
"DiscardTitle": "Annullare le modifiche?",
"DiscardText": "Le modifiche non salvate andranno perse e verranno ricaricati i dati salvati.",
"Discard": "Annulla le modifiche",
"DeleteTitle": "Eliminare?",
"DeleteText": "L'eliminazione non si può annullare.",
"Tabs": {
"Lines": "Righe",
"Header": "Testata",
"Totals": "Totali",
"DueDates": "Scadenze",
"Notes": "Note",
"Attachments": "Allegati",
"Links": "Collegamenti",
"History": "Storico"
}
}
}
}
+50
View File
@@ -106,3 +106,53 @@ public sealed class DialogService
pending?.TrySetResult(confirmed);
}
}
/// <summary>A side panel opened from code (SPEC §10.7 <c>DrawerService</c>).</summary>
/// <param name="Title">The title.</param>
/// <param name="Icon">The icon.</param>
/// <param name="Content">The content.</param>
/// <param name="Footer">The buttons, or <see langword="null"/>.</param>
/// <param name="Wide">A wider panel.</param>
public sealed record DrawerRequest(string Title, string? Icon, Microsoft.AspNetCore.Components.RenderFragment Content,
Microsoft.AspNetCore.Components.RenderFragment? Footer = null, bool Wide = false);
/// <summary>
/// Opens one side panel at a time from code; <c>KhDrawerHost</c> in the layout shows it. A page that owns its panel
/// can also write <c>&lt;KhDrawer Open="..."&gt;</c> directly.
/// </summary>
public sealed class DrawerService
{
private TaskCompletionSource? _closed;
/// <summary>Raised when the panel opens, closes or must be drawn again.</summary>
public event Action? Changed;
/// <summary>The panel shown, or <see langword="null"/>.</summary>
public DrawerRequest? Current { get; private set; }
/// <summary>Shows a panel, closing the previous one.</summary>
/// <param name="request">The panel.</param>
/// <returns>A task that ends when the panel is closed.</returns>
public Task ShowAsync(DrawerRequest request)
{
ArgumentNullException.ThrowIfNull(request);
_closed?.TrySetResult();
_closed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
Current = request;
Changed?.Invoke();
return _closed.Task;
}
/// <summary>Closes the panel.</summary>
public void Close()
{
var closed = _closed;
_closed = null;
Current = null;
Changed?.Invoke();
closed?.TrySetResult();
}
/// <summary>Draws the panel again after its data changed.</summary>
public void Refresh() => Changed?.Invoke();
}
+37 -2
View File
@@ -17,7 +17,11 @@ public enum ShortcutScope
/// <param name="Keys">The combinations, as the browser script writes them (<c>Ctrl+S</c>, <c>F9</c>, <c>Alt+W</c>).</param>
/// <param name="TextKey">The text key of the description.</param>
/// <param name="Scope">Who handles it.</param>
public sealed record Shortcut(string Id, IReadOnlyList<string> Keys, string TextKey, ShortcutScope Scope);
public sealed record Shortcut(string Id, IReadOnlyList<string> Keys, string TextKey, ShortcutScope Scope)
{
/// <summary>How the keys are shown when they are a series (<c>Alt+1...9</c>); <see langword="null"/> shows <see cref="Keys"/>.</summary>
public string? Display { get; init; }
}
/// <summary>
/// The shortcut table of SPEC §10.5.7. Browsers keep some combinations for themselves (Ctrl+W, Ctrl+Tab, Ctrl+N
@@ -75,6 +79,9 @@ public static class KeyboardShortcuts
/// <summary>Delete.</summary>
public const string Delete = "page.delete";
/// <summary>Alt+1..9: the tab of the page by position; the page receives <c>page.tab.N</c>.</summary>
public const string PageTab = "page.tab";
}
/// <summary>The table.</summary>
@@ -95,6 +102,10 @@ public static class KeyboardShortcuts
new(Commands.PreviousRecord, ["Ctrl+ArrowUp"], "Shell.Shortcuts.PreviousRecord", ShortcutScope.Page),
new(Commands.NextRecord, ["Ctrl+ArrowDown"], "Shell.Shortcuts.NextRecord", ShortcutScope.Page),
new(Commands.Balance, ["Ctrl+D"], "Shell.Shortcuts.Balance", ShortcutScope.Page),
new(Commands.PageTab, [.. Enumerable.Range(1, 9).Select(n => "Alt+" + n.ToString(System.Globalization.CultureInfo.InvariantCulture))], "Shell.Shortcuts.PageTab", ShortcutScope.Page)
{
Display = "Alt+1...9",
},
];
/// <summary>The shortcut of a command.</summary>
@@ -102,10 +113,32 @@ public static class KeyboardShortcuts
/// <returns>The shortcut, or <see langword="null"/>.</returns>
public static Shortcut? Find(string id) => All.FirstOrDefault(s => s.Id == id);
/// <summary>Reads the tab number of a <c>page.tab.N</c> command.</summary>
/// <param name="command">The command received.</param>
/// <param name="number">The tab number, 1 to 9.</param>
/// <returns>Whether the command picks a tab.</returns>
public static bool TryGetTabNumber(string command, out int number)
{
number = 0;
return command is not null && command.StartsWith(Commands.PageTab + ".", StringComparison.Ordinal)
&& int.TryParse(command.AsSpan(Commands.PageTab.Length + 1), System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out number)
&& number is >= 1 and <= 9;
}
/// <summary>The first combination of a command, for tooltips (<c>Ctrl+S</c>).</summary>
/// <param name="id">The command.</param>
/// <returns>The combination, or an empty string.</returns>
public static string KeysOf(string id) => Find(id)?.Keys[0] ?? string.Empty;
/// <summary>A combination as shown to people: arrows as symbols, <c>Escape</c> as <c>Esc</c>.</summary>
/// <param name="combo">The combination, as in <see cref="Shortcut.Keys"/>.</param>
/// <returns>The text to show.</returns>
public static string Pretty(string? combo) => combo is null ? string.Empty : combo
.Replace("ArrowUp", "↑", StringComparison.Ordinal)
.Replace("ArrowDown", "↓", StringComparison.Ordinal)
.Replace("ArrowLeft", "←", StringComparison.Ordinal)
.Replace("ArrowRight", "→", StringComparison.Ordinal)
.Replace("Escape", "Esc", StringComparison.Ordinal);
}
/// <summary>
@@ -147,7 +180,9 @@ public sealed class KeyboardShortcutService(IJSRuntime js) : IAsyncDisposable
var handler = shortcut.Scope == ShortcutScope.Shell ? ShellPressed : PagePressed;
if (handler is not null)
{
await handler(shortcut.Id).ConfigureAwait(false);
// The tab shortcuts tell the page which tab: page.tab.3 for Alt+3.
var command = shortcut.Id == KeyboardShortcuts.Commands.PageTab ? shortcut.Id + "." + combo[^1] : shortcut.Id;
await handler(command).ConfigureAwait(false);
}
}
+11
View File
@@ -129,6 +129,17 @@ public sealed class ShellSession(
Changed?.Invoke();
}
/// <summary>Shows a new name in the shell after the user changed it from the profile.</summary>
/// <param name="displayName">The new name.</param>
public void SetDisplayName(string? displayName)
{
if (!string.IsNullOrWhiteSpace(displayName) && displayName != DisplayName)
{
DisplayName = displayName;
Changed?.Invoke();
}
}
/// <summary>Saves one setting of the user (open tabs, layouts...).</summary>
/// <param name="key">The key.</param>
/// <param name="value">The value, or <see langword="null"/> to remove it.</param>
+3
View File
@@ -33,6 +33,9 @@ public sealed class KhTab
/// <summary>The icon set by the page; <see langword="null"/> uses the menu icon.</summary>
public string? Icon { get; private set; }
/// <summary>Whether the tab is the one shown: page shortcuts act only there.</summary>
public bool IsActive => ReferenceEquals(_owner.Active, this);
/// <summary>Whether the page has unsaved changes (orange dot, warning on close).</summary>
public bool IsModified { get; private set; }
+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";
}
}
+6
View File
@@ -74,6 +74,12 @@ button.sw { text-align: left; color: var(--kh-text); }
padding: 0 8px; font: inherit; }
.kh-inset { margin: 0 14px 14px; }
.kh-h2 { font-size: var(--kh-fs-lg); font-weight: 600; margin: 6px 0 0; }
/* Profile forms (issue #31): actions at the end of a form, read-only facts. */
.form .kh-formactions, .kh-formactions { display: flex; gap: 8px; justify-content: flex-end; flex-wrap: wrap; }
.kh-facts { display: grid; grid-template-columns: max-content 1fr; gap: 6px 14px; margin: 0; padding: 12px 14px; font-size: 12.5px; }
.kh-facts dt { color: var(--kh-text-2); }
.kh-facts dd { margin: 0; }
.fgroup .pb > p:first-child { margin-top: 0; }
.kh-table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
.kh-table th { text-align: left; font-weight: 600; color: var(--kh-text-2); font-size: var(--kh-fs-sm); padding: 6px 10px; border-bottom: 1px solid var(--kh-border-strong); }
.kh-table td { padding: 7px 10px; border-bottom: 1px solid var(--kh-border); vertical-align: middle; }
@@ -140,3 +140,81 @@ a.tab { text-decoration: none; }
@media (max-width: 899px) {
.gsearch .ph { display: none; }
}
/* ---- Kh components (issues #27, #29) ---- */
/* Form fields */
input.in.num, .f .in input.num { text-align: right; font-variant-numeric: tabular-nums; }
input.in.mono { font-family: var(--kh-mono); font-size: 12px; font-weight: 600; color: var(--kh-accent-text); }
.kh-datebox svg.i { color: var(--kh-text-3); flex: none; }
.kh-check { height: auto; min-height: 30px; cursor: pointer; }
.kh-check input { accent-color: var(--kh-accent); width: 15px; height: 15px; margin: 0; }
.kh-switch { display: inline-flex; align-items: center; gap: 8px; height: 30px; border: 0; background: none; padding: 0; font: inherit; color: var(--kh-text); cursor: pointer; }
.kh-switch:disabled { opacity: .55; cursor: default; }
.kh-vsum { display: flex; gap: 10px; align-items: flex-start; padding: 10px 12px; border-radius: var(--kh-radius-lg); background: var(--kh-err-soft); color: var(--kh-err-text); font-size: 12.5px; }
.kh-vsum.wide { grid-column: 1 / -1; }
.kh-vsum ul { margin: 4px 0 0; padding-left: 18px; }
.kh-vsum:focus { outline: 2px solid var(--kh-err); outline-offset: 2px; }
.kh-link { border: 0; background: none; padding: 0; font: inherit; color: inherit; text-decoration: underline; cursor: pointer; text-align: left; }
/* Hotlink */
.kh-hotlink { position: relative; }
.kh-hotlink .in input.code { flex: none; width: 10ch; }
.kh-lk { border: 0; background: none; padding: 2px; color: var(--kh-text-3); cursor: pointer; border-radius: 4px; display: grid; place-items: center; }
.kh-lk:hover { color: var(--kh-accent-text); background: var(--kh-surface-3); }
.kh-hits { position: absolute; top: calc(100% + 3px); left: 0; right: 0; z-index: 15; list-style: none; margin: 0; padding: 4px; max-height: 260px; overflow: auto;
background: var(--kh-surface); border: 1px solid var(--kh-border); border-radius: 8px; box-shadow: var(--kh-shadow-lg); }
.kh-hits li { display: flex; gap: 10px; align-items: center; padding: 6px 8px; border-radius: 6px; font-size: 12.5px; cursor: pointer; white-space: nowrap; overflow: hidden; }
.kh-hits li .code { font: 600 12px var(--kh-mono); color: var(--kh-accent-text); min-width: 8ch; }
.kh-hits li .desc { overflow: hidden; text-overflow: ellipsis; color: var(--kh-text-2); }
.kh-hits li.on, .kh-hits li:hover { background: var(--kh-accent-soft); }
.kh-hits li.none { color: var(--kh-text-3); cursor: default; background: none; }
.kh-hits li.new { color: var(--kh-accent-text); border-top: 1px solid var(--kh-border); margin-top: 3px; }
/* Display */
.kh-money { font-variant-numeric: tabular-nums; white-space: nowrap; }
.kh-money.neg { color: var(--kh-err); }
a.kh-tilelink { color: inherit; text-decoration: none; }
a.kh-tilelink:hover { border-color: var(--kh-accent); }
.kh-chipx { border: 0; background: none; padding: 0; color: inherit; display: grid; place-items: center; cursor: pointer; }
.kh-steps { list-style: none; margin: 0; }
.steps.kh-steps { padding: 4px 0; }
.vsteps.kh-steps { padding: 6px 0; }
button.tab { border: 0; border-bottom: 2px solid transparent; background: none; font: inherit; cursor: pointer; }
button.tab.active { border-bottom-color: var(--kh-accent); }
/* Dialog and drawer */
.dialog.kh-sm { width: 420px; } .dialog.kh-md { width: 640px; } .dialog.kh-lg { width: 860px; }
.dialog .db { max-height: calc(100vh - 220px); overflow: auto; }
.drawer.wide { width: 560px; }
.kh-close { width: 28px; height: 28px; background: none; cursor: pointer; }
@media (max-width: 700px) { .drawer, .drawer.wide { width: 100vw; } }
/* Toolbar */
.kh-toolbar { flex-wrap: nowrap; min-width: 0; }
.kh-toolbar .grp { flex: none; }
.kh-toolbar [data-ovf-hidden] { display: none !important; }
button.ib { background: none; padding: 0; cursor: pointer; font: inherit; }
button.ib.primary { background: var(--kh-accent); }
.ib:disabled, .ib.disabled { opacity: .35; cursor: default; pointer-events: none; }
button.ctx { cursor: pointer; }
.ctx:disabled { opacity: .45; cursor: default; }
.kh-morewrap { position: relative; flex: none; }
.kh-catch { position: fixed; inset: 0; z-index: 19; }
.kh-moremenu { min-width: 240px; }
.popmenu .mi.danger, .popmenu .mi.danger svg.i { color: var(--kh-err); }
.popmenu .mi:disabled { opacity: .45; }
/* Document header and record pages */
.kh-min0 { min-width: 0; }
.kh-ellipsis { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.kh-record { display: flex; flex-direction: column; gap: var(--kh-gap); min-width: 0; }
.kh-recordbody { overflow: visible; }
.kh-recordtab { min-width: 0; overflow-x: auto; }
@media (max-width: 1200px) { .dochead { grid-template-columns: 1fr 1fr; } .dochead > div:last-child { grid-column: 1 / -1; border-left: 0; border-top: 1px solid var(--kh-border); align-items: flex-start; text-align: left; } }
@media (max-width: 800px) { .dochead { grid-template-columns: 1fr; } .dochead > div + div { border-left: 0; border-top: 1px solid var(--kh-border); } }
/* Component catalog (development) */
.kh-catalog { display: flex; flex-direction: column; gap: var(--kh-gap); padding-top: var(--kh-gap); }
.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); }
+104 -1
View File
@@ -22,10 +22,16 @@
return combo + key;
}
// The keys an element handles itself (data-kh-prevent="ArrowDown F4"): the page shortcuts leave them alone.
function preventedBy(element, combo) {
const list = element && element.getAttribute ? element.getAttribute("data-kh-prevent") : null;
return !!list && list.split(" ").indexOf(combo) >= 0;
}
function onKeyDown(e) {
if (!shortcutTarget || e.isComposing) return;
const combo = comboOf(e);
if (!combo || !shortcutCombos.has(combo)) return;
if (!combo || !shortcutCombos.has(combo) || preventedBy(e.target, combo)) return;
e.preventDefault();
e.stopPropagation();
shortcutTarget.invokeMethodAsync("OnShortcut", combo).catch(function () { /* circuit gone */ });
@@ -87,6 +93,103 @@
}
},
// Stops the browser default of the keys listed in data-kh-prevent (read at each key, so Blazor can change it):
// arrows and Enter in an open hotlink list, + and - in a date field.
preventKeys: function (element) {
if (!element || element.khPrevent) return;
element.khPrevent = true;
element.addEventListener("keydown", function (e) {
// Date fields: + and - move one day when the field holds a whole date, and are typed otherwise (5-3-26, +30).
if ((e.key === "+" || e.key === "-") && !e.ctrlKey && !e.altKey && element.hasAttribute("data-kh-datestep")
&& /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(element.value)) {
e.preventDefault();
e.stopPropagation();
element.dispatchEvent(new KeyboardEvent("keydown", { key: e.key === "+" ? "ArrowUp" : "ArrowDown", bubbles: true }));
return;
}
const combo = comboOf(e);
if (combo && preventedBy(element, combo)) e.preventDefault();
});
},
// Places a drop-down menu under its button with fixed coordinates, aligned right, shorter when the window is.
placeMenu: function (menu) {
const anchor = menu && menu.parentElement;
if (!anchor) return;
const r = anchor.getBoundingClientRect();
const below = window.innerHeight - r.bottom - 12;
const above = r.top - 12;
menu.style.position = "fixed";
menu.style.right = Math.max(8, window.innerWidth - r.right) + "px";
menu.style.left = "auto";
if (below >= 200 || below >= above) {
menu.style.top = (r.bottom + 6) + "px";
menu.style.bottom = "auto";
menu.style.maxHeight = below + "px";
} else {
menu.style.bottom = (window.innerHeight - r.top + 6) + "px";
menu.style.top = "auto";
menu.style.maxHeight = above + "px";
}
menu.style.overflowY = "auto";
},
// Moves the focus to the first field or button inside an element (dialogs, side panels).
focusFirst: function (element) {
if (!element) return;
const target = element.querySelector("[autofocus], input:not([type=hidden]):not([disabled]):not([readonly]), select:not([disabled]), textarea:not([disabled]):not([readonly]), .db button:not([disabled]), .df button:not([disabled])")
|| element.querySelector("button:not([disabled])");
if (target) target.focus();
},
// Keeps a toolbar on one line: the commands with the highest data-ovf move out (data-ovf-hidden) until the bar
// fits, then .NET is told which ones, to list them in the "..." menu.
watchToolbar: function (element, target) {
if (!element) return;
element.khToolbar = target;
element.khObserver = new ResizeObserver(function () { window.khaemhat.fitToolbar(element); });
element.khObserver.observe(element);
window.khaemhat.fitToolbar(element);
},
fitToolbar: function (element) {
if (!element || !element.khToolbar || element.clientWidth === 0) return;
const items = Array.prototype.slice.call(element.querySelectorAll("[data-ovf]"));
const groups = element.querySelectorAll("[data-ovf-group]");
items.forEach(function (item) { item.removeAttribute("data-ovf-hidden"); });
groups.forEach(function (group) { group.removeAttribute("data-ovf-hidden"); });
const order = items.map(function (item, index) { return { item: item, index: index, priority: Number(item.getAttribute("data-ovf")) || 0 }; })
.sort(function (a, b) { return b.priority - a.priority || b.index - a.index; });
const hidden = [];
for (let i = 0; i < order.length && element.scrollWidth > element.clientWidth; i++) {
order[i].item.setAttribute("data-ovf-hidden", "");
hidden.push(order[i].item.getAttribute("data-id"));
}
groups.forEach(function (group) {
const children = group.querySelectorAll("[data-ovf]");
if (children.length > 0 && Array.prototype.every.call(children, function (c) { return c.hasAttribute("data-ovf-hidden"); })) {
group.setAttribute("data-ovf-hidden", "");
}
});
element.querySelectorAll(".sep").forEach(function (sep) {
const next = sep.nextElementSibling;
if (next && next.hasAttribute("data-ovf-hidden")) sep.setAttribute("data-ovf-hidden", "");
else sep.removeAttribute("data-ovf-hidden");
});
const key = hidden.join(",");
if (element.khOverflow !== key) {
element.khOverflow = key;
element.khToolbar.invokeMethodAsync("SetOverflow", hidden).catch(function () { /* circuit gone */ });
}
},
unwatchToolbar: function (element) {
if (!element) return;
if (element.khObserver) element.khObserver.disconnect();
element.khObserver = null;
element.khToolbar = null;
},
print: function () {
window.print();
},
@@ -87,6 +87,7 @@ public sealed partial class LocalizationRulesTests
keys.AddRange(Enum.GetValues<StartPage>().Select(v => "Pages.Profile.Start." + v));
keys.AddRange(Enum.GetValues<ShortcutScope>().Select(v => "Pages.Profile.Shortcuts." + v));
keys.AddRange(UserPreferences.Accents.Select(a => "Pages.Profile.Accent." + a));
keys.AddRange(Enum.GetValues<ToastKind>().Select(v => "Pages.Catalog.Windows.Toast." + v));
Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).ToList());
}
@@ -268,6 +269,6 @@ public sealed partial class LocalizationRulesTests
[GeneratedRegex(@"&[a-zA-Z]+;|&#\d+;")]
private static partial Regex EntityPattern();
[GeneratedRegex("\"((?:Shell|Pages|Auth|Common)\\.[A-Za-z0-9_.]+)\"")]
[GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui)\\.[A-Za-z0-9_.]+)\"")]
private static partial Regex KeyPattern();
}
@@ -0,0 +1,97 @@
using Khaemhat.Application.Security;
using Khaemhat.Core.Security;
using Khaemhat.Infrastructure.Security;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.Shell;
/// <summary>"Il mio profilo": the user changes name, e-mail, password and two-step verification alone (issue #31).</summary>
[TestClass]
public sealed class ProfileServiceTests
{
private const string NewPassword = "Altra-Password-2026";
[TestMethod]
public async Task InstanceAccount_ChangesData_Password_AndTurnsOnTheVerification()
{
var (app, _, _) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var profiles = app.Services.GetRequiredService<ProfileService>();
var sessions = app.Services.GetRequiredService<SessionStore>();
var owner = new SessionOwner(null, 1);
var info = await profiles.GetAsync(owner);
Assert.IsNotNull(info);
Assert.AreEqual(TestInstance.SuperUser, info.UserName);
Assert.IsTrue(info.TotpRequired, "Instance accounts always need the two-step verification.");
// Name and e-mail are checked, then saved.
CollectionAssert.AreEquivalent(
new[] { ProfileService.DisplayNameInvalid, ProfileService.EmailInvalid }, (await profiles.UpdateAsync(owner, " ", "not-an-address")).ToList());
Assert.IsEmpty(await profiles.UpdateAsync(owner, " Amministratore Prova ", "admin@example.com"));
info = await profiles.GetAsync(owner);
Assert.AreEqual("Amministratore Prova", info!.DisplayName);
Assert.AreEqual("admin@example.com", info.Email);
// The password: the current one is checked, the policy applies, the other sessions are closed.
await sessions.CreateAsync(owner, SessionState.Active, null, "10.0.0.1", "test-a", persistent: false);
await sessions.CreateAsync(owner, SessionState.Active, null, "10.0.0.2", "test-b", persistent: false);
var kept = (await sessions.ListAsync(owner))[0].Id;
CollectionAssert.AreEqual(new[] { SecurityErrors.CurrentPasswordWrong }, (await profiles.ChangePasswordAsync(owner, kept, "wrong", NewPassword)).ToList());
CollectionAssert.Contains((await profiles.ChangePasswordAsync(owner, kept, TestInstance.SuperUserPassword, "short")).ToList(), SecurityErrors.PasswordTooShort);
Assert.IsEmpty(await profiles.ChangePasswordAsync(owner, kept, TestInstance.SuperUserPassword, NewPassword));
Assert.AreEqual(kept, (await sessions.ListAsync(owner)).Single().Id, "Only the session that changed the password stays open.");
CollectionAssert.AreEqual(new[] { SecurityErrors.CurrentPasswordWrong }, (await profiles.ChangePasswordAsync(owner, kept, TestInstance.SuperUserPassword, "Terza-Password-2026")).ToList());
// The two-step verification: the same secret until confirmed, ten recovery codes, cannot be turned off.
var setup = await profiles.BeginTotpSetupAsync(owner, null);
Assert.IsNotNull(setup);
Assert.AreEqual(setup.Secret, (await profiles.BeginTotpSetupAsync(owner, null))!.Secret);
Assert.IsNull(await profiles.ConfirmTotpSetupAsync(owner, "abc"));
var codes = await profiles.ConfirmTotpSetupAsync(owner, CodeOf(setup.Secret));
Assert.HasCount(10, codes!);
info = await profiles.GetAsync(owner);
Assert.IsTrue(info!.TotpEnabled);
Assert.AreEqual(10, info.RecoveryCodesLeft);
Assert.IsNull(await profiles.BeginTotpSetupAsync(owner, null), "Already active.");
CollectionAssert.AreEqual(new[] { ProfileService.TotpRequiredError }, (await profiles.DisableTotpAsync(owner, NewPassword)).ToList());
// New recovery codes need the password and replace the old ones.
Assert.IsNull(await profiles.RenewRecoveryCodesAsync(owner, "wrong"));
var renewed = await profiles.RenewRecoveryCodesAsync(owner, NewPassword);
Assert.HasCount(10, renewed!);
Assert.IsEmpty(renewed!.Intersect(codes!).ToList());
await app.StopAsync();
}
}
[TestMethod]
public async Task CompanyUser_MayTurnTheVerificationOff_WithThePassword()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var profiles = app.Services.GetRequiredService<ProfileService>();
var users = app.Services.GetRequiredService<UserService>();
var root = new Actor(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
var (user, password) = await users.CreateAsync(root, company, new NewCompanyUser("lucia", "Lucia Bianchi", null, UserKind.Human, [], new UserFlags(false, false, false, false)));
var owner = new SessionOwner(company, user.Id);
var setup = await profiles.BeginTotpSetupAsync(owner, company);
Assert.Contains("lucia%40", setup!.ProvisioningUri, "The app shows user and company.");
Assert.IsNotNull(await profiles.ConfirmTotpSetupAsync(owner, CodeOf(setup.Secret)));
Assert.IsFalse((await profiles.GetAsync(owner))!.TotpRequired);
CollectionAssert.AreEqual(new[] { SecurityErrors.CurrentPasswordWrong }, (await profiles.DisableTotpAsync(owner, "wrong")).ToList());
Assert.IsEmpty(await profiles.DisableTotpAsync(owner, password!));
var info = await profiles.GetAsync(owner);
Assert.IsFalse(info!.TotpEnabled);
Assert.AreEqual(0, info.RecoveryCodesLeft);
await app.StopAsync();
}
}
private static string CodeOf(string secret) => TotpGenerator.Compute(Base32.Decode(secret), TotpGenerator.StepOf(DateTimeOffset.UtcNow));
}
@@ -0,0 +1,186 @@
using System.Globalization;
using Khaemhat.Web.Shell;
using Khaemhat.Web.Ui;
namespace Khaemhat.Web.Tests.Ui;
/// <summary>Numbers, inline calculations and dates typed the Italian way (SPEC §10.7, issue #27).</summary>
[TestClass]
public sealed class ItalianInputTests
{
private static readonly DateOnly Today = new(2026, 11, 11);
[TestMethod]
[DataRow("1234,5", "1234.5")]
[DataRow("1.234,56", "1234.56")]
[DataRow("1.234.567", "1234567")]
[DataRow("-12,5", "-12.5")]
[DataRow("12.5", "12.5")]
[DataRow("1.234", "1234")]
[DataRow(" 42 ", "42")]
[DataRow("=10*3", "30")]
[DataRow("=100/3", "33.333333333333333333333333333")]
[DataRow("=(2+3)x4", "20")]
[DataRow("=12:4", "3")]
[DataRow("=10,5+0,5", "11")]
[DataRow("=-2*-3", "6")]
public void Number_ReadsItalianFormsAndCalculations(string text, string expected)
{
Assert.IsTrue(ItalianNumber.TryParse(text, out var value), text);
Assert.AreEqual(decimal.Parse(expected, CultureInfo.InvariantCulture), value, text);
}
[TestMethod]
[DataRow("abc")]
[DataRow("12,3,4")]
[DataRow("=10/0")]
[DataRow("=(1+2")]
[DataRow("=1+")]
[DataRow("=")]
public void Number_RefusesWhatIsNotANumber(string text) => Assert.IsFalse(ItalianNumber.TryParse(text, out _), text);
[TestMethod]
public void Number_EmptyIsNull()
{
Assert.IsTrue(ItalianNumber.TryParse(" ", out var value));
Assert.IsNull(value);
}
[TestMethod]
public void Number_FormatsWithTheCulture()
{
var italian = CultureInfo.GetCultureInfo("it-IT");
Assert.AreEqual("1.234,50", ItalianNumber.Format(1234.5m, 2, italian));
Assert.AreEqual(string.Empty, ItalianNumber.Format(null, 2, italian));
}
[TestMethod]
[DataRow("T", 2026, 11, 11)]
[DataRow("o", 2026, 11, 11)]
[DataRow("F", 2026, 11, 30)]
[DataRow("I", 2026, 11, 1)]
[DataRow("+", 2026, 11, 12)]
[DataRow("-", 2026, 11, 10)]
[DataRow("+30", 2026, 12, 11)]
[DataRow("-11", 2026, 10, 31)]
[DataRow("5", 2026, 11, 5)]
[DataRow("5/3", 2026, 3, 5)]
[DataRow("05/03/2027", 2027, 3, 5)]
[DataRow("5-3-26", 2026, 3, 5)]
[DataRow("5.3.26", 2026, 3, 5)]
[DataRow("0503", 2026, 3, 5)]
[DataRow("050326", 2026, 3, 5)]
[DataRow("05032026", 2026, 3, 5)]
[DataRow("1/1/60", 1960, 1, 1)]
[DataRow("1/1/46", 2046, 1, 1)]
[DataRow("29/2/28", 2028, 2, 29)]
public void Date_ReadsShortFormsAndLetters(string text, int year, int month, int day)
{
Assert.IsTrue(ItalianDate.TryParse(text, Today, null, out var value), text);
Assert.AreEqual(new DateOnly(year, month, day), value, text);
}
[TestMethod]
public void Date_RelativeFormsStartFromTheCurrentValue()
{
var current = new DateOnly(2026, 2, 10);
Assert.IsTrue(ItalianDate.TryParse("F", Today, current, out var end));
Assert.AreEqual(new DateOnly(2026, 2, 28), end);
Assert.IsTrue(ItalianDate.TryParse("+7", Today, current, out var week));
Assert.AreEqual(new DateOnly(2026, 2, 17), week);
Assert.IsTrue(ItalianDate.TryParse("T", Today, current, out var today));
Assert.AreEqual(Today, today);
}
[TestMethod]
[DataRow("31/11/2026")]
[DataRow("29/2/2027")]
[DataRow("0/1")]
[DataRow("1/13")]
[DataRow("123")]
[DataRow("ieri")]
[DataRow("1/2/3/4")]
public void Date_RefusesWhatIsNotADate(string text) => Assert.IsFalse(ItalianDate.TryParse(text, Today, null, out _), text);
[TestMethod]
public void Date_EmptyIsNull()
{
Assert.IsTrue(ItalianDate.TryParse(string.Empty, Today, Today, out var value));
Assert.IsNull(value);
}
[TestMethod]
public void Validation_CollectsFieldMessagesAndRaisesChanged()
{
var validation = new KhValidation();
var changes = 0;
validation.Changed += () => changes++;
validation.Add("number", "taken");
validation.Add(null, "whole form");
Assert.IsFalse(validation.IsValid);
CollectionAssert.AreEqual(new[] { "taken" }, validation.For("number").ToArray());
validation.ClearField("number");
validation.ClearField("number");
Assert.HasCount(1, validation.Messages);
validation.Clear();
Assert.IsTrue(validation.IsValid);
Assert.AreEqual(4, changes);
}
[TestMethod]
public void FormContext_ValidatesEveryRegisteredField()
{
var context = new KhFormContext(new KhValidation());
var empty = new FakeField("name", "Nome", "Campo obbligatorio.");
var good = new FakeField("code", "Codice");
context.Register(empty);
context.Register(good);
Assert.IsFalse(context.Validate());
var message = context.Validation.Messages.Single();
Assert.AreEqual("name", message.Field);
Assert.AreEqual("Nome", message.Label);
Assert.AreEqual("in-name", message.InputId);
Assert.AreSame(good, context.Find("code"));
context.Unregister(empty);
Assert.IsTrue(context.Validate());
}
[TestMethod]
[DataRow("page.tab.1", 1)]
[DataRow("page.tab.9", 9)]
public void PageTab_ReadsTheNumber(string command, int expected)
{
Assert.IsTrue(KeyboardShortcuts.TryGetTabNumber(command, out var number));
Assert.AreEqual(expected, number);
}
[TestMethod]
[DataRow("page.tab.0")]
[DataRow("page.tab.10")]
[DataRow("page.tab.")]
[DataRow("page.save")]
public void PageTab_RefusesOtherCommands(string command) => Assert.IsFalse(KeyboardShortcuts.TryGetTabNumber(command, out _));
[TestMethod]
public void Pretty_ShowsArrowsAsSymbols()
{
Assert.AreEqual("Ctrl+↑", KeyboardShortcuts.Pretty("Ctrl+ArrowUp"));
Assert.AreEqual("Esc", KeyboardShortcuts.Pretty("Escape"));
Assert.AreEqual(string.Empty, KeyboardShortcuts.Pretty(null));
}
private sealed class FakeField(string name, string label, params string[] messages) : IKhField
{
public string FieldName => name;
public string? Label => label;
public string InputId => "in-" + name;
public IEnumerable<string> Validate() => messages;
}
}