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:
Alby96andClaude Opus 5.5 committed 2026-11-11 16:44:59 +01:00
1 parent 1c30054e3d
commit cf6f849cc1
72 files changed
+5785 -259

No files matched your search

@@ -0,0 +1,273 @@
using System.Text;
using System.Text.RegularExpressions;
using Khaemhat.Application.Preferences;
using Khaemhat.Web.Shell;
namespace Khaemhat.Web.Tests.Shell;
/// <summary>
/// The rule of SPEC §1.9 and issue #33: components contain no literal interface texts, every text comes from
/// <c>Resources/it-IT/*.json</c>, and every key the code asks for exists.
/// </summary>
[TestClass]
public sealed partial class LocalizationRulesTests
{
// Words allowed as they are: the product name and the names of things that are not translated.
private static readonly HashSet<string> Allowed = new(StringComparer.Ordinal) { "Khaemhat" };
[TestMethod]
public void Components_ContainNoLiteralTexts()
{
var problems = new List<string>();
foreach (var file in ComponentFiles())
{
foreach (var text in LiteralTexts(File.ReadAllText(file)))
{
problems.Add(Path.GetRelativePath(Repository.Root, file) + ": " + text);
}
}
Assert.IsEmpty(problems, "Texts belong in Resources/it-IT/*.json:\n" + string.Join('\n', problems));
}
[TestMethod]
public void TheCheck_FindsLiteralTexts_AndLetsTheRestThrough()
{
const string page = """
@page "/x"
@inject Foo Bar
@* A comment with words is fine. *@
<h1>@T["Pages.X.Title"]</h1>
<p class="lead">Testo scritto a mano</p>
<button title="Chiudi" aria-label="@T["Common.Close"]">@T.Format("Pages.X.Count", items.Count(i => i > 0))</button>
<img alt="" src="x.svg" />
<span>@(a ? T["A"] : T["B"]) · @Model.Name</span>
<input placeholder="Cerca" />
@foreach (var item in Items.Where(i => i.Level > 2))
{
<li>@item.Name</li>
}
<span>&times; ● Khaemhat @Session.Company?.Code @if (n.Body is not null) {<br />}</span>
@code {
private string Text => "Un testo nel codice";
}
""";
var found = LiteralTexts(page).ToList();
CollectionAssert.AreEquivalent(new[] { "Testo scritto a mano", "title=\"Chiudi\"", "placeholder=\"Cerca\"" }, found);
}
[TestMethod]
public void EveryTextKeyInTheCode_Exists()
{
var missing = new List<string>();
foreach (var file in Directory.EnumerateFiles(Path.Combine(Repository.Root, "src", "Khaemhat.Web"), "*.*", SearchOption.AllDirectories)
.Where(f => (f.EndsWith(".razor", StringComparison.Ordinal) || f.EndsWith(".cs", StringComparison.Ordinal)) && !Repository.IsBuildOutput(f)))
{
foreach (Match match in KeyPattern().Matches(File.ReadAllText(file)))
{
var key = match.Groups[1].Value;
if (!key.EndsWith('.') && !ShellTests.Texts.Contains(key))
{
missing.Add(Path.GetFileName(file) + ": " + key);
}
}
}
Assert.IsEmpty(missing, string.Join('\n', missing));
}
[TestMethod]
public void KeysBuiltFromValues_Exist()
{
var keys = new List<string>();
keys.AddRange(Enum.GetValues<ThemeMode>().Select(v => "Pages.Profile.Theme." + v));
keys.AddRange(Enum.GetValues<Density>().Select(v => "Pages.Profile.Density." + v));
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));
Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).ToList());
}
[TestMethod]
public void TextFiles_AvoidCharactersGiteaFlagsAsAmbiguous()
{
var folder = Path.Combine(Repository.Root, "src", "Khaemhat.Web", "Resources");
foreach (var file in Directory.EnumerateFiles(folder, "*.json", SearchOption.AllDirectories))
{
var text = File.ReadAllText(file);
foreach (var c in new[] { '–', '×', '−', '›' })
{
Assert.DoesNotContain(c.ToString(), text, Path.GetFileName(file) + " contains U+" + ((int)c).ToString("X4", System.Globalization.CultureInfo.InvariantCulture));
}
}
}
internal static IEnumerable<string> ComponentFiles() =>
Directory.EnumerateFiles(Path.Combine(Repository.Root, "src", "Khaemhat.Web", "Components"), "*.razor", SearchOption.AllDirectories)
.Where(f => !Repository.IsBuildOutput(f));
/// <summary>The literal texts of a component: text between tags and text attributes, once code and expressions are removed.</summary>
/// <param name="razor">The component source.</param>
/// <returns>The texts found.</returns>
internal static IEnumerable<string> LiteralTexts(string razor)
{
var markup = CommentPattern().Replace(razor, string.Empty);
var code = markup.IndexOf("@code", StringComparison.Ordinal);
if (code >= 0)
{
markup = markup[..code];
}
var lines = markup.Split('\n').Select(l => CodeLinePattern().IsMatch(l) ? string.Empty : l);
markup = StripExpressions(string.Join('\n', lines));
foreach (Match attribute in AttributePattern().Matches(markup))
{
if (HasWords(attribute.Groups[2].Value))
{
yield return attribute.Groups[1].Value + "=\"" + attribute.Groups[2].Value + "\"";
}
}
foreach (Match node in TextNodePattern().Matches(markup))
{
var text = node.Groups[1].Value.Trim();
if (HasWords(text))
{
yield return text;
}
}
}
private static bool HasWords(string text)
{
var words = WordPattern().Matches(EntityPattern().Replace(text, " ")).Select(m => m.Value).Where(w => !Allowed.Contains(w));
return words.Any();
}
// Removes Razor expressions: @T["..."], @T.Format(...), @(...), @item.Name, @Model.Items[0].Text...
private static string StripExpressions(string text)
{
var result = new StringBuilder(text.Length);
var i = 0;
while (i < text.Length)
{
if (text[i] != '@' || i + 1 >= text.Length)
{
result.Append(text[i++]);
continue;
}
i++;
if (text[i] == '(')
{
i = SkipBalanced(text, i);
continue;
}
var start = i;
while (i < text.Length && (char.IsLetterOrDigit(text[i]) || text[i] == '_'))
{
i++;
while (i < text.Length && text[i] is '[' or '(')
{
i = SkipBalanced(text, i);
}
// Member access, also null-conditional (?.) and null-forgiving (!.).
if (i + 2 < text.Length && text[i] is '?' or '!' && text[i + 1] == '.' && char.IsLetter(text[i + 2]))
{
i += 2;
}
else if (i + 1 < text.Length && text[i] == '.' && char.IsLetter(text[i + 1]))
{
i++;
}
}
// @if (...) { ... } written inside a line of markup: the condition is code.
if (text.AsSpan(start, i - start) is "if" or "foreach" or "for" or "while" or "switch")
{
while (i < text.Length && text[i] == ' ')
{
i++;
}
if (i < text.Length && text[i] == '(')
{
i = SkipBalanced(text, i);
}
}
}
return result.ToString();
}
private static int SkipBalanced(string text, int start)
{
var depth = 0;
var quote = '\0';
for (var i = start; i < text.Length; i++)
{
var c = text[i];
if (quote != '\0')
{
if (c == '\\')
{
i++;
}
else if (c == quote)
{
quote = '\0';
}
continue;
}
switch (c)
{
case '"' or '\'':
quote = c;
break;
case '(' or '[' or '{':
depth++;
break;
case ')' or ']' or '}':
depth--;
if (depth == 0)
{
return i + 1;
}
break;
}
}
return text.Length;
}
[GeneratedRegex(@"@\*.*?\*@", RegexOptions.Singleline)]
private static partial Regex CommentPattern();
// Lines of C#: directives, control flow, braces, local declarations and assignments inside code blocks.
[GeneratedRegex(@"^\s*(@(page|inject|using|attribute|layout|implements|inherits|namespace|rendermode|typeparam|foreach|for|if|switch|while|else)\b|@\{|\{|\}|(else|case|default|break|var|if|foreach|return)\b|[a-z_][A-Za-z0-9_.]*\s*(=[^=>]|\+\+|--)|(string|int|bool|long)\??\s)")]
private static partial Regex CodeLinePattern();
[GeneratedRegex("\\b(title|placeholder|alt|aria-label|label)=\"([^\"]*)\"")]
private static partial Regex AttributePattern();
[GeneratedRegex(@">([^<>]+)<")]
private static partial Regex TextNodePattern();
[GeneratedRegex(@"\p{L}{2,}")]
private static partial Regex WordPattern();
[GeneratedRegex(@"&[a-zA-Z]+;|&#\d+;")]
private static partial Regex EntityPattern();
[GeneratedRegex("\"((?:Shell|Pages|Auth|Common)\\.[A-Za-z0-9_.]+)\"")]
private static partial Regex KeyPattern();
}
@@ -0,0 +1,47 @@
using Khaemhat.Application.Preferences;
using Khaemhat.Application.Security;
using Khaemhat.Core.Security;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.Shell;
/// <summary>The preferences are kept per user: instance accounts in the system database, company users in their company (issue #31).</summary>
[TestClass]
public sealed class PreferencesStoreTests
{
[TestMethod]
public async Task Preferences_AreSavedPerUser_InTheRightDatabase()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var settings = app.Services.GetRequiredService<UserSettingsService>();
var root = new Actor(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
var companyUser = new Actor("mario", UserLevel.Standard, null, 1, company);
var otherCompanyUser = new Actor("lucia", UserLevel.Standard, null, 2, company);
Assert.AreEqual(UserPreferences.Default, await settings.GetPreferencesAsync(root));
var dark = UserPreferences.Default with { Theme = ThemeMode.Dark, Accent = "ametista", MenuCollapsed = true };
await settings.SavePreferencesAsync(root, dark);
await settings.SavePreferencesAsync(companyUser, UserPreferences.Default with { Density = Density.Compact });
Assert.AreEqual(dark, await settings.GetPreferencesAsync(root));
Assert.AreEqual(Density.Compact, (await settings.GetPreferencesAsync(companyUser)).Density);
Assert.AreEqual(ThemeMode.Auto, (await settings.GetPreferencesAsync(companyUser)).Theme, "Users do not share preferences.");
Assert.AreEqual(UserPreferences.Default, await settings.GetPreferencesAsync(otherCompanyUser));
// A saved value can be changed and removed.
await settings.SetAsync(root, PreferenceKeys.OpenTabs, "{\"active\":\"/\"}");
Assert.AreEqual("{\"active\":\"/\"}", await settings.GetAsync(root, PreferenceKeys.OpenTabs));
await settings.SetAsync(root, PreferenceKeys.OpenTabs, null);
Assert.IsNull(await settings.GetAsync(root, PreferenceKeys.OpenTabs));
// Limits: the key is short, the value at most 64 KB.
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => settings.SetAsync(root, new string('k', 201), "x"));
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => settings.SetAsync(root, "ui.big", new string('x', UserSettingsService.MaxValueLength + 1)));
await app.StopAsync();
}
}
}
@@ -0,0 +1,30 @@
namespace Khaemhat.Web.Tests.Shell;
/// <summary>The repository the tests run from, to read sources, wiki pages and assets.</summary>
internal static class Repository
{
private static readonly Lazy<string> RootPath = new(() =>
{
for (var folder = new DirectoryInfo(AppContext.BaseDirectory); folder is not null; folder = folder.Parent)
{
if (File.Exists(Path.Combine(folder.FullName, "Khaemhat.sln")))
{
return folder.FullName;
}
}
throw new InvalidOperationException("Khaemhat.sln not found above " + AppContext.BaseDirectory);
});
/// <summary>The folder holding <c>Khaemhat.sln</c>.</summary>
public static string Root => RootPath.Value;
/// <summary>Whether a file is under <c>bin/</c> or <c>obj/</c>.</summary>
/// <param name="path">The file.</param>
/// <returns><see langword="true"/> for build output.</returns>
public static bool IsBuildOutput(string path)
{
var parts = path.Replace('\\', '/').Split('/');
return parts.Contains("bin") || parts.Contains("obj");
}
}
@@ -0,0 +1,169 @@
using System.Globalization;
using Khaemhat.Application.Localization;
using Khaemhat.Application.Preferences;
using Khaemhat.Application.Security;
using Khaemhat.Web.Hosting;
using Khaemhat.Web.Shell;
namespace Khaemhat.Web.Tests.Shell;
/// <summary>The shell of SPEC §10.2: tabs, menu, shortcuts and help (issues #25, #26).</summary>
[TestClass]
public sealed class ShellTests
{
internal static readonly ITexts Texts = JsonTextProvider.FromAssembly(typeof(KhaemhatApp).Assembly, CultureInfo.GetCultureInfo("it-IT"));
[TestMethod]
public void Tabs_OpenOncePerPath_AndKeepTheLatestAddress()
{
var tabs = new TabService();
Assert.AreEqual(TabOpenResult.Opened, tabs.Open("/anagrafiche/clienti", null));
Assert.AreEqual(TabOpenResult.Opened, tabs.Open("profilo", null));
Assert.AreEqual(TabOpenResult.Activated, tabs.Open("/profilo?scheda=sessioni", null));
Assert.HasCount(2, tabs.Tabs);
Assert.AreEqual("/profilo", tabs.Active!.Path);
Assert.AreEqual("/profilo?scheda=sessioni", tabs.Active.Url);
Assert.AreEqual("/profilo?scheda=sessioni", tabs.Recent[0]);
}
[TestMethod]
public void Tabs_AtTheLimit_CloseTheLeastUsedUnmodifiedTab()
{
var tabs = new TabService();
for (var i = 0; i < TabService.MaxTabs; i++)
{
tabs.Open("/p" + i.ToString(CultureInfo.InvariantCulture), null);
}
tabs.Find("/p0")!.SetModified(true);
tabs.Open("/p1", null);
Assert.AreEqual(TabOpenResult.OpenedAndEvicted, tabs.Open("/nuova", null));
Assert.HasCount(TabService.MaxTabs, tabs.Tabs);
Assert.IsNotNull(tabs.Find("/p0"), "A tab with unsaved changes is never closed for room.");
Assert.IsNotNull(tabs.Find("/p1"), "A tab used recently stays.");
Assert.IsNull(tabs.Find("/p2"), "The least recently used tab goes.");
}
[TestMethod]
public void Tabs_AtTheLimit_WithEveryTabModified_RefuseANewOne()
{
var tabs = new TabService();
for (var i = 0; i < TabService.MaxTabs; i++)
{
tabs.Open("/p" + i.ToString(CultureInfo.InvariantCulture), null);
tabs.Active!.SetModified(true);
}
Assert.AreEqual(TabOpenResult.Refused, tabs.Open("/nuova", null));
Assert.HasCount(TabService.MaxTabs, tabs.Tabs);
Assert.IsTrue(tabs.HasModified);
}
[TestMethod]
public void Tabs_ClosingTheActiveTab_ShowsANeighbour()
{
var tabs = new TabService();
tabs.Open("/a", null);
tabs.Open("/b", null);
tabs.Open("/c", null);
tabs.Open("/b", null);
// The tab after the closed one takes its place (the layout then navigates there).
var next = tabs.Close(tabs.Active!);
Assert.AreEqual("/c", next);
Assert.HasCount(2, tabs.Tabs);
Assert.IsNull(tabs.Find("/b"));
tabs.Open(next!, null);
Assert.IsNull(tabs.Close(tabs.Find("/a")!), "Closing a tab in the background moves nothing.");
Assert.AreEqual("/c", tabs.Active!.Path);
Assert.AreEqual("/", tabs.Close(tabs.Active), "Closing the last tab goes back to the home page.");
}
[TestMethod]
[DataRow("/anagrafiche/clienti", "Shell.Menu.Parties.Customers", "Shell.Menu.Parties")]
[DataRow("/anagrafiche/clienti/42", "Shell.Menu.Parties.Customers", "Shell.Menu.Parties")]
[DataRow("/contabilita", "Shell.Menu.Ledger", "Shell.Menu.Ledger")]
[DataRow("/", "Shell.Menu.Home", "Shell.Menu.Home")]
public void Menu_FindsTheDeepestEntry(string path, string entry, string area)
{
Assert.AreEqual(entry, MenuCatalog.Find(path)?.Key);
Assert.AreEqual(area, MenuCatalog.FindArea(path)?.Key);
}
[TestMethod]
public void Menu_FollowsTheOrderOfTheSpecification_AndEveryEntryHasTextAndIcon()
{
string[] order =
[
"Shell.Menu.Home", "Shell.Menu.Parties", "Shell.Menu.Crm", "Shell.Menu.Sales", "Shell.Menu.Purchases", "Shell.Menu.Inventory",
"Shell.Menu.Ledger", "Shell.Menu.Finance", "Shell.Menu.EInvoicing", "Shell.Menu.Assets", "Shell.Menu.Services", "Shell.Menu.Channels",
"Shell.Menu.Reports", "Shell.Menu.CompanyTables", "Shell.Menu.Automation", "Shell.Menu.Admin",
];
CollectionAssert.AreEqual(order, MenuCatalog.Sections.SelectMany(s => s.Items).Select(i => i.Key).ToArray());
var sprite = File.ReadAllText(Path.Combine(Repository.Root, "src", "Khaemhat.Web", "wwwroot", "icons", "sprite.svg"));
foreach (var item in MenuCatalog.All)
{
Assert.IsTrue(Texts.Contains(item.Key), item.Key);
StringAssert.Contains(sprite, "id=\"" + item.Icon + "\"", item.Key);
}
Assert.AreEqual(MenuCatalog.All.Count(), MenuCatalog.All.Select(i => i.Href).Distinct(StringComparer.Ordinal).Count(), "Addresses are unique.");
}
[TestMethod]
public void Help_EveryMenuEntryOpensAnExistingWikiPage()
{
foreach (var item in MenuCatalog.All.Append(new MenuItem("x", "x", "/profilo", "CORE", null, null)))
{
var page = HelpLinks.PageFor(item.Href);
Assert.IsTrue(File.Exists(Path.Combine(Repository.Root, "docs", "wiki", page + ".md")), item.Href + " -> " + page);
}
Assert.AreEqual("Articoli-e-listini", HelpLinks.PageFor("/anagrafiche/articoli/12?x=1"));
Assert.AreEqual(HelpLinks.DefaultBaseUrl + "IVA", HelpLinks.UrlFor(HelpLinks.DefaultBaseUrl, "/contabilita/registri-iva"));
}
[TestMethod]
public void Shortcuts_AreUnique_AndDescribed()
{
var combos = KeyboardShortcuts.All.SelectMany(s => s.Keys).ToList();
Assert.HasCount(combos.Distinct(StringComparer.Ordinal).Count(), combos, "A key combination belongs to one command.");
foreach (var shortcut in KeyboardShortcuts.All)
{
Assert.IsTrue(Texts.Contains(shortcut.TextKey), shortcut.TextKey);
}
// Browsers keep Ctrl+W, Ctrl+Tab and Ctrl+N for themselves: each has an alternative that reaches the page.
Assert.Contains("Alt+W", KeyboardShortcuts.Find(KeyboardShortcuts.Commands.CloseTab)!.Keys);
Assert.Contains("Alt+PageDown", KeyboardShortcuts.Find(KeyboardShortcuts.Commands.NextTab)!.Keys);
Assert.Contains("Alt+N", KeyboardShortcuts.Find(KeyboardShortcuts.Commands.New)!.Keys);
}
[TestMethod]
public void Theme_WritesEveryRootAttribute()
{
var attributes = ThemeService.RootAttributes(new UserPreferences { Theme = ThemeMode.Dark, Accent = "ocra", TextSize = 110, ReducedMotion = true });
Assert.AreEqual("dark", attributes["data-theme"]);
Assert.AreEqual("ocra", attributes["data-accent"]);
Assert.AreEqual("110", attributes["data-text-size"]);
Assert.AreEqual("reduced", attributes["data-motion"]);
Assert.AreEqual("auto", ThemeService.RootAttributes(null)["data-theme"]);
}
[TestMethod]
public void SignInMessages_ExistForEveryErrorCode()
{
var codes = typeof(SecurityErrors).GetFields().Where(f => f.IsLiteral).Select(f => (string)f.GetRawConstantValue()!).ToList();
Assert.IsNotEmpty(codes);
foreach (var code in codes)
{
Assert.IsTrue(Texts.Contains("Auth.Errors." + code), code);
}
}
}