From 17ed0a19a1fa5470c6de08c85566e6095366385e Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Mon, 10 Aug 2026 22:49:37 +0200 Subject: [PATCH] =?UTF-8?q?feat(web):=20navigation=20&=20layout=20responsi?= =?UTF-8?q?ve=20=E2=80=94=20drawer=20adaptatif,=20badge=20notif,=20dark=20?= =?UTF-8?q?toggle=20(Fixes=20#33)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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. --- .../Components/Layout/MainLayout.razor | 31 +++-- .../Components/Shared/NotificationBadge.razor | 30 +++++ src/Heimdall.Web/Heimdall.Web.csproj | 1 + src/Heimdall.Web/Program.cs | 1 + .../Services/NotificationsHubClient.cs | 111 ++++++++++++++++++ .../Components/Pages/PageTestBase.cs | 4 + 6 files changed, 168 insertions(+), 10 deletions(-) create mode 100644 src/Heimdall.Web/Components/Shared/NotificationBadge.razor create mode 100644 src/Heimdall.Web/Services/NotificationsHubClient.cs diff --git a/src/Heimdall.Web/Components/Layout/MainLayout.razor b/src/Heimdall.Web/Components/Layout/MainLayout.razor index bd068e5..bd8ca6d 100644 --- a/src/Heimdall.Web/Components/Layout/MainLayout.razor +++ b/src/Heimdall.Web/Components/Layout/MainLayout.razor @@ -5,7 +5,7 @@ @inject IJSRuntime JsRuntime @using Heimdall.Web.Theme - + @@ -29,8 +29,10 @@ @if (Auth.IsLoggedIn) { - + + @@ -50,7 +52,8 @@ } - + @if (Auth.IsLoggedIn) { @@ -62,6 +65,12 @@ Sites & Caméras + + Événements + + + Snapshots + @if (Auth.HasPermission("Admin.Users") || Auth.HasPermission("Admin.Manage")) { @@ -81,12 +90,6 @@ Matrice des permissions - - Événements - - - Snapshots - Journal d'audit @@ -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(); diff --git a/src/Heimdall.Web/Components/Shared/NotificationBadge.razor b/src/Heimdall.Web/Components/Shared/NotificationBadge.razor new file mode 100644 index 0000000..e907199 --- /dev/null +++ b/src/Heimdall.Web/Components/Shared/NotificationBadge.razor @@ -0,0 +1,30 @@ +@* NotificationBadge.razor — cloche avec badge compteur temps réel (SignalR). *@ +@implements IAsyncDisposable +@inject NotificationsHubClient Hub +@inject NavigationManager Navigation + + + + @if (Hub.UnreadCount > 0) + { + + } + + + +@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(); + } +} diff --git a/src/Heimdall.Web/Heimdall.Web.csproj b/src/Heimdall.Web/Heimdall.Web.csproj index 3bfb779..8409db7 100644 --- a/src/Heimdall.Web/Heimdall.Web.csproj +++ b/src/Heimdall.Web/Heimdall.Web.csproj @@ -24,6 +24,7 @@ + diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index 3d5624e..b1a31ae 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -510,6 +510,7 @@ public partial class Program { // explicit ApiBaseUrl (config/env) overrides that for external APIs. builder.Services.AddHttpContextAccessor(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddTransient(); builder.Services.AddTransient(); var apiBaseUrlConfigured = ApiBaseUrlResolver.IsConfigured(builder.Configuration); diff --git a/src/Heimdall.Web/Services/NotificationsHubClient.cs b/src/Heimdall.Web/Services/NotificationsHubClient.cs new file mode 100644 index 0000000..fef44e2 --- /dev/null +++ b/src/Heimdall.Web/Services/NotificationsHubClient.cs @@ -0,0 +1,111 @@ +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.SignalR.Client; + +namespace Heimdall.Web.Services; + +/// +/// Client hub SignalR pour les notifications temps réel (badge compteur). +/// S'abonne au groupe personnel "notif_{userId}" et expose l'événement +/// . 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. +/// +public class NotificationsHubClient : IAsyncDisposable, IDisposable +{ + private readonly AuthState _authState; + private readonly NavigationManager _navigation; + private readonly ILogger _logger; + private HubConnection? _connection; + private bool _started; + + public NotificationsHubClient( + AuthState authState, + NavigationManager navigation, + ILogger logger) + { + _authState = authState; + _navigation = navigation; + _logger = logger; + } + + /// Compteur de notifications non lues (mis à jour par le hub). + public int UnreadCount { get; private set; } + + public event Action? 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("UnreadCount", (payload) => + { + try + { + var count = (int)((IDictionary)payload)["count"]; + UnreadCount = count; + UnreadCountChanged?.Invoke(count); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "NotificationsHubClient: UnreadCount payload inattendu"); + } + }); + + _connection.On("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 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; + } +} diff --git a/tests/Heimdall.Web.Tests/Components/Pages/PageTestBase.cs b/tests/Heimdall.Web.Tests/Components/Pages/PageTestBase.cs index 4af4147..2a75b93 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/PageTestBase.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/PageTestBase.cs @@ -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(), + Substitute.For>())); } /// Logs the shared AuthState in as the given role.