feat: application shell, localized texts and user preferences (M3, part 1)
The pages built so far now live inside the shell of the mockups instead of the M0 placeholder, every interface text comes from Resources/it-IT, and each user keeps their own look and start page. - Shell: top bar, collapsible side menu with fly-out sub-menus, status bar and tabs that keep each page alive (page type and route values per tab, so a tab never shows another page); at most 12 tabs, least-used clean tab evicted. - One shortcut table with Alt variants for the combinations browsers keep (Ctrl+W, Ctrl+Tab, Ctrl+N); command palette for pages and commands. - ITexts over embedded JSON; tests forbid literal texts in .razor components and check that every key used exists. - User settings in sys_user_settings / user_settings; theme written on the server; profile page with live preview, start page, sessions and shortcuts. - Home, coming-soon pages for later milestones, localized sign-in and error pages; ADR 0020; wiki, CHANGELOG, STATUS and data model updated. Refs #25 #26 #31 #33 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1c30054e3d
commit
cf6f849cc1
72 files changed
+5785
-259
No files matched your search
@@ -0,0 +1,108 @@
|
||||
namespace Khaemhat.Web.Shell;
|
||||
|
||||
/// <summary>The weight of a toast.</summary>
|
||||
public enum ToastKind
|
||||
{
|
||||
/// <summary>Information.</summary>
|
||||
Info = 0,
|
||||
|
||||
/// <summary>Done.</summary>
|
||||
Success = 1,
|
||||
|
||||
/// <summary>Attention.</summary>
|
||||
Warning = 2,
|
||||
|
||||
/// <summary>Failure.</summary>
|
||||
Error = 3,
|
||||
}
|
||||
|
||||
/// <summary>A short message in the bottom right corner (SPEC §10.7 <c>KhToast</c>).</summary>
|
||||
/// <param name="Id">The identifier.</param>
|
||||
/// <param name="Kind">The weight.</param>
|
||||
/// <param name="Title">The title.</param>
|
||||
/// <param name="Text">The text, or <see langword="null"/>.</param>
|
||||
public sealed record Toast(Guid Id, ToastKind Kind, string Title, string? Text);
|
||||
|
||||
/// <summary>Shows toasts; <c>KhToastHost</c> in the layout renders them and removes them after a few seconds.</summary>
|
||||
public sealed class ToastService
|
||||
{
|
||||
private readonly List<Toast> _toasts = [];
|
||||
|
||||
/// <summary>Raised when toasts appear or go.</summary>
|
||||
public event Action? Changed;
|
||||
|
||||
/// <summary>The toasts on screen.</summary>
|
||||
public IReadOnlyList<Toast> Toasts => _toasts;
|
||||
|
||||
/// <summary>Shows a toast.</summary>
|
||||
/// <param name="kind">The weight.</param>
|
||||
/// <param name="title">The title.</param>
|
||||
/// <param name="text">The text.</param>
|
||||
/// <returns>The toast.</returns>
|
||||
public Toast Show(ToastKind kind, string title, string? text = null)
|
||||
{
|
||||
var toast = new Toast(Guid.NewGuid(), kind, title, text);
|
||||
_toasts.Add(toast);
|
||||
if (_toasts.Count > 5)
|
||||
{
|
||||
_toasts.RemoveAt(0);
|
||||
}
|
||||
|
||||
Changed?.Invoke();
|
||||
return toast;
|
||||
}
|
||||
|
||||
/// <summary>Removes a toast.</summary>
|
||||
/// <param name="id">The toast.</param>
|
||||
public void Dismiss(Guid id)
|
||||
{
|
||||
if (_toasts.RemoveAll(t => t.Id == id) > 0)
|
||||
{
|
||||
Changed?.Invoke();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A question that needs a yes or no (SPEC §10.7 <c>KhConfirm</c>).</summary>
|
||||
/// <param name="Title">The title.</param>
|
||||
/// <param name="Text">The question.</param>
|
||||
/// <param name="ConfirmText">The text of the confirming button.</param>
|
||||
/// <param name="CancelText">The text of the cancelling button.</param>
|
||||
/// <param name="Danger">Whether confirming destroys something (red button).</param>
|
||||
public sealed record ConfirmRequest(string Title, string Text, string ConfirmText, string CancelText, bool Danger = false);
|
||||
|
||||
/// <summary>Asks confirmations; <c>KhDialogHost</c> in the layout shows them one at a time.</summary>
|
||||
public sealed class DialogService
|
||||
{
|
||||
private TaskCompletionSource<bool>? _pending;
|
||||
|
||||
/// <summary>Raised when a question appears or is answered.</summary>
|
||||
public event Action? Changed;
|
||||
|
||||
/// <summary>The question on screen, or <see langword="null"/>.</summary>
|
||||
public ConfirmRequest? Current { get; private set; }
|
||||
|
||||
/// <summary>Asks a question and waits for the answer.</summary>
|
||||
/// <param name="request">The question.</param>
|
||||
/// <returns><see langword="true"/> when the user confirms.</returns>
|
||||
public Task<bool> ConfirmAsync(ConfirmRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
_pending?.TrySetResult(false);
|
||||
_pending = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
Current = request;
|
||||
Changed?.Invoke();
|
||||
return _pending.Task;
|
||||
}
|
||||
|
||||
/// <summary>Called by the dialog with the answer.</summary>
|
||||
/// <param name="confirmed">The answer.</param>
|
||||
public void Answer(bool confirmed)
|
||||
{
|
||||
var pending = _pending;
|
||||
_pending = null;
|
||||
Current = null;
|
||||
Changed?.Invoke();
|
||||
pending?.TrySetResult(confirmed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
namespace Khaemhat.Web.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// The wiki page of each part of the application (SPEC §17: F1 and "?" open the page of the screen). The address is
|
||||
/// the deepest prefix that matches; anything unknown opens the wiki home.
|
||||
/// </summary>
|
||||
public static class HelpLinks
|
||||
{
|
||||
/// <summary>The wiki of the project, used when no other address is configured.</summary>
|
||||
public const string DefaultBaseUrl = "https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/";
|
||||
|
||||
private static readonly (string Prefix, string Page)[] Pages =
|
||||
[
|
||||
("/anagrafiche/articoli", "Articoli-e-listini"),
|
||||
("/anagrafiche/listini", "Articoli-e-listini"),
|
||||
("/anagrafiche", "Anagrafiche"),
|
||||
("/crm", "CRM"),
|
||||
("/vendite", "Vendite"),
|
||||
("/acquisti", "Acquisti"),
|
||||
("/magazzino", "Magazzino"),
|
||||
("/contabilita/liquidazione-iva", "IVA"),
|
||||
("/contabilita/registri-iva", "IVA"),
|
||||
("/contabilita", "Contabilita"),
|
||||
("/scadenzario", "Scadenzario"),
|
||||
("/fatturazione-elettronica", "Fatturazione-elettronica"),
|
||||
("/cespiti", "Cespiti"),
|
||||
("/servizi", "Servizi"),
|
||||
("/canali", "Canali-e-commerce"),
|
||||
("/report", "Report"),
|
||||
("/tabelle", "Tabelle-azienda"),
|
||||
("/automazioni", "Automazioni"),
|
||||
("/amministrazione/licenze", "Licenze-e-moduli"),
|
||||
("/amministrazione/log", "Log"),
|
||||
("/amministrazione/attivita", "Attivita-programmate"),
|
||||
("/amministrazione/stato", "Stato-sistema"),
|
||||
("/amministrazione/utenti", "Utenti-e-permessi"),
|
||||
("/amministrazione/ruoli", "Utenti-e-permessi"),
|
||||
("/amministrazione", "Istanza-e-database"),
|
||||
("/profilo", "Preferenze-utente"),
|
||||
("/", "Dashboard"),
|
||||
];
|
||||
|
||||
/// <summary>The wiki page of a path.</summary>
|
||||
/// <param name="path">The path, without query.</param>
|
||||
/// <returns>The page name, for example <c>Anagrafiche</c>.</returns>
|
||||
public static string PageFor(string path)
|
||||
{
|
||||
var p = TabService.PathOf(path);
|
||||
foreach (var (prefix, page) in Pages)
|
||||
{
|
||||
if (prefix == "/" ? p == "/" : p.Equals(prefix, StringComparison.OrdinalIgnoreCase) || p.StartsWith(prefix + "/", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return page;
|
||||
}
|
||||
}
|
||||
|
||||
return "Home";
|
||||
}
|
||||
|
||||
/// <summary>The address of the help of a path.</summary>
|
||||
/// <param name="baseUrl">The wiki address, ending with a slash.</param>
|
||||
/// <param name="path">The path.</param>
|
||||
/// <returns>The address.</returns>
|
||||
public static string UrlFor(string baseUrl, string path) => baseUrl + PageFor(path);
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
using Microsoft.JSInterop;
|
||||
|
||||
namespace Khaemhat.Web.Shell;
|
||||
|
||||
/// <summary>Who handles a shortcut.</summary>
|
||||
public enum ShortcutScope
|
||||
{
|
||||
/// <summary>The shell (menu, tabs, search, help).</summary>
|
||||
Shell = 0,
|
||||
|
||||
/// <summary>The active page (save, new, print, radar...).</summary>
|
||||
Page = 1,
|
||||
}
|
||||
|
||||
/// <summary>A keyboard shortcut of SPEC §10.5.7.</summary>
|
||||
/// <param name="Id">The command.</param>
|
||||
/// <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);
|
||||
|
||||
/// <summary>
|
||||
/// The shortcut table of SPEC §10.5.7. Browsers keep some combinations for themselves (Ctrl+W, Ctrl+Tab, Ctrl+N
|
||||
/// in a normal window): each of those has an <c>Alt</c> alternative that always works (ADR 0020).
|
||||
/// </summary>
|
||||
public static class KeyboardShortcuts
|
||||
{
|
||||
/// <summary>Command ids.</summary>
|
||||
public static class Commands
|
||||
{
|
||||
/// <summary>Collapse or expand the menu.</summary>
|
||||
public const string ToggleMenu = "shell.menu";
|
||||
|
||||
/// <summary>Global search.</summary>
|
||||
public const string Search = "shell.search";
|
||||
|
||||
/// <summary>Help of the page.</summary>
|
||||
public const string Help = "shell.help";
|
||||
|
||||
/// <summary>Close the active tab.</summary>
|
||||
public const string CloseTab = "shell.tab.close";
|
||||
|
||||
/// <summary>Next tab.</summary>
|
||||
public const string NextTab = "shell.tab.next";
|
||||
|
||||
/// <summary>Previous tab.</summary>
|
||||
public const string PreviousTab = "shell.tab.previous";
|
||||
|
||||
/// <summary>Save.</summary>
|
||||
public const string Save = "page.save";
|
||||
|
||||
/// <summary>New record.</summary>
|
||||
public const string New = "page.new";
|
||||
|
||||
/// <summary>Print.</summary>
|
||||
public const string Print = "page.print";
|
||||
|
||||
/// <summary>Lookup of the field.</summary>
|
||||
public const string Lookup = "page.lookup";
|
||||
|
||||
/// <summary>Radar of the page.</summary>
|
||||
public const string Radar = "page.radar";
|
||||
|
||||
/// <summary>Cancel.</summary>
|
||||
public const string Cancel = "page.cancel";
|
||||
|
||||
/// <summary>Previous record.</summary>
|
||||
public const string PreviousRecord = "page.record.previous";
|
||||
|
||||
/// <summary>Next record.</summary>
|
||||
public const string NextRecord = "page.record.next";
|
||||
|
||||
/// <summary>Balance the journal entry.</summary>
|
||||
public const string Balance = "page.balance";
|
||||
|
||||
/// <summary>Delete.</summary>
|
||||
public const string Delete = "page.delete";
|
||||
}
|
||||
|
||||
/// <summary>The table.</summary>
|
||||
public static IReadOnlyList<Shortcut> All { get; } =
|
||||
[
|
||||
new(Commands.Search, ["Ctrl+K"], "Shell.Shortcuts.Search", ShortcutScope.Shell),
|
||||
new(Commands.ToggleMenu, ["Ctrl+B"], "Shell.Shortcuts.ToggleMenu", ShortcutScope.Shell),
|
||||
new(Commands.Help, ["F1"], "Shell.Shortcuts.Help", ShortcutScope.Shell),
|
||||
new(Commands.CloseTab, ["Ctrl+W", "Alt+W"], "Shell.Shortcuts.CloseTab", ShortcutScope.Shell),
|
||||
new(Commands.NextTab, ["Ctrl+Tab", "Alt+PageDown"], "Shell.Shortcuts.NextTab", ShortcutScope.Shell),
|
||||
new(Commands.PreviousTab, ["Ctrl+Shift+Tab", "Alt+PageUp"], "Shell.Shortcuts.PreviousTab", ShortcutScope.Shell),
|
||||
new(Commands.Save, ["Ctrl+S"], "Shell.Shortcuts.Save", ShortcutScope.Page),
|
||||
new(Commands.New, ["Ctrl+N", "Alt+N"], "Shell.Shortcuts.New", ShortcutScope.Page),
|
||||
new(Commands.Print, ["Ctrl+P"], "Shell.Shortcuts.Print", ShortcutScope.Page),
|
||||
new(Commands.Delete, ["Ctrl+Delete"], "Shell.Shortcuts.Delete", ShortcutScope.Page),
|
||||
new(Commands.Lookup, ["F4"], "Shell.Shortcuts.Lookup", ShortcutScope.Page),
|
||||
new(Commands.Radar, ["F9"], "Shell.Shortcuts.Radar", ShortcutScope.Page),
|
||||
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),
|
||||
];
|
||||
|
||||
/// <summary>The shortcut of a command.</summary>
|
||||
/// <param name="id">The command.</param>
|
||||
/// <returns>The shortcut, or <see langword="null"/>.</returns>
|
||||
public static Shortcut? Find(string id) => All.FirstOrDefault(s => s.Id == id);
|
||||
|
||||
/// <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>
|
||||
/// Receives the shortcuts from the browser script and hands them out: the shell handles its own, the active page
|
||||
/// subscribes to <see cref="PagePressed"/> for the rest. Escape is not intercepted (inputs and dialogs need it).
|
||||
/// </summary>
|
||||
/// <param name="js">The browser.</param>
|
||||
public sealed class KeyboardShortcutService(IJSRuntime js) : IAsyncDisposable
|
||||
{
|
||||
private DotNetObjectReference<KeyboardShortcutService>? _self;
|
||||
|
||||
/// <summary>A shell command was pressed.</summary>
|
||||
public event Func<string, Task>? ShellPressed;
|
||||
|
||||
/// <summary>A page command was pressed; the active page handles it.</summary>
|
||||
public event Func<string, Task>? PagePressed;
|
||||
|
||||
/// <summary>Starts listening in the browser.</summary>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task StartAsync()
|
||||
{
|
||||
_self ??= DotNetObjectReference.Create(this);
|
||||
var combos = KeyboardShortcuts.All.SelectMany(s => s.Keys).Distinct(StringComparer.Ordinal).ToArray();
|
||||
await js.InvokeVoidAsync("khaemhat.startShortcuts", _self, combos).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Called by the browser script.</summary>
|
||||
/// <param name="combo">The combination pressed.</param>
|
||||
/// <returns>A task.</returns>
|
||||
[JSInvokable]
|
||||
public async Task OnShortcut(string combo)
|
||||
{
|
||||
var shortcut = KeyboardShortcuts.All.FirstOrDefault(s => s.Keys.Contains(combo, StringComparer.Ordinal));
|
||||
if (shortcut is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var handler = shortcut.Scope == ShortcutScope.Shell ? ShellPressed : PagePressed;
|
||||
if (handler is not null)
|
||||
{
|
||||
await handler(shortcut.Id).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_self is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await js.InvokeVoidAsync("khaemhat.stopShortcuts").ConfigureAwait(false);
|
||||
}
|
||||
catch (JSDisconnectedException)
|
||||
{
|
||||
// The circuit is gone together with the page.
|
||||
}
|
||||
|
||||
_self.Dispose();
|
||||
_self = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
using Khaemhat.Application.Modules;
|
||||
|
||||
namespace Khaemhat.Web.Shell;
|
||||
|
||||
/// <summary>Who may see a menu entry besides module and permission.</summary>
|
||||
public enum MenuAudience
|
||||
{
|
||||
/// <summary>Everybody with the module and the permission.</summary>
|
||||
Everyone = 0,
|
||||
|
||||
/// <summary>Only instance accounts (super user and administrators).</summary>
|
||||
InstanceAccounts = 1,
|
||||
}
|
||||
|
||||
/// <summary>An entry of the side menu (SPEC §10.2).</summary>
|
||||
/// <param name="Key">The text key of the label (<c>Shell.Menu.*</c>) and the identity of the entry.</param>
|
||||
/// <param name="Icon">The icon in <c>icons/sprite.svg</c>.</param>
|
||||
/// <param name="Href">The address.</param>
|
||||
/// <param name="Module">The licence module that must be active.</param>
|
||||
/// <param name="Permission">The permission needed, or <see langword="null"/>.</param>
|
||||
/// <param name="Milestone">The milestone that delivers the page, shown while it is not there yet (<c>M4</c>...); <see langword="null"/> once delivered.</param>
|
||||
/// <param name="Audience">Who may see it.</param>
|
||||
public sealed record MenuItem(string Key, string Icon, string Href, string Module, string? Permission, string? Milestone,
|
||||
MenuAudience Audience = MenuAudience.Everyone)
|
||||
{
|
||||
/// <summary>The sub-entries shown under the active module or in the pop-up of the collapsed menu.</summary>
|
||||
public IReadOnlyList<MenuItem> Children { get; init; } = [];
|
||||
|
||||
/// <summary>Whether an address belongs to this entry or to one of its children.</summary>
|
||||
/// <param name="path">The path, without query.</param>
|
||||
/// <returns><see langword="true"/> when it matches.</returns>
|
||||
public bool Matches(string path) =>
|
||||
Href == "/" ? path == "/" : path.Equals(Href, StringComparison.OrdinalIgnoreCase) || path.StartsWith(Href + "/", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>A titled group of the side menu.</summary>
|
||||
/// <param name="Key">The text key of the title.</param>
|
||||
/// <param name="Items">The entries.</param>
|
||||
public sealed record MenuSection(string Key, IReadOnlyList<MenuItem> Items);
|
||||
|
||||
/// <summary>
|
||||
/// The side menu of SPEC §10.2, in its order: Home; Anagrafiche, CRM, Vendite, Acquisti, Magazzino, Contabilità,
|
||||
/// Scadenzario, Fatturazione elettronica, Cespiti, Servizi, Canali e-commerce, Report; Tabelle azienda,
|
||||
/// Automazioni, Amministrazione. Entries appear only with the licensed module and the permission.
|
||||
/// </summary>
|
||||
public static class MenuCatalog
|
||||
{
|
||||
/// <summary>The sections.</summary>
|
||||
public static IReadOnlyList<MenuSection> Sections { get; } =
|
||||
[
|
||||
new("Shell.Menu.Section.Main",
|
||||
[
|
||||
new("Shell.Menu.Home", "home", "/", ModuleCodes.Core, null, null),
|
||||
]),
|
||||
new("Shell.Menu.Section.Operations",
|
||||
[
|
||||
Area("Shell.Menu.Parties", "users", "/anagrafiche", ModuleCodes.Core, "parties.party.read", "M4",
|
||||
("Shell.Menu.Parties.Customers", "clienti"), ("Shell.Menu.Parties.Suppliers", "fornitori"), ("Shell.Menu.Parties.Contacts", "contatti"),
|
||||
("Shell.Menu.Parties.Items", "articoli"), ("Shell.Menu.Parties.PriceLists", "listini"), ("Shell.Menu.Parties.Categories", "categorie")),
|
||||
Area("Shell.Menu.Crm", "target", "/crm", ModuleCodes.Crm, "crm.lead.read", "M11",
|
||||
("Shell.Menu.Crm.Dashboard", "cruscotto"), ("Shell.Menu.Crm.Leads", "lead"), ("Shell.Menu.Crm.Pipeline", "pipeline"),
|
||||
("Shell.Menu.Crm.Agenda", "agenda"), ("Shell.Menu.Crm.Tickets", "ticket"), ("Shell.Menu.Crm.Campaigns", "campagne")),
|
||||
Area("Shell.Menu.Sales", "cart", "/vendite", ModuleCodes.Core, "sales.invoice.read", "M5",
|
||||
("Shell.Menu.Sales.Quotes", "preventivi"), ("Shell.Menu.Sales.Orders", "ordini"), ("Shell.Menu.Sales.DeliveryNotes", "ddt"),
|
||||
("Shell.Menu.Sales.Invoices", "fatture"), ("Shell.Menu.Sales.CreditNotes", "note-credito")),
|
||||
Area("Shell.Menu.Purchases", "truck", "/acquisti", ModuleCodes.Core, "purchases.order.read", "M6",
|
||||
("Shell.Menu.Purchases.Orders", "ordini"), ("Shell.Menu.Purchases.Receipts", "ricevimenti"), ("Shell.Menu.Purchases.Invoices", "fatture")),
|
||||
Area("Shell.Menu.Inventory", "box", "/magazzino", ModuleCodes.Core, "inventory.stock.read", "M6",
|
||||
("Shell.Menu.Inventory.Stock", "giacenze"), ("Shell.Menu.Inventory.Entries", "movimenti"), ("Shell.Menu.Inventory.StockTake", "inventario"),
|
||||
("Shell.Menu.Inventory.Reorder", "riordino")),
|
||||
Area("Shell.Menu.Ledger", "book", "/contabilita", ModuleCodes.Accounting, "ledger.entry.read", "M7",
|
||||
("Shell.Menu.Ledger.Journal", "prima-nota"), ("Shell.Menu.Ledger.Accounts", "piano-dei-conti"), ("Shell.Menu.Ledger.VatRegisters", "registri-iva"),
|
||||
("Shell.Menu.Ledger.VatSettlement", "liquidazione-iva"), ("Shell.Menu.Ledger.Statements", "bilancio")),
|
||||
Area("Shell.Menu.Finance", "coins", "/scadenzario", ModuleCodes.Finance, "finance.schedule.read", "M9",
|
||||
("Shell.Menu.Finance.OpenItems", "scadenze"), ("Shell.Menu.Finance.Remittances", "distinte"), ("Shell.Menu.Finance.Dunning", "solleciti"),
|
||||
("Shell.Menu.Finance.Reconciliation", "riconciliazione")),
|
||||
Area("Shell.Menu.EInvoicing", "file-check", "/fatturazione-elettronica", ModuleCodes.EInvoicing, "einvoice.document.read", "M8",
|
||||
("Shell.Menu.EInvoicing.Dashboard", "cruscotto"), ("Shell.Menu.EInvoicing.Channels", "canali"), ("Shell.Menu.EInvoicing.StampDuty", "bollo"),
|
||||
("Shell.Menu.EInvoicing.IntentDeclarations", "dichiarazioni-intento")),
|
||||
Area("Shell.Menu.Assets", "building", "/cespiti", ModuleCodes.Assets, "assets.asset.read", "M10",
|
||||
("Shell.Menu.Assets.Register", "registro"), ("Shell.Menu.Assets.Depreciation", "ammortamenti")),
|
||||
Area("Shell.Menu.Services", "wrench", "/servizi", ModuleCodes.Services, null, "M12",
|
||||
("Shell.Menu.Services.Contracts", "contratti"), ("Shell.Menu.Services.Interventions", "interventi")),
|
||||
Area("Shell.Menu.Channels", "globe", "/canali", ModuleCodes.Channels, null, "M12",
|
||||
("Shell.Menu.Channels.Orders", "ordini")),
|
||||
Area("Shell.Menu.Reports", "chart", "/report", ModuleCodes.Reports, "reports.report.read", "M13"),
|
||||
]),
|
||||
new("Shell.Menu.Section.System",
|
||||
[
|
||||
Area("Shell.Menu.CompanyTables", "layers", "/tabelle", ModuleCodes.Core, "company.settings.read", "M4",
|
||||
("Shell.Menu.CompanyTables.Profile", "profilo-azienda"), ("Shell.Menu.CompanyTables.FiscalYears", "esercizi"),
|
||||
("Shell.Menu.CompanyTables.TaxCodes", "codici-iva"), ("Shell.Menu.CompanyTables.Payments", "pagamenti")),
|
||||
Area("Shell.Menu.Automation", "zap", "/automazioni", ModuleCodes.Automation, null, "M12",
|
||||
("Shell.Menu.Automation.Rules", "regole"), ("Shell.Menu.Automation.Procedures", "procedure")),
|
||||
Area("Shell.Menu.Admin", "shield", "/amministrazione", ModuleCodes.Core, null, "M13",
|
||||
MenuAudience.InstanceAccounts,
|
||||
("Shell.Menu.Admin.Companies", "aziende"), ("Shell.Menu.Admin.Users", "utenti"), ("Shell.Menu.Admin.Roles", "ruoli"),
|
||||
("Shell.Menu.Admin.Licenses", "licenze"), ("Shell.Menu.Admin.Jobs", "attivita"), ("Shell.Menu.Admin.Log", "log"),
|
||||
("Shell.Menu.Admin.Status", "stato")),
|
||||
]),
|
||||
];
|
||||
|
||||
/// <summary>Every entry with its children, in menu order.</summary>
|
||||
public static IEnumerable<MenuItem> All => Sections.SelectMany(s => s.Items).SelectMany(i => i.Children.Prepend(i));
|
||||
|
||||
/// <summary>The entry that best matches an address: the deepest one whose address is a prefix.</summary>
|
||||
/// <param name="path">The path, without query.</param>
|
||||
/// <returns>The entry, or <see langword="null"/>.</returns>
|
||||
public static MenuItem? Find(string path) =>
|
||||
All.Where(i => i.Matches(path)).OrderByDescending(i => i.Href.Length).FirstOrDefault();
|
||||
|
||||
/// <summary>The top-level entry an address belongs to.</summary>
|
||||
/// <param name="path">The path.</param>
|
||||
/// <returns>The entry, or <see langword="null"/>.</returns>
|
||||
public static MenuItem? FindArea(string path) =>
|
||||
Sections.SelectMany(s => s.Items).Where(i => i.Matches(path)).OrderByDescending(i => i.Href.Length).FirstOrDefault();
|
||||
|
||||
private static MenuItem Area(string key, string icon, string href, string module, string? permission, string? milestone,
|
||||
params (string Key, string Slug)[] children) =>
|
||||
Area(key, icon, href, module, permission, milestone, MenuAudience.Everyone, children);
|
||||
|
||||
private static MenuItem Area(string key, string icon, string href, string module, string? permission, string? milestone, MenuAudience audience,
|
||||
params (string Key, string Slug)[] children) =>
|
||||
new(key, icon, href, module, permission, milestone, audience)
|
||||
{
|
||||
Children = [.. children.Select(c => new MenuItem(c.Key, icon, href + "/" + c.Slug, module, permission, milestone, audience))],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
using Khaemhat.Application.Licensing;
|
||||
using Khaemhat.Application.Preferences;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Core.Security;
|
||||
using Khaemhat.Data.Companies;
|
||||
using Khaemhat.Web.Security;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
|
||||
namespace Khaemhat.Web.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// What the shell needs to know about the signed-in user, loaded once per circuit: the actor, the display name, the
|
||||
/// company, the effective permissions and the interface preferences. Components read it; preference changes go
|
||||
/// through <see cref="SavePreferencesAsync"/> so every part of the shell is told (<see cref="Changed"/>).
|
||||
/// </summary>
|
||||
/// <param name="authentication">The signed-in user.</param>
|
||||
/// <param name="permissions">Effective permissions.</param>
|
||||
/// <param name="companies">The company registry.</param>
|
||||
/// <param name="licenses">The licence.</param>
|
||||
/// <param name="settings">The user preferences store.</param>
|
||||
public sealed class ShellSession(
|
||||
AuthenticationStateProvider authentication,
|
||||
PermissionService permissions,
|
||||
ICompanyRegistry companies,
|
||||
ILicenseGate licenses,
|
||||
UserSettingsService settings) : IDisposable
|
||||
{
|
||||
private readonly SemaphoreSlim _load = new(1, 1);
|
||||
private bool _loaded;
|
||||
|
||||
/// <summary>Raised after the preferences or the permissions change.</summary>
|
||||
public event Action? Changed;
|
||||
|
||||
/// <summary>The signed-in user, or <see langword="null"/>.</summary>
|
||||
public Actor? Actor { get; private set; }
|
||||
|
||||
/// <summary>The name shown in the top bar.</summary>
|
||||
public string DisplayName { get; private set; } = string.Empty;
|
||||
|
||||
/// <summary>The company the session works in.</summary>
|
||||
public Company? Company { get; private set; }
|
||||
|
||||
/// <summary>The companies an instance account may switch to (empty for company users).</summary>
|
||||
public IReadOnlyList<Company> SwitchableCompanies { get; private set; } = [];
|
||||
|
||||
/// <summary>The effective permissions.</summary>
|
||||
public EffectivePermissions Permissions { get; private set; } = EffectivePermissions.None;
|
||||
|
||||
/// <summary>The interface preferences.</summary>
|
||||
public UserPreferences Preferences { get; private set; } = UserPreferences.Default;
|
||||
|
||||
/// <summary>The licence.</summary>
|
||||
public ILicenseGate Licenses => licenses;
|
||||
|
||||
/// <summary>The initials of the user for the avatar.</summary>
|
||||
public string Initials => InitialsOf(DisplayName);
|
||||
|
||||
/// <summary>Loads everything once; later calls return at once.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task EnsureLoadedAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_loaded)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await _load.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (_loaded)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var state = await authentication.GetAuthenticationStateAsync().ConfigureAwait(false);
|
||||
Actor = SessionCookie.ActorOf(state.User);
|
||||
DisplayName = state.User.FindFirst(SessionCookie.DisplayNameClaim)?.Value ?? Actor?.UserName ?? string.Empty;
|
||||
if (Actor is not null)
|
||||
{
|
||||
Permissions = await permissions.GetAsync(Actor, cancellationToken).ConfigureAwait(false);
|
||||
Preferences = await settings.GetPreferencesAsync(Actor, cancellationToken).ConfigureAwait(false);
|
||||
var all = await companies.ListAsync(cancellationToken).ConfigureAwait(false);
|
||||
Company = Actor.CompanyCode is { } code ? all.FirstOrDefault(c => string.Equals(c.Code, code, StringComparison.OrdinalIgnoreCase)) : null;
|
||||
SwitchableCompanies = Actor.IsInstanceAccount ? [.. all.Where(c => c.Status != CompanyStatus.Disabled).OrderBy(c => c.Name, StringComparer.CurrentCulture)] : [];
|
||||
}
|
||||
|
||||
_loaded = true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_load.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Whether a menu entry is visible: licensed module, permission and audience.</summary>
|
||||
/// <param name="item">The entry.</param>
|
||||
/// <returns><see langword="true"/> when the user may see it.</returns>
|
||||
public bool CanSee(MenuItem item)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(item);
|
||||
if (Actor is null || !licenses.IsModuleActive(item.Module))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (item.Audience == MenuAudience.InstanceAccounts && !Actor.IsInstanceAccount)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return item.Permission is null || Permissions.Allows(item.Permission);
|
||||
}
|
||||
|
||||
/// <summary>Saves new preferences and tells the shell.</summary>
|
||||
/// <param name="preferences">The preferences.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task SavePreferencesAsync(UserPreferences preferences, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(preferences);
|
||||
Preferences = preferences;
|
||||
if (Actor is not null)
|
||||
{
|
||||
await settings.SavePreferencesAsync(Actor, preferences, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
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>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public Task SaveSettingAsync(string key, string? value, CancellationToken cancellationToken = default) =>
|
||||
Actor is null ? Task.CompletedTask : settings.SetAsync(Actor, key, value, cancellationToken);
|
||||
|
||||
/// <summary>Reads one setting of the user.</summary>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The value, or <see langword="null"/>.</returns>
|
||||
public Task<string?> ReadSettingAsync(string key, CancellationToken cancellationToken = default) =>
|
||||
Actor is null ? Task.FromResult<string?>(null) : settings.GetAsync(Actor, key, cancellationToken);
|
||||
|
||||
/// <summary>The level of the user as a text key (<c>Shell.Level.*</c>).</summary>
|
||||
public string LevelKey => Actor?.Level switch
|
||||
{
|
||||
UserLevel.SuperUser => "Shell.Level.SuperUser",
|
||||
UserLevel.Administrator => "Shell.Level.Administrator",
|
||||
_ => "Shell.Level.User",
|
||||
};
|
||||
|
||||
/// <summary>Up to two initials of a name: <c>Alberto Balbo</c> gives <c>AB</c>.</summary>
|
||||
/// <param name="name">The name.</param>
|
||||
/// <returns>The initials, upper case.</returns>
|
||||
public static string InitialsOf(string? name)
|
||||
{
|
||||
var parts = (name ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
var initials = parts.Length switch
|
||||
{
|
||||
0 => "?",
|
||||
1 => parts[0][..Math.Min(2, parts[0].Length)],
|
||||
_ => string.Concat(parts[0][0], parts[^1][0]),
|
||||
};
|
||||
return initials.ToUpperInvariant();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose() => _load.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
using Microsoft.AspNetCore.Components;
|
||||
|
||||
namespace Khaemhat.Web.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// One open page of the tab area (SPEC §10.2). The page component stays alive while the tab is open: the layout keeps
|
||||
/// rendering its content, hidden when another tab is active.
|
||||
/// </summary>
|
||||
public sealed class KhTab
|
||||
{
|
||||
private readonly TabService _owner;
|
||||
|
||||
internal KhTab(TabService owner, string path, string url)
|
||||
{
|
||||
_owner = owner;
|
||||
Path = path;
|
||||
Url = url;
|
||||
Id = Guid.NewGuid().ToString("N")[..12];
|
||||
}
|
||||
|
||||
/// <summary>A stable identifier, used as render key.</summary>
|
||||
public string Id { get; }
|
||||
|
||||
/// <summary>The path that identifies the tab (without query).</summary>
|
||||
public string Path { get; }
|
||||
|
||||
/// <summary>The full address last shown in the tab (with query).</summary>
|
||||
public string Url { get; internal set; }
|
||||
|
||||
/// <summary>The title set by the page; <see langword="null"/> uses the menu label.</summary>
|
||||
public string? Title { get; private set; }
|
||||
|
||||
/// <summary>The icon set by the page; <see langword="null"/> uses the menu icon.</summary>
|
||||
public string? Icon { get; private set; }
|
||||
|
||||
/// <summary>Whether the page has unsaved changes (orange dot, warning on close).</summary>
|
||||
public bool IsModified { get; private set; }
|
||||
|
||||
/// <summary>The page content.</summary>
|
||||
public RenderFragment? Content { get; internal set; }
|
||||
|
||||
/// <summary>When the tab was last activated, to choose which one to drop past the limit.</summary>
|
||||
public long LastUsed { get; internal set; }
|
||||
|
||||
/// <summary>Sets the title shown in the tab.</summary>
|
||||
/// <param name="title">The title.</param>
|
||||
/// <param name="icon">The icon, or <see langword="null"/>.</param>
|
||||
public void SetTitle(string? title, string? icon = null)
|
||||
{
|
||||
if (Title == title && Icon == icon)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Title = title;
|
||||
Icon = icon;
|
||||
_owner.Notify();
|
||||
}
|
||||
|
||||
/// <summary>Marks the page as modified or saved.</summary>
|
||||
/// <param name="modified">Whether there are unsaved changes.</param>
|
||||
public void SetModified(bool modified)
|
||||
{
|
||||
if (IsModified == modified)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
IsModified = modified;
|
||||
_owner.Notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What happened when an address was opened.</summary>
|
||||
public enum TabOpenResult
|
||||
{
|
||||
/// <summary>A tab already open was activated.</summary>
|
||||
Activated = 0,
|
||||
|
||||
/// <summary>A new tab was opened.</summary>
|
||||
Opened = 1,
|
||||
|
||||
/// <summary>A new tab was opened and the least recently used unmodified tab was closed to stay within the limit.</summary>
|
||||
OpenedAndEvicted = 2,
|
||||
|
||||
/// <summary>The limit is reached and every tab has unsaved changes: nothing was opened.</summary>
|
||||
Refused = 3,
|
||||
}
|
||||
|
||||
/// <summary>The open tabs of a circuit (SPEC §10.2): at most <see cref="MaxTabs"/>, one active.</summary>
|
||||
public sealed class TabService
|
||||
{
|
||||
/// <summary>The largest number of open tabs.</summary>
|
||||
public const int MaxTabs = 12;
|
||||
|
||||
/// <summary>The largest number of recent addresses kept for the "recent" menu.</summary>
|
||||
public const int MaxRecent = 10;
|
||||
|
||||
private readonly List<KhTab> _tabs = [];
|
||||
private readonly List<string> _recent = [];
|
||||
private long _clock;
|
||||
|
||||
/// <summary>Raised when tabs open, close, change title or state.</summary>
|
||||
public event Action? Changed;
|
||||
|
||||
/// <summary>The open tabs, in order.</summary>
|
||||
public IReadOnlyList<KhTab> Tabs => _tabs;
|
||||
|
||||
/// <summary>The active tab.</summary>
|
||||
public KhTab? Active { get; private set; }
|
||||
|
||||
/// <summary>The addresses opened most recently, newest first.</summary>
|
||||
public IReadOnlyList<string> Recent => _recent;
|
||||
|
||||
/// <summary>Whether any tab has unsaved changes.</summary>
|
||||
public bool HasModified => _tabs.Exists(t => t.IsModified);
|
||||
|
||||
/// <summary>The path of an address: no query, no fragment, no trailing slash.</summary>
|
||||
/// <param name="url">The address relative to the base (<c>anagrafiche/clienti?x=1</c>) or absolute path.</param>
|
||||
/// <returns>The path, starting with <c>/</c>.</returns>
|
||||
public static string PathOf(string url)
|
||||
{
|
||||
var path = (url ?? string.Empty).Split('?', '#')[0];
|
||||
path = "/" + path.Trim('/');
|
||||
return path;
|
||||
}
|
||||
|
||||
/// <summary>Opens or activates the tab of an address with the page content.</summary>
|
||||
/// <param name="url">The address.</param>
|
||||
/// <param name="content">The page content.</param>
|
||||
/// <returns>What happened.</returns>
|
||||
public TabOpenResult Open(string url, RenderFragment? content)
|
||||
{
|
||||
var path = PathOf(url);
|
||||
var normalized = path + QueryOf(url);
|
||||
var existing = _tabs.Find(t => string.Equals(t.Path, path, StringComparison.OrdinalIgnoreCase));
|
||||
TabOpenResult result;
|
||||
if (existing is not null)
|
||||
{
|
||||
existing.Url = normalized;
|
||||
existing.Content = content ?? existing.Content;
|
||||
result = TabOpenResult.Activated;
|
||||
}
|
||||
else
|
||||
{
|
||||
result = TabOpenResult.Opened;
|
||||
if (_tabs.Count >= MaxTabs)
|
||||
{
|
||||
var victim = _tabs.Where(t => !t.IsModified && t != Active).MinBy(t => t.LastUsed);
|
||||
if (victim is null)
|
||||
{
|
||||
return TabOpenResult.Refused;
|
||||
}
|
||||
|
||||
_tabs.Remove(victim);
|
||||
result = TabOpenResult.OpenedAndEvicted;
|
||||
}
|
||||
|
||||
existing = new KhTab(this, path, normalized) { Content = content };
|
||||
var at = Active is null ? _tabs.Count : _tabs.IndexOf(Active) + 1;
|
||||
_tabs.Insert(at, existing);
|
||||
}
|
||||
|
||||
existing.LastUsed = ++_clock;
|
||||
Active = existing;
|
||||
_recent.RemoveAll(r => string.Equals(PathOf(r), path, StringComparison.OrdinalIgnoreCase));
|
||||
_recent.Insert(0, normalized);
|
||||
if (_recent.Count > MaxRecent)
|
||||
{
|
||||
_recent.RemoveRange(MaxRecent, _recent.Count - MaxRecent);
|
||||
}
|
||||
|
||||
Notify();
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Closes a tab.</summary>
|
||||
/// <param name="tab">The tab.</param>
|
||||
/// <returns>The address to show next when the closed tab was active, otherwise <see langword="null"/>.</returns>
|
||||
public string? Close(KhTab tab)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(tab);
|
||||
var index = _tabs.IndexOf(tab);
|
||||
if (index < 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
_tabs.RemoveAt(index);
|
||||
string? next = null;
|
||||
if (tab == Active)
|
||||
{
|
||||
Active = null;
|
||||
var neighbour = _tabs.Count == 0 ? null : _tabs[Math.Min(index, _tabs.Count - 1)];
|
||||
next = neighbour?.Url ?? "/";
|
||||
}
|
||||
|
||||
Notify();
|
||||
return next;
|
||||
}
|
||||
|
||||
/// <summary>The tab after (or before) the active one, cycling.</summary>
|
||||
/// <param name="step">+1 for the next, -1 for the previous.</param>
|
||||
/// <returns>The tab, or <see langword="null"/> with fewer than two tabs.</returns>
|
||||
public KhTab? Neighbour(int step)
|
||||
{
|
||||
if (_tabs.Count < 2 || Active is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var index = _tabs.IndexOf(Active);
|
||||
return _tabs[((index + step) % _tabs.Count + _tabs.Count) % _tabs.Count];
|
||||
}
|
||||
|
||||
/// <summary>Finds the tab of an address.</summary>
|
||||
/// <param name="url">The address.</param>
|
||||
/// <returns>The tab, or <see langword="null"/>.</returns>
|
||||
public KhTab? Find(string url)
|
||||
{
|
||||
var path = PathOf(url);
|
||||
return _tabs.Find(t => string.Equals(t.Path, path, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
internal void Notify() => Changed?.Invoke();
|
||||
|
||||
private static string QueryOf(string url)
|
||||
{
|
||||
var index = (url ?? string.Empty).IndexOf('?', StringComparison.Ordinal);
|
||||
return index < 0 ? string.Empty : url![index..].Split('#')[0];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Preferences;
|
||||
using Microsoft.JSInterop;
|
||||
|
||||
namespace Khaemhat.Web.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// Applies the interface preferences of SPEC §10.6 to the root element: <c>data-theme</c>, <c>data-accent</c>,
|
||||
/// <c>data-density</c>, <c>data-text-size</c> and the switches. The first page render writes them on the server
|
||||
/// (<c>App.razor</c>); changes made in the session are applied at once through the browser script.
|
||||
/// </summary>
|
||||
/// <param name="js">The browser.</param>
|
||||
/// <param name="session">The shell session.</param>
|
||||
public sealed class ThemeService(IJSRuntime js, ShellSession session)
|
||||
{
|
||||
/// <summary>The root attributes of some preferences.</summary>
|
||||
/// <param name="preferences">The preferences; <see langword="null"/> before sign-in (system theme).</param>
|
||||
/// <returns>The attributes by name.</returns>
|
||||
public static IReadOnlyDictionary<string, string> RootAttributes(UserPreferences? preferences)
|
||||
{
|
||||
var p = preferences ?? UserPreferences.Default;
|
||||
return new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["data-theme"] = p.ThemeAttribute,
|
||||
["data-accent"] = p.Accent,
|
||||
["data-density"] = p.DensityAttribute,
|
||||
["data-text-size"] = p.TextSize.ToString(CultureInfo.InvariantCulture),
|
||||
["data-tabular"] = p.TabularNumbers ? "on" : "off",
|
||||
["data-motion"] = p.ReducedMotion ? "reduced" : "full",
|
||||
["data-tooltips"] = p.Tooltips ? "on" : "off",
|
||||
["data-row-hover"] = p.RowHover ? "on" : "off",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Applies preferences to the page without saving them (live preview).</summary>
|
||||
/// <param name="preferences">The preferences.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task PreviewAsync(UserPreferences preferences)
|
||||
{
|
||||
try
|
||||
{
|
||||
await js.InvokeVoidAsync("khaemhat.applyRoot", RootAttributes(preferences)).ConfigureAwait(false);
|
||||
}
|
||||
catch (JSDisconnectedException)
|
||||
{
|
||||
// The page was closed.
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Applies and saves preferences.</summary>
|
||||
/// <param name="preferences">The preferences.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task ApplyAsync(UserPreferences preferences)
|
||||
{
|
||||
await PreviewAsync(preferences).ConfigureAwait(false);
|
||||
await session.SavePreferencesAsync(preferences).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The quick switch of the top bar: dark when the current theme is light or automatic, light otherwise.</summary>
|
||||
/// <returns>A task.</returns>
|
||||
public Task ToggleDarkAsync()
|
||||
{
|
||||
var current = session.Preferences;
|
||||
var next = current.Theme is ThemeMode.Dark ? ThemeMode.Light : ThemeMode.Dark;
|
||||
return ApplyAsync(current with { Theme = next });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user