feat(web): navigation & layout responsive — drawer adaptatif, badge notif, dark toggle (Fixes #33)

- Drawer : Breakpoint.Sm + mini-variant (64px) — responsive mobile/desktop.
- Nav restructurée : Événements et Snapshots SORTIS de la section
  Administration (bug d'accès : masqués aux non-admin alors que les pages
  sont autorisées) — section Navigation pour tous les connectés.
- Badge notifications temps réel : NotificationsHubClient (SignalR,
  access_token JWT, reconnexion auto, fallback silencieux) +
  NotificationBadge dans l'AppBar (compteur non lues, clic → /events).
- Toggle clair/sombre dans l'AppBar (IsDarkMode du MudThemeProvider).
- PageTestBase : enregistre NotificationsHubClient pour les tests bUnit.
172 tests Web verts.
This commit is contained in:
Arnaud Dartois committed 2026-08-10 22:49:37 +02:00
1 parent 319060a997
commit 17ed0a19a1
6 files changed
+168 -10

No files matched your search

@@ -5,7 +5,7 @@
@inject IJSRuntime JsRuntime
@using Heimdall.Web.Theme
<MudThemeProvider Theme="@HeimdallTheme.Instance" />
<MudThemeProvider Theme="@HeimdallTheme.Instance" IsDarkMode="_darkMode" />
<MudPopoverProvider />
<MudDialogProvider />
<MudSnackbarProvider />
@@ -29,8 +29,10 @@
<MudSpacer />
@if (Auth.IsLoggedIn)
{
<MudIconButton Icon="@Icons.Material.Filled.Notifications" Color="Color.Inherit" aria-label="Notifications"
OnClick="@(() => Navigation.NavigateTo("/events"))" />
<MudIconButton Icon="@(_darkMode ? Icons.Material.Filled.LightMode : Icons.Material.Filled.DarkMode)"
Color="Color.Inherit" aria-label="Basculer le thème"
OnClick="@ToggleDarkMode" />
<NotificationBadge />
<MudMenu AnchorOrigin="Origin.BottomRight">
<ActivatorContent>
<MudIconButton Icon="@Icons.Material.Filled.AccountCircle" Color="Color.Inherit" aria-label="Profil" OnClick="@context.ToggleAsync" />
@@ -50,7 +52,8 @@
}
</MudAppBar>
<MudDrawer @bind-Open="_drawerOpen" Variant="DrawerVariant.Responsive" ClipMode="DrawerClipMode.Never">
<MudDrawer @bind-Open="_drawerOpen" Variant="DrawerVariant.Responsive" ClipMode="DrawerClipMode.Never"
Breakpoint="Breakpoint.Sm" MiniVariantWidth="64px" @bind-MiniVariant="_miniVariant">
<MudNavMenu>
@if (Auth.IsLoggedIn)
{
@@ -62,6 +65,12 @@
<MudNavLink Href="/sites" Match="NavLinkMatch.Prefix" Icon="@Icons.Material.Filled.Videocam">
Sites &amp; Caméras
</MudNavLink>
<MudNavLink Href="/events" Match="NavLinkMatch.Prefix" Icon="@Icons.Material.Filled.Notifications">
Événements
</MudNavLink>
<MudNavLink Href="/snapshots" Match="NavLinkMatch.Prefix" Icon="@Icons.Material.Filled.PhotoLibrary">
Snapshots
</MudNavLink>
@if (Auth.HasPermission("Admin.Users") || Auth.HasPermission("Admin.Manage"))
{
@@ -81,12 +90,6 @@
<MudNavLink Href="/admin/claims" Match="NavLinkMatch.Prefix" Icon="@Icons.Material.Filled.Policy">
Matrice des permissions
</MudNavLink>
<MudNavLink Href="/events" Match="NavLinkMatch.Prefix" Icon="@Icons.Material.Filled.Notifications">
Événements
</MudNavLink>
<MudNavLink Href="/snapshots" Match="NavLinkMatch.Prefix" Icon="@Icons.Material.Filled.PhotoLibrary">
Snapshots
</MudNavLink>
<MudNavLink Href="/audit-logs" Match="NavLinkMatch.Prefix" Icon="@Icons.Material.Filled.History">
Journal d'audit
</MudNavLink>
@@ -115,8 +118,16 @@
@code {
private bool _drawerOpen = true;
private bool _miniVariant;
private bool _darkMode = true;
private string _searchQuery = "";
private void ToggleDarkMode()
{
_darkMode = !_darkMode;
StateHasChanged();
}
private async Task Logout()
{
await AuthStateProvider.NotifyLogoutAsync();
@@ -0,0 +1,30 @@
@* NotificationBadge.razor — cloche avec badge compteur temps réel (SignalR). *@
@implements IAsyncDisposable
@inject NotificationsHubClient Hub
@inject NavigationManager Navigation
<MudTooltip Text="Notifications">
<MudIconButton Icon="@Icons.Material.Filled.Notifications" Color="Color.Inherit" aria-label="Notifications"
OnClick="@(() => Navigation.NavigateTo("/events"))">
@if (Hub.UnreadCount > 0)
{
<MudBadge Color="Color.Error" Overlap="true" Bordered="true" Content="@Hub.UnreadCount" />
}
</MudIconButton>
</MudTooltip>
@code {
protected override async Task OnInitializedAsync()
{
Hub.UnreadCountChanged += OnUnreadChanged;
await Hub.StartAsync();
}
private void OnUnreadChanged(int _) => InvokeAsync(StateHasChanged);
public async ValueTask DisposeAsync()
{
Hub.UnreadCountChanged -= OnUnreadChanged;
await Hub.DisposeAsync();
}
}
+1
View File
@@ -24,6 +24,7 @@
<PackageReference Include="Hangfire.PostgreSql" Version="1.20.10" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.8" />
<PackageReference Include="MudBlazor" Version="9.8.0" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="10.0.8" />
<PackageReference Include="Sentry.AspNetCore" Version="6.8.0" />
</ItemGroup>
+1
View File
@@ -510,6 +510,7 @@ public partial class Program {
// explicit ApiBaseUrl (config/env) overrides that for external APIs.
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<HeimdallApiClient>();
builder.Services.AddScoped<NotificationsHubClient>();
builder.Services.AddTransient<TokenRefreshHandler>();
builder.Services.AddTransient<SameOriginHttpMessageHandler>();
var apiBaseUrlConfigured = ApiBaseUrlResolver.IsConfigured(builder.Configuration);
@@ -0,0 +1,111 @@
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.SignalR.Client;
namespace Heimdall.Web.Services;
/// <summary>
/// Client hub SignalR pour les notifications temps réel (badge compteur).
/// S'abonne au groupe personnel "notif_{userId}" et expose l'événement
/// <see cref="UnreadCountChanged"/>. Le polling est le fallback : si la
/// connexion échoue (pas de JWT en session cookie, hub indisponible), le
/// badge reste silencieux sans casser l'UI.
/// </summary>
public class NotificationsHubClient : IAsyncDisposable, IDisposable
{
private readonly AuthState _authState;
private readonly NavigationManager _navigation;
private readonly ILogger<NotificationsHubClient> _logger;
private HubConnection? _connection;
private bool _started;
public NotificationsHubClient(
AuthState authState,
NavigationManager navigation,
ILogger<NotificationsHubClient> logger)
{
_authState = authState;
_navigation = navigation;
_logger = logger;
}
/// <summary>Compteur de notifications non lues (mis à jour par le hub).</summary>
public int UnreadCount { get; private set; }
public event Action<int>? UnreadCountChanged;
public async Task StartAsync()
{
if (_started || !_authState.IsLoggedIn)
return;
try
{
var accessToken = _authState.AccessToken;
if (string.IsNullOrEmpty(accessToken))
return; // session cookie (SSR/reload) : pas de JWT → pas de hub, fallback silencieux
_connection = new HubConnectionBuilder()
.WithUrl($"{_navigation.BaseUri}hubs/notifications", options =>
{
options.AccessTokenProvider = GetAccessTokenAsync;
})
.WithAutomaticReconnect()
.Build();
_connection.On<object>("UnreadCount", (payload) =>
{
try
{
var count = (int)((IDictionary<string, object>)payload)["count"];
UnreadCount = count;
UnreadCountChanged?.Invoke(count);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "NotificationsHubClient: UnreadCount payload inattendu");
}
});
_connection.On<object>("NewNotification", (_) =>
{
UnreadCount++;
UnreadCountChanged?.Invoke(UnreadCount);
});
await _connection.StartAsync();
await _connection.InvokeAsync("JoinPersonalNotifications");
_started = true;
_logger.LogDebug("NotificationsHubClient connecté");
}
catch (Exception ex)
{
_logger.LogWarning(ex, "NotificationsHubClient: connexion impossible — fallback polling");
}
}
private Task<string?> GetAccessTokenAsync() => Task.FromResult(_authState.AccessToken);
public void Dispose()
{
// Dispose synchrone (requis par certains conteneurs / bUnit) :
// déconnexion best-effort sans attendre la fermeture réseau.
if (_connection is not null)
{
try
{
_connection.StopAsync(CancellationToken.None).Wait(TimeSpan.FromMilliseconds(500));
_connection.DisposeAsync().AsTask().GetAwaiter().GetResult();
}
catch { /* best effort */ }
}
_started = false;
GC.SuppressFinalize(this);
}
public async ValueTask DisposeAsync()
{
Dispose();
GC.SuppressFinalize(this);
await Task.CompletedTask;
}
}
@@ -57,6 +57,10 @@ public abstract class PageTestBase : MudTestBase
Services.AddScoped(_ => AuthState);
Services.AddScoped(_ => Api);
Services.AddScoped(_ => AuthProvider);
Services.AddScoped(sp => new NotificationsHubClient(
AuthState,
Services.GetRequiredService<NavigationManager>(),
Substitute.For<Microsoft.Extensions.Logging.ILogger<NotificationsHubClient>>()));
}
/// <summary>Logs the shared AuthState in as the given role.</summary>