feat: widget dashboard and company settings (#30, #31)

The home page becomes the widget dashboard of mockups 004-006. Each user
switches widgets on and off, orders them (drag and drop or buttons that
also work from the keyboard), sizes them on the 12-column grid and picks
the start page; every change is saved at once. Whoever may change the
company settings sets a default layout per role, used by people who
never customized; Reset goes back to it.

Todo, Done and Deadlines collect lines from sources each module
registers, so later milestones fill them without touching the widgets;
a failing source is logged and skipped. M3 provides licence, unread
warnings and scheduled task runs. Notes, Shortcuts and System status
work now; widgets of modules still to come say which milestone brings
their data instead of showing fake numbers.

Role defaults live in the new company_settings table, written through
CompanySettingsService with company.settings.write (ADR 0022).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 19:15:06 +01:00
1 parent 75d60ee4c4
commit acb7e598d1
34 files changed
+2812 -76

No files matched your search

@@ -0,0 +1,18 @@
@* A widget whose data comes from a module still to come (SPEC §10.3): it can already be placed and sized, and says
which milestone fills it. *@
<KhWidget Id="@Definition.Id" Title="@T[Definition.TitleKey]" Icon="@Definition.Icon">
<div class="kh-wcoming">
<KhIcon Name="clock" />
<p class="muted">@T[Definition.DescriptionKey]</p>
@if (Definition.Milestone is { } milestone)
{
<p class="s">@T.Format("Dashboard.Coming.Text", T["Dashboard.Coming." + milestone], milestone)</p>
}
</div>
</KhWidget>
@code {
/// <summary>The widget.</summary>
[Parameter, EditorRequired]
public WidgetDefinition Definition { get; set; } = default!;
}
@@ -0,0 +1,31 @@
@* Picks the component of a widget of the layout. *@
@switch (Definition.Id)
{
case WidgetIds.Todo:
<FeedWidget Definition="Definition" Kind="FeedKind.Todo" />
break;
case WidgetIds.Done:
<FeedWidget Definition="Definition" Kind="FeedKind.Done" />
break;
case WidgetIds.Deadlines:
<FeedWidget Definition="Definition" Kind="FeedKind.Deadlines" />
break;
case WidgetIds.Notes:
<NotesWidget Definition="Definition" />
break;
case WidgetIds.Shortcuts:
<ShortcutsWidget Definition="Definition" />
break;
case WidgetIds.SystemStatus:
<SystemStatusWidget Definition="Definition" />
break;
default:
<ComingWidget Definition="Definition" />
break;
}
@code {
/// <summary>The widget.</summary>
[Parameter, EditorRequired]
public WidgetDefinition Definition { get; set; } = default!;
}
@@ -0,0 +1,140 @@
@inject ShellSession Session
@inject TodoAggregator Todos
@inject DoneAggregator Dones
@inject DeadlineAggregator Deadlines
@inject TimeProvider Clock
@* Da fare oggi, Fatto oggi and Scadenze 30 giorni (SPEC §10.3): the lines the sources of the modules give, with the
area at the side. Mockup 004. *@
<KhWidget Id="@Definition.Id" Title="@T[Definition.TitleKey]" Icon="@Definition.Icon" Tight="true">
<Actions>
@if (_items is { Count: > 0 })
{
<span class="badge @(Kind == FeedKind.Todo && _items.Any(i => i.Tone >= FeedTone.Warning) ? "red" : "gray")">@T.Number(_items.Count)</span>
}
</Actions>
<ChildContent>
@if (_failed)
{
<p class="kh-wempty"><KhIcon Name="alert" /> @T["Dashboard.Feed.Error"]</p>
}
else if (_items is null)
{
<p class="kh-wempty muted">@T["Dashboard.Feed.Loading"]</p>
}
else if (_items.Count == 0)
{
<p class="kh-wempty"><KhIcon Name="check-circle" /> @T[EmptyKey]</p>
}
else if (Kind == FeedKind.Deadlines)
{
<div class="kh-wlist">
@foreach (var item in _items)
{
<a class="deadline" href="@HrefOf(item)" aria-disabled="@(item.Href is null ? "true" : null)">
<div class="dd @DayClass(item)">
<b>@item.When!.Value.ToString("dd", T.Culture)</b>
<span>@item.When!.Value.ToString("MMM", T.Culture)</span>
</div>
<div>
<div class="dt">@item.Text</div>
<div class="ds">@Relative(item)@(item.Detail is null ? null : " · " + item.Detail)</div>
</div>
<span class="badge gray">@T[item.AreaKey]</span>
</a>
}
</div>
}
else
{
<div class="list kh-wlist">
@foreach (var item in _items)
{
<a class="li" href="@HrefOf(item)" aria-disabled="@(item.Href is null ? "true" : null)">
<span class="kh-tone @ToneClass(item.Tone)" aria-hidden="true"></span>
<div class="grow">
<div class="t">@item.Text</div>
@if (item.Detail is not null)
{
<div class="s">@item.Detail</div>
}
</div>
<span class="badge gray">@T[item.AreaKey]</span>
@if (Kind == FeedKind.Done && item.When is { } when)
{
<span class="s num">@when.ToString("HH:mm", T.Culture)</span>
}
</a>
}
</div>
}
</ChildContent>
</KhWidget>
@code {
private IReadOnlyList<FeedItem>? _items;
private bool _failed;
/// <summary>The widget.</summary>
[Parameter, EditorRequired]
public WidgetDefinition Definition { get; set; } = default!;
/// <summary>Which list.</summary>
[Parameter]
public FeedKind Kind { get; set; }
private string EmptyKey => Definition.TitleKey[..Definition.TitleKey.LastIndexOf('.')] + ".Empty";
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
if (Session.Actor is not { } actor)
{
_items = [];
return;
}
try
{
_items = Kind switch
{
FeedKind.Todo => await Todos.GetAsync(actor),
FeedKind.Done => await Dones.GetAsync(actor),
_ => await Deadlines.GetAsync(actor),
};
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_failed = true;
}
}
private static string? HrefOf(FeedItem item) => item.Href?.TrimStart('/') is { } href ? (href.Length == 0 ? "./" : href) : null;
private static string ToneClass(FeedTone tone) => tone switch
{
FeedTone.Ok => "ok",
FeedTone.Info => "info",
FeedTone.Warning => "warn",
FeedTone.Error => "err",
_ => "neutral",
};
private int DaysTo(FeedItem item) =>
DateOnly.FromDateTime(item.When!.Value.DateTime).DayNumber - DateOnly.FromDateTime(Clock.GetLocalNow().DateTime).DayNumber;
private string? DayClass(FeedItem item) => DaysTo(item) switch
{
<= 1 => "hot",
<= 7 => "warm",
_ => null,
};
private string Relative(FeedItem item) => DaysTo(item) switch
{
<= 0 => T["Dashboard.Feed.Today"],
1 => T["Dashboard.Feed.Tomorrow"],
var days => T.Format("Dashboard.Feed.InDays", days),
};
}
@@ -0,0 +1,110 @@
@inject ShellSession Session
@inject DashboardService Dashboard
@inject ToastService Toasts
@* Promemoria personali (SPEC §10.3): free notes of the user, ticked when done, saved as they change. *@
<KhWidget Id="@Definition.Id" Title="@T[Definition.TitleKey]" Icon="@Definition.Icon" Tight="true">
<Actions>
@if (_notes.Any(n => n.Done))
{
<button type="button" class="ib" title="@T["Dashboard.Widgets.Notes.ClearDone"]" aria-label="@T["Dashboard.Widgets.Notes.ClearDone"]"
@onclick="ClearDoneAsync"><KhIcon Name="trash" /></button>
}
</Actions>
<ChildContent>
<div class="kh-wlist">
@for (var i = 0; i < _notes.Count; i++)
{
var index = i;
var note = _notes[i];
<div class="chk-row @(note.Done ? "done" : null)">
<input type="checkbox" checked="@note.Done" aria-label="@T.Format("Dashboard.Widgets.Notes.Toggle", note.Text)"
@onchange="() => ToggleAsync(index)" />
<div class="t">@note.Text</div>
<button type="button" class="ib kh-rowx" title="@T.Format("Dashboard.Widgets.Notes.Remove", note.Text)"
aria-label="@T.Format("Dashboard.Widgets.Notes.Remove", note.Text)" @onclick="() => RemoveAsync(index)"><KhIcon Name="x" /></button>
</div>
}
@if (_loaded && _notes.Count == 0)
{
<p class="kh-wempty muted">@T["Dashboard.Widgets.Notes.Empty"]</p>
}
</div>
<div class="kh-wadd">
<KhIcon Name="plus" Class="sm" />
<input class="kh-input" value="@_text" maxlength="@DashboardService.MaxNoteLength" aria-label="@T["Dashboard.Widgets.Notes.Add"]"
placeholder="@T["Dashboard.Widgets.Notes.Placeholder"]" @oninput="e => _text = e.Value as string" @onkeydown="OnKeyDownAsync" />
</div>
</ChildContent>
</KhWidget>
@code {
private List<PersonalNote> _notes = [];
private string? _text;
private bool _loaded;
/// <summary>The widget.</summary>
[Parameter, EditorRequired]
public WidgetDefinition Definition { get; set; } = default!;
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
if (Session.Actor is { } actor)
{
_notes = [.. await Dashboard.GetNotesAsync(actor)];
}
_loaded = true;
}
private async Task OnKeyDownAsync(KeyboardEventArgs e)
{
if (e.Key != "Enter" || string.IsNullOrWhiteSpace(_text))
{
return;
}
if (_notes.Count >= DashboardService.MaxNotes)
{
Toasts.Show(ToastKind.Warning, T.Format("Dashboard.Widgets.Notes.Full", DashboardService.MaxNotes));
return;
}
// Show the text just typed before clearing, or Blazor would not see the field change and keep it.
_notes.Add(new PersonalNote(_text.Trim(), false));
var typed = _text;
_text = typed;
StateHasChanged();
await Task.Yield();
_text = null;
await SaveAsync();
}
private Task ToggleAsync(int index)
{
_notes[index] = _notes[index] with { Done = !_notes[index].Done };
return SaveAsync();
}
private Task RemoveAsync(int index)
{
_notes.RemoveAt(index);
return SaveAsync();
}
private Task ClearDoneAsync()
{
_notes.RemoveAll(n => n.Done);
return SaveAsync();
}
private async Task SaveAsync()
{
if (Session.Actor is { } actor)
{
await Dashboard.SaveNotesAsync(actor, _notes);
}
}
}
@@ -0,0 +1,105 @@
@inject ShellSession Session
@inject DashboardService Dashboard
@* Scorciatoie (SPEC §10.3): buttons to the pages the user opens most, chosen among the menu entries they can see.
Until chosen, the first areas of the menu. *@
<KhWidget Id="@Definition.Id" Title="@T[Definition.TitleKey]" Icon="@Definition.Icon">
<Actions>
<button type="button" class="ib" title="@T["Dashboard.Widgets.Shortcuts.Edit"]" aria-label="@T["Dashboard.Widgets.Shortcuts.Edit"]"
@onclick="Edit"><KhIcon Name="edit" /></button>
</Actions>
<ChildContent>
@if (Shortcuts.Count == 0)
{
<p class="kh-wempty muted">@T["Dashboard.Widgets.Shortcuts.Empty"]</p>
}
else
{
<div class="kh-shortcuts">
@foreach (var item in Shortcuts)
{
<a class="kh-shortcut" href="@(item.Href == "/" ? "./" : item.Href.TrimStart('/'))">
<span class="ico-box"><KhIcon Name="@item.Icon" /></span>
<span>@T[item.Key]</span>
</a>
}
</div>
}
</ChildContent>
</KhWidget>
<KhDialog Open="_editing" Title="@T["Dashboard.Widgets.Shortcuts.Edit"]" Icon="zap" Size="sm" OnClose="() => _editing = false">
<ChildContent>
<p class="muted">@T.Format("Dashboard.Widgets.Shortcuts.Hint", DashboardService.MaxShortcuts)</p>
<div class="kh-picklist">
@foreach (var item in Choices)
{
var chosen = _draft.Contains(item.Href);
<label class="chk">
<input type="checkbox" checked="@chosen" disabled="@(!chosen && _draft.Count >= DashboardService.MaxShortcuts)"
@onchange="() => Toggle(item.Href)" />
<KhIcon Name="@item.Icon" Class="sm" /> @T[item.Key]
</label>
}
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _editing = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" @onclick="SaveAsync"><KhIcon Name="check" /> @T["Common.Save"]</button>
</Footer>
</KhDialog>
@code {
private IReadOnlyList<string>? _paths;
private List<string> _draft = [];
private bool _editing;
/// <summary>The widget.</summary>
[Parameter, EditorRequired]
public WidgetDefinition Definition { get; set; } = default!;
private IEnumerable<MenuItem> Choices => MenuCatalog.All.Where(i => i.Href != "/" && Session.CanSee(i));
private IReadOnlyList<MenuItem> Shortcuts =>
_paths is null
? [.. MenuCatalog.Sections.SelectMany(s => s.Items).Where(i => i.Href != "/" && Session.CanSee(i)).Take(6)]
: [.. _paths.Select(p => Choices.FirstOrDefault(i => string.Equals(i.Href, p, StringComparison.OrdinalIgnoreCase))).OfType<MenuItem>()];
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
if (Session.Actor is { } actor)
{
_paths = await Dashboard.GetShortcutsAsync(actor);
}
}
private void Edit()
{
_draft = [.. Shortcuts.Select(i => i.Href)];
_editing = true;
}
private void Toggle(string href)
{
if (!_draft.Remove(href) && _draft.Count < DashboardService.MaxShortcuts)
{
_draft.Add(href);
}
}
private async Task SaveAsync()
{
// Keep the menu order: the buttons read like the menu.
var order = Choices.Select(i => i.Href).ToList();
var chosen = _draft.OrderBy(order.IndexOf).ToList();
if (Session.Actor is { } actor)
{
await Dashboard.SaveShortcutsAsync(actor, chosen);
}
_paths = chosen;
_editing = false;
}
}
@@ -0,0 +1,86 @@
@using Khaemhat.Application.Licensing
@using Khaemhat.Core.Caching
@using Khaemhat.Core.Common
@using Khaemhat.Data
@inject SystemStatusService Status
@inject ProductVersion Version
@inject ICacheProvider Cache
@inject ILicenseGate Licenses
@inject TimeProvider Clock
@* Stato del sistema (SPEC §10.3, administrators only): version, database, cache, licence, companies and the scheduled
tasks of today, each with a dot that turns yellow or red when something needs a look. *@
<KhWidget Id="@Definition.Id" Title="@T[Definition.TitleKey]" Icon="@Definition.Icon" Tight="true">
<div class="list kh-wlist kh-status">
<div class="li">
<span class="kh-tone ok" aria-hidden="true"></span>
<span class="grow">@T["Dashboard.Widgets.System.Version"]</span>
<span class="s num" title="@Version.Full">@Version.Version@(ShortRevision.Length == 0 ? null : " (" + ShortRevision + ")")</span>
</div>
<div class="li">
<span class="kh-tone ok" aria-hidden="true"></span>
<span class="grow">@T["Dashboard.Widgets.System.Database"]</span>
<span class="s">@(_status?.Engine == DbEngine.PostgreSql ? "PostgreSQL" : "SQLite")</span>
</div>
<div class="li">
<span class="kh-tone ok" aria-hidden="true"></span>
<span class="grow">@T["Dashboard.Widgets.System.Cache"]</span>
<span class="s">@(Cache.IsDistributed ? T["Dashboard.Widgets.System.Redis"] : T["Dashboard.Widgets.System.LocalCache"])</span>
</div>
<div class="li">
<span class="kh-tone @LicenseTone" aria-hidden="true"></span>
<span class="grow">@T["Dashboard.Widgets.System.License"]</span>
<span class="s">@LicenseText</span>
</div>
@if (_status is { } status)
{
<div class="li">
<span class="kh-tone @(status.FailedCompanies > 0 ? "err" : "ok")" aria-hidden="true"></span>
<span class="grow">@T["Dashboard.Widgets.System.Companies"]</span>
<span class="s">@(status.FailedCompanies > 0
? T.Format("Dashboard.Widgets.System.CompaniesFailed", status.Companies, status.FailedCompanies)
: T.Format("Dashboard.Widgets.System.CompaniesOk", status.Companies))</span>
</div>
<div class="li">
<span class="kh-tone @(status.JobsFailed > 0 ? "err" : "ok")" aria-hidden="true"></span>
<span class="grow">@T["Dashboard.Widgets.System.Jobs"]</span>
<span class="s">@T.Format("Dashboard.Widgets.System.JobsSummary", status.JobsSucceeded, status.JobsFailed)</span>
</div>
}
</div>
</KhWidget>
@code {
private SystemStatus? _status;
/// <summary>The widget.</summary>
[Parameter, EditorRequired]
public WidgetDefinition Definition { get; set; } = default!;
private string ShortRevision => Version.Revision.Length > 7 ? Version.Revision[..7] : Version.Revision;
private LicenseState License => Licenses.Current;
private int? DaysLeft => License.DaysLeft(Clock.GetUtcNow().UtcDateTime);
private string LicenseTone => License.Status switch
{
LicenseStatus.Expired => "err",
LicenseStatus.Grace => "err",
_ when DaysLeft <= LicenseFeedSource.RenewDays => "warn",
_ => "ok",
};
private string LicenseText => License switch
{
{ IsTestMode: true } => T["Dashboard.Widgets.System.LicenseTest"],
{ Status: LicenseStatus.Expired } => T["Dashboard.Widgets.System.LicenseExpired"],
{ Status: LicenseStatus.Grace } => T["Dashboard.Widgets.System.LicenseGrace"],
{ Kind: LicenseKind.Trial } => T.Format("Dashboard.Widgets.System.LicenseTrial", DaysLeft ?? 0),
_ when DaysLeft is { } days => T.Format("Dashboard.Widgets.System.LicenseDays", days),
_ => T["Dashboard.Widgets.System.LicenseUnlimited"],
};
/// <inheritdoc />
protected override async Task OnInitializedAsync() => _status = await Status.GetAsync();
}
+312 -46
View File
@@ -2,66 +2,228 @@
@attribute [Authorize]
@using Khaemhat.Application.Licensing
@using Khaemhat.Application.Modules
@using Khaemhat.Core.Security
@using Khaemhat.Application.Instance
@inject ShellSession Session
@inject DashboardService Dashboard
@inject ToastService Toasts
@inject TimeProvider Clock
@* The home page of SPEC §10.2 until the widget dashboard of mockup 004 (issue #30): who is signed in, the licence,
the company and the areas the user can open, with the milestone of those still to come. *@
@* The home page (SPEC §10.3, mockups 004 and 006): the widget dashboard, with the Personalizza panel to switch widgets
on and off, order and size them, choose the start page and, for whoever manages the company, the default of a
role. With the dashboard switched off, the areas the user can open. *@
<KhPageTitle Text="@T["Pages.Home.Title"]" Icon="home" />
<div class="phead">
<div>
<h1>@Greeting</h1>
<div class="sub">@T.Format("Pages.Home.Today", Today)</div>
</div>
</div>
<div class="cols cols-3 kh-home-tiles">
<div class="tile acc">
<div class="t"><KhIcon Name="key" Class="sm" /> @T["Pages.Home.LicenseTile"]</div>
<div class="v">@(License.Kind == LicenseKind.Trial ? T["Pages.Home.LicenseTrial"] : T["Pages.Home.LicenseFull"])</div>
<div class="d">@LicenseDetail</div>
</div>
<div class="tile">
<div class="t"><KhIcon Name="layers" Class="sm" /> @T["Pages.Home.ModulesTile"]</div>
<div class="v">@T.Format("Pages.Home.ModulesText", License.Modules.Count, ModuleRegistry.Default.Modules.Count)</div>
<div class="d">@(License.Modules.Count == 0 ? T["Pages.Home.ModulesNone"] : string.Join(" · ", License.Modules.Order(StringComparer.Ordinal)))</div>
</div>
<div class="tile">
<div class="t"><KhIcon Name="building" Class="sm" /> @T["Pages.Home.CompanyTile"]</div>
<div class="v">@(Session.Company?.Name ?? T["Pages.Home.CompanyNone"])</div>
<div class="d">@Session.Company?.Code</div>
</div>
</div>
<section class="panel" aria-labelledby="kh-home-areas">
<div class="ph"><KhIcon Name="grid" /> <span id="kh-home-areas">@T["Pages.Home.AreasTitle"]</span></div>
<div class="pb">
<p class="muted">@T["Pages.Home.AreasHint"]</p>
<div class="kh-areas">
@foreach (var area in Areas)
{
<a class="kh-area" href="@area.Href.TrimStart('/')">
<span class="ico-box"><KhIcon Name="@area.Icon" /></span>
<span class="grow">@T[area.Key]</span>
@if (area.Milestone is { } milestone)
{
<span class="badge gray">@T.Format("Pages.Home.Coming", milestone)</span>
}
</a>
}
<div class="kh-home @(_customizing ? "kh-with-drawer" : null)">
<div class="phead">
<div>
<h1>@Greeting</h1>
<div class="sub">@T.Format("Pages.Home.Today", Today)</div>
</div>
<div class="grow"></div>
@if (_loaded && ShowDashboard)
{
<div class="actions">
<button type="button" class="btn @(_customizing ? "primary" : null)" aria-pressed="@(_customizing ? "true" : "false")"
@onclick="ToggleCustomize"><KhIcon Name="layout" /> @T["Dashboard.Customize"]</button>
</div>
}
</div>
</section>
<div class="callout info"><KhIcon Name="info" /> <span>@T["Pages.Home.DashboardSoon"]</span></div>
@if (!_loaded)
{
<p class="muted">@T["Dashboard.Feed.Loading"]</p>
}
else if (ShowDashboard)
{
@if (_layout.Widgets.Count == 0)
{
<div class="callout info"><KhIcon Name="info" /> <span>@T["Dashboard.Empty"]</span></div>
}
else
{
<KhWidgetGrid Layout="_layout" Editing="_customizing" LayoutChanged="ChangeLayoutAsync" Label="@T["Dashboard.Grid"]">
@foreach (var placement in _layout.Widgets)
{
if (WidgetCatalog.Find(placement.Id) is { } definition)
{
<DashboardWidget @key="placement.Id" Definition="definition" />
}
}
</KhWidgetGrid>
}
}
else
{
<div class="callout info kh-home-off">
<KhIcon Name="info" />
<span class="grow">@T["Dashboard.Off"]</span>
<button type="button" class="btn sm" @onclick="() => ChangeShowAsync(true)">@T["Dashboard.ShowAgain"]</button>
</div>
<div class="cols cols-3 kh-home-tiles">
<div class="tile acc">
<div class="t"><KhIcon Name="key" Class="sm" /> @T["Pages.Home.LicenseTile"]</div>
<div class="v">@(License.Kind == LicenseKind.Trial ? T["Pages.Home.LicenseTrial"] : T["Pages.Home.LicenseFull"])</div>
<div class="d">@LicenseDetail</div>
</div>
<div class="tile">
<div class="t"><KhIcon Name="layers" Class="sm" /> @T["Pages.Home.ModulesTile"]</div>
<div class="v">@T.Format("Pages.Home.ModulesText", License.Modules.Count, ModuleRegistry.Default.Modules.Count)</div>
<div class="d">@(License.Modules.Count == 0 ? T["Pages.Home.ModulesNone"] : string.Join(" · ", License.Modules.Order(StringComparer.Ordinal)))</div>
</div>
<div class="tile">
<div class="t"><KhIcon Name="building" Class="sm" /> @T["Pages.Home.CompanyTile"]</div>
<div class="v">@(Session.Company?.Name ?? T["Pages.Home.CompanyNone"])</div>
<div class="d">@Session.Company?.Code</div>
</div>
</div>
<section class="panel" aria-labelledby="kh-home-areas">
<div class="ph"><KhIcon Name="grid" /> <span id="kh-home-areas">@T["Pages.Home.AreasTitle"]</span></div>
<div class="pb">
<p class="muted">@T["Pages.Home.AreasHint"]</p>
<div class="kh-areas">
@foreach (var area in Areas)
{
<a class="kh-area" href="@area.Href.TrimStart('/')">
<span class="ico-box"><KhIcon Name="@area.Icon" /></span>
<span class="grow">@T[area.Key]</span>
@if (area.Milestone is { } milestone)
{
<span class="badge gray">@T.Format("Pages.Home.Coming", milestone)</span>
}
</a>
}
</div>
</div>
</section>
}
</div>
<KhDrawer Open="_customizing" Title="@T["Dashboard.CustomizeTitle"]" Icon="layout" OnClose="CloseCustomize">
<ChildContent>
<section class="kh-dsec" aria-labelledby="kh-dash-start-h">
<h3 class="fgh" id="kh-dash-start-h"><KhIcon Name="home" /> @T["Dashboard.Panel.Start"]</h3>
<div class="f">
<label for="kh-dash-start">@T["Dashboard.Panel.StartPage"]</label>
<select id="kh-dash-start" class="kh-input" value="@StartValue" @onchange="ChangeStartAsync">
<option value="@nameof(StartPage.Dashboard)">@T["Pages.Profile.Start.Dashboard"]</option>
<option value="@nameof(StartPage.LastTab)">@T["Pages.Profile.Start.LastTab"]</option>
@foreach (var item in StartChoices)
{
<option value="@item.Href">@T[item.Key]</option>
}
</select>
</div>
<KhSwitchRow Label="@T["Dashboard.Panel.Show"]" Value="Session.Preferences.ShowDashboard" ValueChanged="ChangeShowAsync" />
</section>
<section class="kh-dsec" aria-labelledby="kh-dash-widgets-h">
<h3 class="fgh" id="kh-dash-widgets-h"><KhIcon Name="grid" /> @T["Dashboard.Panel.Widgets"]</h3>
<p class="muted s">@T["Dashboard.Panel.WidgetsHint"] @SourceText</p>
<div class="kh-wpick">
@foreach (var definition in _available)
{
var on = _layout.Contains(definition.Id);
var title = T[definition.TitleKey];
<div class="kh-wpick-row @(on ? null : "off")" @key="definition.Id">
<KhSwitchRow Label="@title" Hint="@HintOf(definition)" Value="on" ValueChanged="v => ToggleAsync(definition.Id, v)" />
@if (on)
{
<div class="kh-wpick-tools">
<select class="kh-input" aria-label="@T.Format("Dashboard.Panel.Width", title)" value="@_layout.WidthOf(definition.Id)"
@onchange="e => ResizeAsync(definition.Id, e.Value as string)">
@foreach (var width in WidgetDefinition.Widths)
{
<option value="@width">@T["Dashboard.Widths." + width]</option>
}
</select>
<button type="button" class="ib" title="@T.Format("Dashboard.Panel.MoveUp", title)" aria-label="@T.Format("Dashboard.Panel.MoveUp", title)"
disabled="@(_layout.Widgets[0].Id == definition.Id)" @onclick="() => MoveAsync(definition.Id, -1)"><KhIcon Name="chevron-up" /></button>
<button type="button" class="ib" title="@T.Format("Dashboard.Panel.MoveDown", title)" aria-label="@T.Format("Dashboard.Panel.MoveDown", title)"
disabled="@(_layout.Widgets[^1].Id == definition.Id)" @onclick="() => MoveAsync(definition.Id, 1)"><KhIcon Name="chevron-down" /></button>
</div>
}
</div>
}
</div>
</section>
@if (CanSetRoleDefaults)
{
<section class="kh-dsec" aria-labelledby="kh-dash-role-h">
<h3 class="fgh" id="kh-dash-role-h"><KhIcon Name="users" /> @T["Dashboard.Panel.Role"]</h3>
<p class="muted s">@T["Dashboard.Panel.RoleHint"]</p>
@if (_roles.Count == 0)
{
<p class="muted s">@T["Dashboard.Panel.RoleNone"]</p>
}
else
{
<div class="f">
<label for="kh-dash-role">@T["Dashboard.Panel.RolePick"]</label>
<select id="kh-dash-role" class="kh-input" value="@_role" @onchange="e => _role = e.Value as string">
@foreach (var (role, layout) in _roles)
{
<option value="@role.Code">@(layout is null ? role.Name : T.Format("Dashboard.Panel.RoleHas", role.Name))</option>
}
</select>
</div>
<div class="kh-row">
<button type="button" class="btn" @onclick="SaveRoleAsync"><KhIcon Name="users" /> @T["Dashboard.Panel.RoleSave"]</button>
@if (SelectedRole is { Layout: not null })
{
<button type="button" class="btn ghost" @onclick="RemoveRoleAsync"><KhIcon Name="x" /> @T["Dashboard.Panel.RoleRemove"]</button>
}
</div>
}
</section>
}
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="ResetAsync"><KhIcon Name="refresh" /> @T["Dashboard.Panel.Reset"]</button>
<button type="button" class="btn primary" @onclick="CloseCustomize"><KhIcon Name="check" /> @T["Dashboard.Panel.Done"]</button>
</Footer>
</KhDrawer>
@code {
private DashboardLayout _layout = WidgetCatalog.BuiltIn;
private DashboardView? _view;
private IReadOnlyList<WidgetDefinition> _available = [];
private IReadOnlyList<(Role Role, DashboardLayout? Layout)> _roles = [];
private string? _role;
private bool _loaded;
private bool _customizing;
private LicenseState License => Session.Licenses.Current;
private bool ShowDashboard => Session.Preferences.ShowDashboard;
private bool CanSetRoleDefaults => Session.Company is not null && Session.Permissions.Allows(CompanySettingsService.WritePermission);
private (Role Role, DashboardLayout? Layout)? SelectedRole =>
_roles.Where(r => r.Role.Code == _role).Select(r => ((Role, DashboardLayout?)?)r).FirstOrDefault();
private IEnumerable<MenuItem> Areas =>
MenuCatalog.Sections.SelectMany(s => s.Items).Where(i => i.Href != "/" && Session.CanSee(i));
private IEnumerable<MenuItem> StartChoices => MenuCatalog.All.Where(i => i.Href != "/" && i.Milestone is null && Session.CanSee(i));
private string StartValue => Session.Preferences.StartPage switch
{
StartPage.Page when Session.Preferences.StartPath is { } path => path,
StartPage.LastTab => nameof(StartPage.LastTab),
_ => nameof(StartPage.Dashboard),
};
private string SourceText => _view?.Source switch
{
DashboardLayoutSource.User => T["Dashboard.Panel.SourceUser"],
DashboardLayoutSource.Role => T.Format("Dashboard.Panel.SourceRole", _roles.FirstOrDefault(r => r.Role.Code == _view.RoleCode).Role?.Name ?? _view.RoleCode ?? string.Empty),
_ => T["Dashboard.Panel.SourceBuiltIn"],
};
private string Today => Clock.GetLocalNow().ToString("dddd d MMMM yyyy", T.Culture);
private string Greeting
@@ -98,5 +260,109 @@
}
/// <inheritdoc />
protected override Task OnInitializedAsync() => Session.EnsureLoadedAsync();
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
if (Session.Actor is { } actor)
{
_available = await Dashboard.AvailableAsync(actor);
_view = await Dashboard.GetAsync(actor);
_layout = _view.Layout;
}
_loaded = true;
}
private string HintOf(WidgetDefinition definition) =>
definition.Milestone is { } milestone
? T[definition.DescriptionKey] + " " + T.Format("Dashboard.Panel.ComingFrom", milestone)
: T[definition.DescriptionKey];
private async Task ToggleCustomize()
{
if (_customizing)
{
CloseCustomize();
return;
}
if (CanSetRoleDefaults && Session.Company is { } company)
{
_roles = await Dashboard.RoleDefaultsAsync(company.Code);
_role ??= _roles.FirstOrDefault().Role?.Code;
}
_customizing = true;
}
private void CloseCustomize() => _customizing = false;
private async Task ChangeLayoutAsync(DashboardLayout next)
{
_layout = next;
if (Session.Actor is { } actor)
{
await Dashboard.SaveAsync(actor, next);
_view = new DashboardView(next, DashboardLayoutSource.User);
}
}
private Task ToggleAsync(string id, bool visible) => ChangeLayoutAsync(_layout.Toggle(id, visible));
private Task MoveAsync(string id, int offset) => ChangeLayoutAsync(_layout.Move(id, offset));
private Task ResizeAsync(string id, string? value) =>
int.TryParse(value, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var width)
? ChangeLayoutAsync(_layout.Resize(id, width))
: Task.CompletedTask;
private async Task ResetAsync()
{
if (Session.Actor is not { } actor)
{
return;
}
await Dashboard.ResetAsync(actor);
_view = await Dashboard.GetAsync(actor);
_layout = _view.Layout;
Toasts.Show(ToastKind.Info, T["Dashboard.Panel.ResetDone"]);
}
private async Task ChangeShowAsync(bool show)
{
await Session.SavePreferencesAsync(Session.Preferences with { ShowDashboard = show });
if (!show)
{
_customizing = false;
}
}
private async Task ChangeStartAsync(ChangeEventArgs e)
{
var value = e.Value as string;
var next = value switch
{
nameof(StartPage.LastTab) => Session.Preferences with { StartPage = StartPage.LastTab },
_ when UserPreferences.IsLocalPath(value) && value != "/" => Session.Preferences with { StartPage = StartPage.Page, StartPath = value },
_ => Session.Preferences with { StartPage = StartPage.Dashboard },
};
await Session.SavePreferencesAsync(next);
}
private async Task SaveRoleAsync() => await SetRoleDefaultAsync(_layout, "Dashboard.Panel.RoleSaved");
private async Task RemoveRoleAsync() => await SetRoleDefaultAsync(null, "Dashboard.Panel.RoleRemoved");
private async Task SetRoleDefaultAsync(DashboardLayout? layout, string doneKey)
{
if (Session.Actor is not { } actor || Session.Company is not { } company || SelectedRole is not { } selected)
{
return;
}
await Dashboard.SaveRoleDefaultAsync(actor, company.Code, selected.Role.Code, layout);
_roles = await Dashboard.RoleDefaultsAsync(company.Code);
Toasts.Show(ToastKind.Success, T.Format(doneKey, selected.Role.Name));
}
}
@@ -0,0 +1,114 @@
@* A widget of the dashboard (SPEC §10.3): a card with icon, title and actions, as wide as the KhWidgetGrid around it
says. In customize mode the header shows the drag grip and the buttons to move, resize and hide it, so all of it
works from the keyboard too. *@
<section class="widget w@(Width) @(Editing ? "editing" : null) @(_over ? "kh-over" : null)" role="listitem" aria-labelledby="@(_id + "-t")"
data-widget="@Id" data-kh-drag="@(Editing ? "true" : null)" draggable="@(Editing ? "true" : null)"
@ondragstart="StartDrag" @ondragend="EndDrag" @ondragenter="() => SetOver(true)" @ondragleave="() => SetOver(false)"
@ondragover:preventDefault="Editing" @ondrop="DropAsync">
<div class="wh">
@if (Editing)
{
<span class="drag" title="@T["Dashboard.Edit.Drag"]" aria-hidden="true"><KhIcon Name="grip" /></span>
}
else if (Icon is not null)
{
<KhIcon Name="@Icon" />
}
<span class="grow" id="@(_id + "-t")">@Title</span>
<div class="wa">
@if (Editing && Grid is not null)
{
<button type="button" class="ib" title="@T["Dashboard.Edit.Before"]" aria-label="@T["Dashboard.Edit.Before"]"
disabled="@Grid.IsAtEnd(Id, last: false)" @onclick="() => Grid.MoveAsync(Id, -1)"><KhIcon Name="chevron-left" /></button>
<button type="button" class="ib" title="@T["Dashboard.Edit.After"]" aria-label="@T["Dashboard.Edit.After"]"
disabled="@Grid.IsAtEnd(Id, last: true)" @onclick="() => Grid.MoveAsync(Id, 1)"><KhIcon Name="chevron-right" /></button>
<button type="button" class="ib" title="@T["Dashboard.Edit.Narrower"]" aria-label="@T["Dashboard.Edit.Narrower"]"
disabled="@(Width <= 3)" @onclick="() => Grid.ResizeAsync(Id, -1)"><KhIcon Name="minus" /></button>
<button type="button" class="ib" title="@T["Dashboard.Edit.Wider"]" aria-label="@T["Dashboard.Edit.Wider"]"
disabled="@(Width >= 12)" @onclick="() => Grid.ResizeAsync(Id, 1)"><KhIcon Name="plus" /></button>
<button type="button" class="ib" title="@T["Dashboard.Edit.Hide"]" aria-label="@T["Dashboard.Edit.Hide"]"
@onclick="() => Grid.HideAsync(Id)"><KhIcon Name="x" /></button>
}
else
{
@Actions
}
</div>
</div>
<div class="wb @(Tight ? "tight" : null)">
@ChildContent
</div>
</section>
@code {
private static int _next;
private readonly string _id = "kh-wdg" + Interlocked.Increment(ref _next).ToString(System.Globalization.CultureInfo.InvariantCulture);
private bool _over;
/// <summary>The grid around, which knows the width and handles the changes.</summary>
[CascadingParameter]
public KhWidgetGrid? Grid { get; set; }
/// <summary>The widget id, as in the layout.</summary>
[Parameter, EditorRequired]
public string Id { get; set; } = string.Empty;
/// <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 at the right of the title (hidden while customizing).</summary>
[Parameter]
public RenderFragment? Actions { get; set; }
/// <summary>The content.</summary>
[Parameter]
public RenderFragment? ChildContent { get; set; }
/// <summary>Content without padding (lists that run to the edges).</summary>
[Parameter]
public bool Tight { get; set; }
/// <summary>The width when there is no grid around.</summary>
[Parameter]
public int FallbackWidth { get; set; } = 4;
private int Width => Grid?.WidthOf(Id) ?? FallbackWidth;
private bool Editing => Grid?.Editing == true;
private void StartDrag()
{
if (Editing)
{
Grid!.StartDrag(Id);
}
}
private void EndDrag()
{
_over = false;
Grid?.EndDrag();
}
private void SetOver(bool over)
{
if (Editing)
{
_over = over;
}
}
private async Task DropAsync()
{
_over = false;
if (Editing)
{
await Grid!.DropOnAsync(Id);
}
}
}
@@ -0,0 +1,94 @@
@using Khaemhat.Application.Dashboard
@* The grid of the dashboard (SPEC §10.3, mockup 004/006): twelve columns, each KhWidget inside takes 3, 4, 6, 8 or 12.
In customize mode the widgets are dashed and can be dragged onto each other, moved with the arrow buttons,
narrowed, widened and hidden; every change comes out of LayoutChanged. *@
<CascadingValue Value="this" IsFixed="true">
<div class="wgrid kh-wgrid @(Editing ? "kh-editing" : null)" role="list" aria-label="@Label">
@ChildContent
</div>
</CascadingValue>
@code {
private string? _dragging;
/// <summary>The widgets in order, with their width.</summary>
[Parameter, EditorRequired]
public DashboardLayout Layout { get; set; } = WidgetCatalog.BuiltIn;
/// <summary>Whether the widgets can be moved, resized and hidden.</summary>
[Parameter]
public bool Editing { get; set; }
/// <summary>Called with the new layout after a move, resize or hide.</summary>
[Parameter]
public EventCallback<DashboardLayout> LayoutChanged { get; set; }
/// <summary>The name of the grid for screen readers.</summary>
[Parameter]
public string? Label { get; set; }
/// <summary>The KhWidget components, one per widget of the layout.</summary>
[Parameter]
public RenderFragment? ChildContent { get; set; }
/// <summary>The width of a widget, in columns of twelve.</summary>
/// <param name="id">The widget id.</param>
/// <returns>The width.</returns>
public int WidthOf(string id) => Layout.WidthOf(id);
/// <summary>Whether a widget is the first or the last.</summary>
/// <param name="id">The widget id.</param>
/// <param name="last">Ask about the last one.</param>
/// <returns><see langword="true"/> at that end.</returns>
public bool IsAtEnd(string id, bool last) =>
Layout.Widgets.Count > 0 && (last ? Layout.Widgets[^1].Id : Layout.Widgets[0].Id) == id;
/// <summary>Moves a widget by one place.</summary>
/// <param name="id">The widget id.</param>
/// <param name="offset">-1 before, +1 after.</param>
/// <returns>A task.</returns>
public Task MoveAsync(string id, int offset) => ChangeAsync(Layout.Move(id, offset));
/// <summary>Makes a widget narrower or wider by one step.</summary>
/// <param name="id">The widget id.</param>
/// <param name="step">-1 narrower, +1 wider.</param>
/// <returns>A task.</returns>
public Task ResizeAsync(string id, int step) => ChangeAsync(Layout.Resize(id, WidgetDefinition.Step(WidthOf(id), step)));
/// <summary>Hides a widget.</summary>
/// <param name="id">The widget id.</param>
/// <returns>A task.</returns>
public Task HideAsync(string id) => ChangeAsync(Layout.Toggle(id, false));
/// <summary>A widget starts being dragged.</summary>
/// <param name="id">The widget id.</param>
public void StartDrag(string id) => _dragging = id;
/// <summary>The dragged widget is dropped on another one: it takes that one's place.</summary>
/// <param name="target">The widget dropped on.</param>
/// <returns>A task.</returns>
public async Task DropOnAsync(string target)
{
var dragged = _dragging;
_dragging = null;
if (dragged is null || dragged == target)
{
return;
}
var index = Layout.Widgets.ToList().FindIndex(w => w.Id == target);
await ChangeAsync(Layout.MoveTo(dragged, index));
}
/// <summary>The drag ended without a drop.</summary>
public void EndDrag() => _dragging = null;
private async Task ChangeAsync(DashboardLayout next)
{
if (!next.SameAs(Layout))
{
await LayoutChanged.InvokeAsync(next);
}
}
}
@@ -22,4 +22,6 @@
@using Khaemhat.Web.Components.Shell
@using Khaemhat.Web.Components.Ui
@using Khaemhat.Web.Ui
@using Khaemhat.Web.Components.Dashboard
@using Khaemhat.Application.Dashboard
@inject ITexts T