diff --git a/README.md b/README.md index 1a11cc92..ab45aef0 100644 --- a/README.md +++ b/README.md @@ -105,7 +105,7 @@ Rules: [Hosting and configuration](docs/areas/hosting.md). | `ConnectionStrings:DockerUpdateGuard` | none | Yes* | Named PostgreSQL connection string used when `DockerUpdateGuard:ConnectionString` is not set | | `DockerUpdateGuard:ConnectionString` | none | Yes* | Inline PostgreSQL connection string | | `DockerUpdateGuard:ConnectionStringName` | `DockerUpdateGuard` | No | Name of the `ConnectionStrings` entry to resolve | -| `DockerUpdateGuard:DisplayVersion` | assembly version | No | Version string shown in the navigation drawer; the Docker image sets this automatically | +| `DockerUpdateGuard:DisplayVersion` | assembly version | No | Version string shown at the end of every page and in the narrow-screen drawer; the Docker image sets this automatically | | `DockerUpdateGuard:Database:MaxConnectionRetryCount` | `8` | No | Retries of a transiently failing database command during normal operation | | `DockerUpdateGuard:Database:MaxConnectionRetryDelaySeconds` | `30` | No | Maximum back-off in seconds between those retries | | `DockerUpdateGuard:Database:MigrationStartupTimeoutSeconds` | `120` | No | How long startup waits for the database to become reachable | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index cfc25ef5..e5e771af 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -417,6 +417,13 @@ Pages, routes and what each page shows or triggers are specified in to `none` ([decision 0078](decisions/0078-mudblazor-elevation-shadows-are-switched-off-in-the-theme.md)). +- **Layout** (`Components\Layout`): `MainLayout` owns the sticky header, the + temporary drawer and the navigation state (the optional entries and the + display version, evaluated once per page load and persisted for the + interactive render); `NavMenu` renders that state as the header row and as + the drawer list. CSS shows the row from 1360 px and a drawer below it, and + the layout closes an open drawer when the window reaches 1360 px + ([decision 0081](decisions/0081-the-navigation-row-shows-from-1360-px-and-a-drawer-below.md)). - **Pages** (`Components\Pages`) have one `@page` route each. - **`IApplicationViewService` (`UI\ApplicationViewService`)** is the single facade every page depends on. It maps `DockerUpdateGuard.Data` entities diff --git a/docs/areas/web-ui.md b/docs/areas/web-ui.md index 36a3c91c..7cd7a14b 100644 --- a/docs/areas/web-ui.md +++ b/docs/areas/web-ui.md @@ -15,25 +15,25 @@ to read the state the other areas compute and to start manual scans; it computes connection. Data loaded for the first render is reused when the page becomes interactive, not loaded twice. - There is no sign-in. Everyone who can reach the application can see every page and start every action ([Hosting and configuration](hosting.md) owns the security posture). -- All pages share one layout: a navigation drawer, a top bar and the page content. The drawer collapses into a menu - button on narrow screens. -- The top bar shows the product name, the dark-mode toggle, the number of *protected assets* (manual observed images - plus own images plus runtime containers) and *last activity* (the start time of the most recent scan run, or "No - scans yet"). The top bar reloads these values on every navigation and on every dashboard refresh signal (see - *Refresh without reload*). When its first load fails the top bar shows neither the values nor a placeholder; when - a reload fails it keeps the last values. -- The navigation lists Dashboard, My Images, Observed Images, Runtime Containers, Docker Instances, Shared Base - Images, Vulnerabilities and Scan History. *My Images* is listed only when both `DockerUpdateGuard:DockerHub:UserName` - and `DockerUpdateGuard:DockerHub:Pat` are set; *Shared Base Images* only when at least one shared base image exists. Both - conditions are evaluated when the session starts. The pages stay reachable by their routes either way. When the - check for shared base images fails, *Shared Base Images* is hidden. +- All pages share one layout: a sticky header (the shield mark and product name as a link to the Dashboard, the + navigation and the dark-mode toggle) above the page content, which is at most 1280 px wide plus 32 px side padding + (16 px below 960 px, 12 px below 600 px). From a window width of 1360 px the navigation is a row in the header; below + it the row gives way to a menu button that opens a drawer over the content, closed whenever a page loads, closed again + by an entry, Escape, a click outside or a window widened to 1360 px + ([decision 0081](../decisions/0081-the-navigation-row-shows-from-1360-px-and-a-drawer-below.md)). +- The navigation lists Dashboard, My Images, Observed Images, Runtime Containers, Docker Instances, Base Images, + Vulnerabilities and Scan History, the same in the row and in the drawer; the entry of the open page (a list page, a + page below it, or either with a query string) is marked as the current page. *My Images* is listed only when both + `DockerUpdateGuard:DockerHub:UserName` and `DockerUpdateGuard:DockerHub:Pat` are set; *Base Images* only when at least + one shared base image exists. Both conditions are evaluated once per page load. The pages stay reachable by their + routes either way. When the check for shared base images fails, *Base Images* is hidden. - When the first load of the Dashboard, My Images, Observed Images, Runtime Containers, Docker Instances, Shared Base Images, Vulnerabilities or Scan History page fails, the page shows an error alert in place of its loading skeleton (on Observed Images inside the *Manual images* section, the registration form stays usable) until a later load succeeds. A page whose load needs two answers (Docker Instances, Scan History) shows no part of its data when either fails. A reload that fails after a successful load keeps what is shown. -- The drawer shows the application version: `DockerUpdateGuard:DisplayVersion` when set, otherwise the version of the - running build, otherwise "unknown". +- The version line `DockerUpdateGuard ` ends every page and the drawer: `DockerUpdateGuard:DisplayVersion` + when set, otherwise the version of the running build, otherwise "unknown". - Timestamps are shown in UTC as `yyyy-MM-dd HH:mm UTC`, the same for every browser and independent of the time zone and culture of the server process. The resource chart labels are UTC too: the first and the last label read `MM-dd HH:mm UTC`, the visible labels between them `HH:mm`. @@ -167,10 +167,10 @@ to read the state the other areas compute and to start manual scans; it computes ### Refresh without reload -- After a manual scan, registration or rescan finishes, every open dashboard and every open top bar in every browser +- After a manual scan, registration or rescan finishes, every open dashboard in every browser session connected to the same application process reloads its data without a page reload. - Scheduled background runs do not send this signal: their results become visible when a page is opened or - navigated to again (the top bar also refreshes on every navigation). No page polls the server. + navigated to again. No page polls the server. ### Dashboard @@ -229,7 +229,7 @@ never their values. ### Light and dark mode -- The UI has a light and a dark theme, switched with the toggle in the top bar. +- The UI has a light and a dark theme, switched with the toggle in the header. - The choice is remembered per browser in encrypted browser storage. Without a stored choice the theme follows the operating system's color-scheme preference, determined after the first render; the server-rendered first paint is always light. @@ -289,8 +289,8 @@ never their values. - A failed first load of a list page or the dashboard shows one error alert `: ` with the fixed reason in place of the skeleton, no empty-state note and no rows, and is logged like a user action (event ID - 4000). A failed reload after a successful load is logged and shows nothing. The layout's loads are logged the same - way and show no text: `LoadDashboardSummary` (top bar) and `LoadNavigation` (the *Shared Base Images* entry). + 4000). A failed reload after a successful load is logged and shows nothing. The layout's load is logged the same + way and shows no text: `LoadNavigation` (the *Base Images* entry). | Page load | Prefix | Logged action | | --- | --- | --- | diff --git a/docs/decisions/0081-the-navigation-row-shows-from-1360-px-and-a-drawer-below.md b/docs/decisions/0081-the-navigation-row-shows-from-1360-px-and-a-drawer-below.md new file mode 100644 index 00000000..10de5b72 --- /dev/null +++ b/docs/decisions/0081-the-navigation-row-shows-from-1360-px-and-a-drawer-below.md @@ -0,0 +1,38 @@ +# 0081: The navigation row shows from 1360 px, and a drawer below + +- **Status:** Accepted +- **Date:** 2026-11-29 +- **Area:** Web UI +- **Source:** Issue #454 +- **Supersedes:** — + +## Context + +The flat refresh (#450) replaces the navigation drawer by a row of links in a 60 px header. The issue asked for the +row from 1280 px on, with 10 px link padding and the mockup's 28 px gaps, inside a header whose content is at most +1280 px wide plus 32 px side padding. Measured on the mockup in Chrome with the shipped Inter, the eight entries do not +fit one row at a 1280 px viewport (the header grows to two rows, 121 px), and fit at 1360 px with about 30 px to spare. +1360 px is no MudBlazor breakpoint (`Lg` is 1280, `Xl` 1920), so MudBlazor's responsive drawer cannot switch there. + +## Options considered + +1. **Row from 1360 px, drawer below, every value of the issue kept (chosen, by the Product Manager)** — the look of + the mockup is kept; between 1280 and 1359 px a desktop window shows the menu button instead of the row. +2. **Row from 1280 px with 8 px link padding and 16 px header gaps** — fits, but with about 7 px to spare under a + classic 15 px scrollbar, so a longer label or another font metric wraps the header again. +3. **Row from 1280 px with the issue's values, allowed to wrap** — the header doubles its height on common laptop + widths and the sticky header covers twice as much content. +4. **MudBlazor's responsive drawer at `Lg` (1280 px)** — no own breakpoint code, but switches at the width where the + row does not fit (option 3). + +## Decision + +The layout shows the navigation row from a 1360 px viewport width on and the menu button with a temporary drawer +below it; the switch is one pair of media queries in `app.css`, and the layout closes an open drawer when the window +reaches 1360 px. The values are in [Web UI](../areas/web-ui.md#general). + +## Consequences + +The breakpoint is the project's own: a ninth entry or a longer label needs a new measurement and possibly a new +width. The drawer state needs a viewport subscription (MudBlazor's `IBrowserViewportService`) instead of the drawer's +own breakpoint. \ No newline at end of file diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 1bd4daf7..1cbd1154 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -146,4 +146,5 @@ once in the [area document](../areas/README.md) of the record's area, and the re | [0078](0078-mudblazor-elevation-shadows-are-switched-off-in-the-theme.md) | MudBlazor elevation shadows are switched off in the theme | Accepted | 2026-11-28 | | [0079](0079-statuses-map-to-tones-in-one-mapping-beside-the-chip-colors-of-unconverted-pages.md) | Statuses map to tones in one mapping, beside the chip colors of unconverted pages | Accepted | 2026-11-28 | | [0080](0080-the-dashboard-counts-the-containers-advisories-and-own-images-it-lists.md) | The dashboard counts the containers, advisories and own images it lists | Accepted | 2026-11-29 | +| [0081](0081-the-navigation-row-shows-from-1360-px-and-a-drawer-below.md) | The navigation row shows from 1360 px, and a drawer below | Accepted | 2026-11-29 | diff --git a/docs/ui-concept/flat-refresh/README.md b/docs/ui-concept/flat-refresh/README.md index 422ee071..ab1ae101 100644 --- a/docs/ui-concept/flat-refresh/README.md +++ b/docs/ui-concept/flat-refresh/README.md @@ -170,7 +170,7 @@ The summary cards become one *Details* column; status and available update sit n ## What the mockups do not show -- **Narrow screens.** The mockups are drawn for the desktop. Below 1280 px the navigation collapses into a menu +- **Narrow screens.** The mockups are drawn for the desktop. Below 1360 px the navigation collapses into a menu button that opens a drawer, and below 960 px table rows keep the card layout of the responsive redesign, in the flat style. - **The detail pages** of My Images, Observed Images and Docker Instances, and the error and not-found pages. They diff --git a/src/DockerUpdateGuard/Components/Layout/MainLayout.razor b/src/DockerUpdateGuard/Components/Layout/MainLayout.razor index 0bc1171a..c0be0f32 100644 --- a/src/DockerUpdateGuard/Components/Layout/MainLayout.razor +++ b/src/DockerUpdateGuard/Components/Layout/MainLayout.razor @@ -5,86 +5,49 @@ - - - - - - +
+ +
+
+ + + + + + + DockerUpdateGuard + - - -
-
- - - DockerUpdateGuard -
+ +
+
- @if (_dashboardSummary is null) - { - @if (_summaryLoadFailed == false) - { - - } - } - else - { -
- - Protected assets - @GetProtectedAssetCount() - - - Last activity - @GetLatestScanLabel() - -
+ + -
- - - @GetProtectedAssetCount() - - -
-
- Protected assets - @GetProtectedAssetCount() -
-
- Last activity - @GetLatestScanLabel() -
-
-
-
-
- } -
- +

DockerUpdateGuard @_navigation.DisplayVersion

+ - +
@Body - - - + +

DockerUpdateGuard @_navigation.DisplayVersion

+
+
+ diff --git a/src/DockerUpdateGuard/Components/Layout/MainLayout.razor.cs b/src/DockerUpdateGuard/Components/Layout/MainLayout.razor.cs index 07c3da7d..e95e156c 100644 --- a/src/DockerUpdateGuard/Components/Layout/MainLayout.razor.cs +++ b/src/DockerUpdateGuard/Components/Layout/MainLayout.razor.cs @@ -1,26 +1,36 @@ +using System.Reflection; using System.Security.Cryptography; +using DockerUpdateGuard.Configuration; using DockerUpdateGuard.UI; using Microsoft.AspNetCore.Components; -using Microsoft.AspNetCore.Components.Routing; using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage; +using Microsoft.AspNetCore.Components.Web; +using Microsoft.Extensions.Options; +using Microsoft.JSInterop; using MudBlazor; +using MudBlazor.Services; namespace DockerUpdateGuard.Components.Layout; /// /// Main application layout /// -public sealed partial class MainLayout : LayoutComponentBase, IDisposable +public sealed partial class MainLayout : LayoutComponentBase, IAsyncDisposable { #region Constants /// - /// Persistent-state key for the prerendered dashboard summary + /// Persistent-state key for the prerendered navigation state /// - private const string DashboardSummaryStateKey = "MainLayout.DashboardSummary"; + private const string NavigationStateKey = "MainLayout.Navigation"; + + /// + /// Window width in pixels from which the navigation row replaces the drawer + /// + private const int WideLayoutMinWidth = 1360; /// /// Browser-storage key for the persisted dark-mode preference @@ -158,24 +168,34 @@ public sealed partial class MainLayout : LayoutComponentBase, IDisposable }; /// - /// Persisting-state subscription used to hand the prerendered summary to the interactive render + /// Identifier under which the layout observes the browser viewport /// - private PersistingComponentStateSubscription _persistingSubscription; + private readonly Guid _viewportObserverId = Guid.NewGuid(); + + /// + /// Navigation state + /// + private NavigationViewData _navigation = new(); + + /// + /// Whether the navigation state was loaded or restored, so it may be persisted + /// + private bool _navigationLoaded; /// - /// Dashboard summary + /// Subscription that persists the navigation state for the interactive render /// - private DashboardSummaryViewData? _dashboardSummary; + private PersistingComponentStateSubscription _persistingSubscription; /// - /// Whether the last load of the dashboard summary failed + /// Whether the layout observes the browser viewport /// - private bool _summaryLoadFailed; + private bool _viewportSubscribed; /// - /// Navigation-drawer state + /// Navigation-drawer state, closed when a page loads /// - private bool _drawerOpen = true; + private bool _drawerOpen; /// /// Dark-mode state @@ -198,110 +218,212 @@ public sealed partial class MainLayout : LayoutComponentBase, IDisposable public IApplicationViewService ViewService { get; set; } = null!; /// - /// Navigation manager + /// Persistent component state used to reuse the prerendered navigation state on the interactive render /// [Inject] - public NavigationManager NavigationManager { get; set; } = null!; + public PersistentComponentState PersistentState { get; set; } = null!; /// - /// Dashboard refresh state + /// Protected browser local storage used to persist the dark-mode preference /// [Inject] - public DashboardRefreshState DashboardRefreshState { get; set; } = null!; + public ProtectedLocalStorage BrowserStorage { get; set; } = null!; /// - /// Persistent component state used to reuse the prerendered summary on the interactive render + /// Logger /// [Inject] - public PersistentComponentState PersistentState { get; set; } = null!; + public ILogger Logger { get; set; } = null!; /// - /// Protected browser local storage used to persist the dark-mode preference + /// Application configuration /// [Inject] - public ProtectedLocalStorage BrowserStorage { get; set; } = null!; + public IConfiguration Configuration { get; set; } = null!; /// - /// Logger + /// Application options /// [Inject] - public ILogger Logger { get; set; } = null!; + public IOptions AppOptions { get; set; } = null!; + + /// + /// Browser viewport service used to close the drawer when the window widens + /// + [Inject] + public IBrowserViewportService BrowserViewportService { get; set; } = null!; #endregion // Properties + #region Static methods + + /// + /// Determine whether Docker Hub account discovery is configured for the given options + /// + /// Docker Hub options to evaluate + /// True when both UserName and Pat are non-empty + private static bool IsDockerHubAccountConfigured(DockerHubOptions dockerHub) + { + return string.IsNullOrWhiteSpace(dockerHub.UserName) == false + && string.IsNullOrWhiteSpace(dockerHub.Pat) == false; + } + + #endregion // Static methods + #region Methods /// - /// Load the current dashboard summary + /// Determine whether Docker Hub account discovery is configured /// - /// Task - private async Task LoadSummaryAsync() + /// True when both UserName and Pat are non-empty + private bool IsDockerHubAccountConfigured() { - var dashboardSummary = await ViewService.GetDashboardSummaryAsync() - .ConfigureAwait(false); + return IsDockerHubAccountConfigured(AppOptions.Value.DockerHub); + } - await InvokeAsync(() => - { - _dashboardSummary = dashboardSummary; + /// + /// Resolve the version to display + /// + /// Display version + private string ResolveDisplayVersion() + { + var configuredVersion = Configuration["DockerUpdateGuard:DisplayVersion"]; - StateHasChanged(); - }).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(configuredVersion) == false) + { + return configuredVersion; + } + + var environmentVersion = Environment.GetEnvironmentVariable("DockerUpdateGuard__DisplayVersion"); + + if (string.IsNullOrWhiteSpace(environmentVersion) == false) + { + return environmentVersion; + } + + var entryAssembly = Assembly.GetEntryAssembly() ?? typeof(MainLayout).Assembly; + var informationalVersion = entryAssembly.GetCustomAttribute()?.InformationalVersion; + + if (string.IsNullOrWhiteSpace(informationalVersion) == false) + { + return informationalVersion; + } + + var fileVersion = entryAssembly.GetCustomAttribute()?.Version; + + if (string.IsNullOrWhiteSpace(fileVersion) == false) + { + return fileVersion; + } + + var assemblyVersion = entryAssembly.GetName().Version; + + if (assemblyVersion is not null) + { + return assemblyVersion.ToString(3); + } + + return "unknown"; } /// - /// Load the current dashboard summary and keep whether the load failed + /// Build the navigation state: the entries that depend on the configuration and the shared base images, and the version /// /// Task - private async Task LoadSummaryOrReportAsync() + private async Task LoadNavigationAsync() { - var loadErrorMessage = await PageLoader.LoadAsync(LoadSummaryAsync, Logger, "LoadDashboardSummary", "Loading the summary failed").ConfigureAwait(false); + var showBaseImages = false; + var showMyImages = IsDockerHubAccountConfigured(); + var displayVersion = ResolveDisplayVersion(); + + _ = await PageLoader.LoadAsync(async () => showBaseImages = await ViewService.HasBaseImagesAsync().ConfigureAwait(false), Logger, "LoadNavigation", "Loading the navigation failed").ConfigureAwait(false); await InvokeAsync(() => { - _summaryLoadFailed = loadErrorMessage is not null; - - StateHasChanged(); + _navigation = new NavigationViewData + { + ShowMyImages = showMyImages, + ShowBaseImages = showBaseImages, + DisplayVersion = displayVersion, + }; + _navigationLoaded = true; }).ConfigureAwait(false); } /// - /// React to application navigation changes + /// Persist the navigation state so the interactive render can reuse the prerendered one + /// + /// Task + private Task PersistNavigation() + { + if (_navigationLoaded) + { + PersistentState.PersistAsJson(NavigationStateKey, _navigation); + } + + return Task.CompletedTask; + } + + /// + /// Toggle the navigation drawer state /// - /// Event sender - /// Navigation event arguments - private void OnLocationChanged(object? sender, LocationChangedEventArgs args) + private void ToggleDrawer() { - _ = InvokeAsync(LoadSummaryOrReportAsync); + _drawerOpen = _drawerOpen == false; } /// - /// React to explicit dashboard refresh notifications + /// Close the navigation drawer /// - private void OnDashboardRefreshRequested() + private void CloseDrawer() { - _ = InvokeAsync(LoadSummaryOrReportAsync); + _drawerOpen = false; } /// - /// Persist the current dashboard summary so the interactive render can reuse the prerendered data + /// Get the attributes of the layout wrapper: the key-down handler that closes the drawer on Escape, only while the drawer is open /// - /// Task - private Task PersistSummary() + /// Attributes of the wrapper + private Dictionary GetShellAttributes() { - if (_dashboardSummary is not null) + var attributes = new Dictionary(); + + if (_drawerOpen) { - PersistentState.PersistAsJson(DashboardSummaryStateKey, _dashboardSummary); + attributes["onkeydown"] = EventCallback.Factory.Create(this, OnShellKeyDown); } - return Task.CompletedTask; + return attributes; } /// - /// Toggle the navigation drawer state + /// Close the open drawer on Escape /// - private void ToggleDrawer() + /// Key-down event arguments + private void OnShellKeyDown(KeyboardEventArgs args) { - _drawerOpen = _drawerOpen == false; + if (args.Key == "Escape") + { + CloseDrawer(); + } + } + + /// + /// Close the open drawer when the window reaches the width of the navigation row + /// + /// Viewport event arguments + private void OnViewportChanged(BrowserViewportEventArgs args) + { + if (args.BrowserWindowSize.Width < WideLayoutMinWidth) + { + return; + } + + _ = InvokeAsync(() => + { + CloseDrawer(); + StateHasChanged(); + }); } /// @@ -361,34 +483,6 @@ await BrowserStorage.SetAsync(DarkModeStorageKey, isDarkMode) } } - /// - /// Get the protected asset count - /// - /// Protected asset count - private int GetProtectedAssetCount() - { - if (_dashboardSummary is null) - { - return 0; - } - - return _dashboardSummary.ObservedImageCount + _dashboardSummary.MyImageCount + _dashboardSummary.RuntimeContainerCount; - } - - /// - /// Get the label for the most recent scan - /// - /// Formatted scan label - private string GetLatestScanLabel() - { - if (_dashboardSummary is null || _dashboardSummary.LatestScan is null) - { - return "No scans yet"; - } - - return TimestampFormatter.Format(_dashboardSummary.LatestScan.StartedAtUtc); - } - #endregion // Methods #region ComponentBase @@ -396,19 +490,18 @@ private string GetLatestScanLabel() /// protected override async Task OnInitializedAsync() { - NavigationManager.LocationChanged += OnLocationChanged; - DashboardRefreshState.Changed += OnDashboardRefreshRequested; - _persistingSubscription = PersistentState.RegisterOnPersisting(PersistSummary); + _persistingSubscription = PersistentState.RegisterOnPersisting(PersistNavigation); - if (PersistentState.TryTakeFromJson(DashboardSummaryStateKey, out var restoredSummary) - && restoredSummary is not null) + if (PersistentState.TryTakeFromJson(NavigationStateKey, out var restoredNavigation) + && restoredNavigation is not null) { - _dashboardSummary = restoredSummary; + _navigation = restoredNavigation; + _navigationLoaded = true; return; } - await LoadSummaryOrReportAsync().ConfigureAwait(false); + await LoadNavigationAsync().ConfigureAwait(false); } /// @@ -428,19 +521,43 @@ await InvokeAsync(() => StateHasChanged(); }).ConfigureAwait(false); + + await BrowserViewportService.SubscribeAsync(_viewportObserverId, + OnViewportChanged, + new ResizeOptions + { + NotifyOnBreakpointOnly = false + }, + false).ConfigureAwait(false); + + _viewportSubscribed = true; } #endregion // ComponentBase - #region IDisposable + #region IAsyncDisposable /// - public void Dispose() + public async ValueTask DisposeAsync() { - NavigationManager.LocationChanged -= OnLocationChanged; - DashboardRefreshState.Changed -= OnDashboardRefreshRequested; _persistingSubscription.Dispose(); + + if (_viewportSubscribed == false) + { + return; + } + + _viewportSubscribed = false; + + try + { + await BrowserViewportService.UnsubscribeAsync(_viewportObserverId).ConfigureAwait(false); + } + catch (JSDisconnectedException) + { + // The circuit is gone, so the browser no longer observes the viewport. + } } - #endregion // IDisposable + #endregion // IAsyncDisposable } \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Layout/NavMenu.razor b/src/DockerUpdateGuard/Components/Layout/NavMenu.razor index 12e65d18..113a6a86 100644 --- a/src/DockerUpdateGuard/Components/Layout/NavMenu.razor +++ b/src/DockerUpdateGuard/Components/Layout/NavMenu.razor @@ -1,25 +1,11 @@ - - + diff --git a/src/DockerUpdateGuard/Components/Layout/NavMenu.razor.cs b/src/DockerUpdateGuard/Components/Layout/NavMenu.razor.cs index 869387a5..a03b31fe 100644 --- a/src/DockerUpdateGuard/Components/Layout/NavMenu.razor.cs +++ b/src/DockerUpdateGuard/Components/Layout/NavMenu.razor.cs @@ -1,158 +1,145 @@ -using System.Reflection; - -using DockerUpdateGuard.Configuration; -using DockerUpdateGuard.UI; - using Microsoft.AspNetCore.Components; -using Microsoft.Extensions.Options; +using Microsoft.AspNetCore.Components.Routing; namespace DockerUpdateGuard.Components.Layout; /// -/// Application navigation menu +/// Application navigation, rendered as the header row and as the list of the drawer /// -public partial class NavMenu +public sealed partial class NavMenu : IDisposable { #region Fields /// - /// Displayed application version - /// - private string _displayVersion = "unknown"; - - /// - /// Whether the My Images navigation entry should be shown - /// - private bool _showMyImages; - - /// - /// Whether the Shared Base Images navigation entry should be shown + /// Current location relative to the base address /// - private bool _showBaseImages; + private string _relativePath = string.Empty; #endregion // Fields #region Properties /// - /// Application configuration + /// Navigation state to render /// - [Inject] - public IConfiguration Configuration { get; set; } = null!; + [Parameter] + [EditorRequired] + public NavigationViewData Navigation { get; set; } = null!; /// - /// Application options + /// Callback invoked when a navigation entry is selected /// - [Inject] - public IOptions AppOptions { get; set; } = null!; - - /// - /// Application view service - /// - [Inject] - public IApplicationViewService ViewService { get; set; } = null!; + [Parameter] + public EventCallback OnEntrySelected { get; set; } /// - /// Logger + /// Navigation manager /// [Inject] - public ILogger Logger { get; set; } = null!; + public NavigationManager NavigationManager { get; set; } = null!; #endregion // Properties #region Static methods /// - /// Determine whether Docker Hub account discovery is configured for the given options + /// Determine whether the navigation entry with the given link target is the active one /// - /// Docker Hub options to evaluate - /// True when both UserName and Pat are non-empty - private static bool IsDockerHubAccountConfigured(DockerHubOptions dockerHub) + /// Link target of the entry, relative to the base address + /// Current location relative to the base address + /// True when the entry is the active one + internal static bool IsActive(string href, string relativePath) { - return string.IsNullOrWhiteSpace(dockerHub.UserName) == false - && string.IsNullOrWhiteSpace(dockerHub.Pat) == false; - } + var path = relativePath; + var cut = path.IndexOfAny(['?', '#']); - #endregion // Static methods + if (cut >= 0) + { + path = path[..cut]; + } - #region Methods + if (path.EndsWith('/')) + { + path = path[..^1]; + } - /// - /// Determine whether Docker Hub account discovery is configured - /// - /// True when both UserName and Pat are non-empty - private bool IsDockerHubAccountConfigured() - { - return IsDockerHubAccountConfigured(AppOptions.Value.DockerHub); + if (href.Length == 0) + { + return path.Length == 0; + } + + return path.Equals(href, StringComparison.OrdinalIgnoreCase) + || path.StartsWith(href + "/", StringComparison.OrdinalIgnoreCase); } - /// - /// Load whether the Shared Base Images navigation entry should be shown - /// - /// Task - private async Task LoadBaseImagesEntryAsync() - { - var hasBaseImages = await ViewService.HasBaseImagesAsync().ConfigureAwait(false); + #endregion // Static methods - await InvokeAsync(() => _showBaseImages = hasBaseImages).ConfigureAwait(false); - } + #region Methods /// - /// Resolve the version to display in the navigation footer + /// Get the entries to show, in order /// - /// Display version - private string ResolveDisplayVersion() + /// Entries as link target and label + private IEnumerable<(string Href, string Label)> GetEntries() { - var configuredVersion = Configuration["DockerUpdateGuard:DisplayVersion"]; + yield return (string.Empty, "Dashboard"); - if (string.IsNullOrWhiteSpace(configuredVersion) == false) + if (Navigation.ShowMyImages) { - return configuredVersion; + yield return ("my-images", "My Images"); } - var environmentVersion = Environment.GetEnvironmentVariable("DockerUpdateGuard__DisplayVersion"); + yield return ("observed-images", "Observed Images"); + yield return ("runtime-containers", "Runtime Containers"); + yield return ("docker-instances", "Docker Instances"); - if (string.IsNullOrWhiteSpace(environmentVersion) == false) + if (Navigation.ShowBaseImages) { - return environmentVersion; + yield return ("base-images", "Base Images"); } - var entryAssembly = Assembly.GetEntryAssembly() ?? typeof(NavMenu).Assembly; - var informationalVersion = entryAssembly.GetCustomAttribute()?.InformationalVersion; + yield return ("vulnerabilities", "Vulnerabilities"); + yield return ("scan-history", "Scan History"); + } - if (string.IsNullOrWhiteSpace(informationalVersion) == false) - { - return informationalVersion; - } + /// + /// Re-render for the new location + /// + /// Event sender + /// Navigation event arguments + private void OnLocationChanged(object? sender, LocationChangedEventArgs args) + { + _relativePath = NavigationManager.ToBaseRelativePath(args.Location); - var fileVersion = entryAssembly.GetCustomAttribute()?.Version; + _ = InvokeAsync(StateHasChanged); + } - if (string.IsNullOrWhiteSpace(fileVersion) == false) - { - return fileVersion; - } + #endregion // Methods - var assemblyVersion = entryAssembly.GetName().Version; + #region ComponentBase - if (assemblyVersion is not null) - { - return assemblyVersion.ToString(3); - } + /// + protected override void OnInitialized() + { + _relativePath = NavigationManager.ToBaseRelativePath(NavigationManager.Uri); + NavigationManager.LocationChanged += OnLocationChanged; + } - return "unknown"; + /// + protected override void OnParametersSet() + { + _relativePath = NavigationManager.ToBaseRelativePath(NavigationManager.Uri); } - #endregion // Methods + #endregion // ComponentBase - #region ComponentBase + #region IDisposable /// - protected override async Task OnInitializedAsync() + public void Dispose() { - _displayVersion = ResolveDisplayVersion(); - _showMyImages = IsDockerHubAccountConfigured(); - _ = await PageLoader.LoadAsync(LoadBaseImagesEntryAsync, Logger, "LoadNavigation", "Loading the navigation failed").ConfigureAwait(false); + NavigationManager.LocationChanged -= OnLocationChanged; } - #endregion // ComponentBase + #endregion // IDisposable } \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Layout/NavigationViewData.cs b/src/DockerUpdateGuard/Components/Layout/NavigationViewData.cs new file mode 100644 index 00000000..2a8da2f3 --- /dev/null +++ b/src/DockerUpdateGuard/Components/Layout/NavigationViewData.cs @@ -0,0 +1,26 @@ +namespace DockerUpdateGuard.Components.Layout; + +/// +/// Navigation state shared by the header row and the drawer +/// +public sealed class NavigationViewData +{ + #region Properties + + /// + /// Whether the My Images entry is shown + /// + public bool ShowMyImages { get; init; } + + /// + /// Whether the Base Images entry is shown + /// + public bool ShowBaseImages { get; init; } + + /// + /// Version displayed at the end of every page and in the drawer + /// + public string DisplayVersion { get; init; } = "unknown"; + + #endregion // Properties +} \ No newline at end of file diff --git a/src/DockerUpdateGuard/UI/ApplicationViewService.cs b/src/DockerUpdateGuard/UI/ApplicationViewService.cs index 5771ccf3..b4576c29 100644 --- a/src/DockerUpdateGuard/UI/ApplicationViewService.cs +++ b/src/DockerUpdateGuard/UI/ApplicationViewService.cs @@ -2069,27 +2069,6 @@ public async Task GetDashboardAsync(CancellationToken cancell cancellationToken).ConfigureAwait(false); } - /// - public async Task GetDashboardSummaryAsync(CancellationToken cancellationToken = default) - { - return await ExecuteSerializedAsync(async () => - { - var recentScans = await GetScanHistoryCoreAsync(1, cancellationToken).ConfigureAwait(false); - var observedImageCount = await _dbContext.ObservedImages.CountAsync(entity => entity.Source == RegistrationSource.Manual, cancellationToken).ConfigureAwait(false); - var myImageCount = await _dbContext.ObservedImages.CountAsync(entity => entity.Source == RegistrationSource.Discovery, cancellationToken).ConfigureAwait(false); - var latestSnapshots = await GetLatestContainerSnapshotsAsync(cancellationToken).ConfigureAwait(false); - - return new DashboardSummaryViewData - { - ObservedImageCount = observedImageCount, - MyImageCount = myImageCount, - RuntimeContainerCount = latestSnapshots.Count, - LatestScan = recentScans.Count > 0 ? recentScans[0] : null, - }; - }, - cancellationToken).ConfigureAwait(false); - } - /// public Task> GetObservedImagesAsync(CancellationToken cancellationToken = default) { diff --git a/src/DockerUpdateGuard/UI/DashboardSummaryViewData.cs b/src/DockerUpdateGuard/UI/DashboardSummaryViewData.cs deleted file mode 100644 index daf084e9..00000000 --- a/src/DockerUpdateGuard/UI/DashboardSummaryViewData.cs +++ /dev/null @@ -1,31 +0,0 @@ -namespace DockerUpdateGuard.UI; - -/// -/// Lightweight dashboard summary consumed by the application top bar, avoiding the full dashboard aggregation on every navigation -/// -public class DashboardSummaryViewData -{ - #region Properties - - /// - /// Manually-registered observed image count - /// - public int ObservedImageCount { get; set; } - - /// - /// Discovery-owned observed image count - /// - public int MyImageCount { get; set; } - - /// - /// Runtime container count - /// - public int RuntimeContainerCount { get; set; } - - /// - /// Most recent scan, or null when no scan has been recorded yet - /// - public ScanHistoryItemData? LatestScan { get; set; } - - #endregion // Properties -} \ No newline at end of file diff --git a/src/DockerUpdateGuard/UI/IApplicationViewService.cs b/src/DockerUpdateGuard/UI/IApplicationViewService.cs index 9419ae69..e9bd6c44 100644 --- a/src/DockerUpdateGuard/UI/IApplicationViewService.cs +++ b/src/DockerUpdateGuard/UI/IApplicationViewService.cs @@ -14,13 +14,6 @@ public interface IApplicationViewService /// Dashboard view data Task GetDashboardAsync(CancellationToken cancellationToken = default); - /// - /// Read the lightweight dashboard summary for the application top bar - /// - /// Cancellation token - /// Dashboard summary view data - Task GetDashboardSummaryAsync(CancellationToken cancellationToken = default); - /// /// Read all observed images for the overview page /// diff --git a/src/DockerUpdateGuard/wwwroot/app.css b/src/DockerUpdateGuard/wwwroot/app.css index 3a139124..cb26e654 100644 --- a/src/DockerUpdateGuard/wwwroot/app.css +++ b/src/DockerUpdateGuard/wwwroot/app.css @@ -135,208 +135,177 @@ a { background: var(--dug-bg-page); } -.app-drawer { - width: min(360px, 92vw); +.app-shell { + min-height: 100vh; } -.app-drawer .mud-drawer-content { - padding: 1.75rem 1.25rem 1.5rem; - color: var(--dug-text); +.app-header { + position: sticky; + top: 0; + z-index: 1100; background: var(--dug-surface); - border-right: 1px solid var(--dug-border); - box-shadow: none; + border-bottom: 1px solid var(--dug-border); } -.app-drawer-content { - height: 100%; +.app-header__inner { + display: flex; + flex-wrap: nowrap; + align-items: center; + max-width: 1344px; + margin-inline: auto; + padding-inline: 32px; + gap: 28px; + min-height: 60px; } -.app-brand__logo { - width: 3rem; - height: 3rem; +.app-header__menu-button { flex: 0 0 auto; - border-radius: 0.9rem; + width: 44px; + min-width: 44px; + height: 44px; + min-height: 44px; + margin-inline-start: -10px; + color: var(--dug-text); +} + +.app-brand { + display: inline-flex; + flex: 0 0 auto; + align-items: center; + gap: 10px; + min-width: 44px; + height: 44px; + color: var(--dug-text); + text-decoration: none; +} + +.app-brand__mark { + flex: 0 0 auto; + width: 28px; + height: 28px; + color: var(--dug-primary); } .app-brand__title { min-width: fit-content; color: var(--dug-text); font-family: var(--dug-font-display); - font-size: clamp(1.15rem, 1.2rem + 0.3vw, 1.35rem); - font-weight: 600; + font-size: 1.125rem; + font-weight: 700; letter-spacing: -0.02em; white-space: nowrap; overflow-wrap: normal; } -.app-nav-shell { - color: var(--dug-text); +.app-nav { display: flex; + flex-wrap: nowrap; flex: 1 1 auto; - flex-direction: column; - min-height: 100%; -} - -.nav-section-label, -.page-eyebrow, -.section-eyebrow { - color: var(--dug-primary); - font-size: 0.78rem; - font-weight: 700; - letter-spacing: 0.12em; - text-transform: uppercase; + align-items: stretch; + min-width: 0; } -.nav-section-label { +.app-nav__link { + display: inline-flex; + flex: 0 0 auto; + align-items: center; + min-width: 44px; + min-height: 60px; + padding: 0 10px; color: var(--dug-text-muted); - padding-inline: 0.75rem; -} - -.app-nav-menu { - gap: 0.55rem; + font-size: 14px; + text-decoration: none; + white-space: nowrap; } -.app-nav-menu .mud-nav-link { - margin-bottom: 0.35rem; - padding: 1rem 1.05rem; - color: var(--dug-text); - border: 1px solid transparent; - border-radius: var(--dug-radius-md); +.app-nav__link:hover { + color: var(--dug-link); } -.app-nav-menu .mud-nav-link:hover { +.app-nav__link--active { color: var(--dug-text); - background: var(--dug-surface-subtle); + font-weight: 600; + box-shadow: inset 0 -2px 0 var(--dug-primary); } -.mud-navmenu.app-nav-menu .mud-nav-link.active:not(.mud-nav-link-disabled), -.mud-navmenu.app-nav-menu .mud-nav-link.active:not(.mud-nav-link-disabled):hover:not(.mud-nav-link-disabled), -.mud-navmenu.app-nav-menu .mud-nav-link.active:not(.mud-nav-link-disabled):focus-visible:not(.mud-nav-link-disabled), -.mud-navmenu.app-nav-menu .mud-nav-link.active:not(.mud-nav-link-disabled):active:not(.mud-nav-link-disabled) { +.app-topbar__theme-toggle { + flex: 0 0 auto; + width: 44px; + min-width: 44px; + height: 44px; + min-height: 44px; + margin-inline-start: auto; color: var(--dug-text); - font-weight: 600 !important; - background: var(--dug-surface-subtle); - border-color: transparent; - box-shadow: none; -} - -.app-nav-menu .mud-nav-link-icon { - color: inherit; -} - -.app-version { - margin-top: auto; - padding: 1rem 0.75rem 0.2rem; -} - -.app-version__label, -.app-version__value { - display: block; } -.app-version__label { - color: var(--dug-text-muted); - font-size: 0.72rem; - letter-spacing: 0.06em; - text-transform: uppercase; +.app-drawer { + --mud-drawer-width: min(360px, 92vw); } -.app-version__value { - margin-top: 0.2rem; +.app-drawer .mud-drawer-content { + display: flex; + flex-direction: column; + padding: 1rem 1rem 1.5rem; color: var(--dug-text); - font-size: 0.78rem; -} - -.app-main-content { - min-height: 100vh; -} - -.mud-paper.app-topbar { background: var(--dug-surface); - border: 1px solid var(--dug-border); - border-radius: var(--dug-radius-lg); + border-right: 1px solid var(--dug-border); box-shadow: none; } -.app-topbar { - position: sticky; - top: 0; - z-index: 1100; - margin: 1.5rem 1.5rem 0.75rem; - padding: 0.9rem 1.35rem; -} - -.app-topbar__content { - display: flex; - align-items: center; - justify-content: space-between; - gap: 1.5rem; +.app-drawer.mud-drawer--closed { + visibility: hidden; } -.app-topbar__brand { - display: flex; - align-items: center; - gap: 1rem; - min-width: 0; -} - -.app-topbar__logo { - width: 2.75rem; - height: 2.75rem; -} - -.app-topbar__title { - color: var(--dug-text); - font-family: var(--dug-font-display); -} - -.app-topbar__menu-button { - display: none; - color: var(--dug-text); - margin-left: -0.35rem; -} - -.app-topbar__theme-toggle { +.app-drawer .app-nav { flex: 0 0 auto; - color: var(--dug-text); + flex-direction: column; } -.app-topbar__meta { - display: flex; - align-items: stretch; - justify-content: flex-end; - gap: 0.85rem; - flex-wrap: wrap; +.app-drawer .app-nav__link { + min-height: 44px; + padding: 0 12px; + border-radius: var(--dug-radius-md); + font-size: 0.9375rem; } -.app-topbar__meta-card { - min-width: 9rem; - flex: 0 1 auto; +.app-drawer .app-nav__link--active { background: var(--dug-surface-subtle); + box-shadow: none; } -.app-topbar__status { - white-space: nowrap; +.app-version { + margin: 0; + color: var(--dug-text-muted); + font-size: 13px; } -.app-topbar__meta--compact { - display: none; +.app-drawer .app-version { + margin-top: auto; + padding: 1rem 12px 0; } -.app-topbar__pill { +.page-eyebrow, +.section-eyebrow { + color: var(--dug-primary); + font-size: 0.78rem; font-weight: 700; + letter-spacing: 0.12em; + text-transform: uppercase; } -.app-topbar__meta-popover { - display: flex; - flex-direction: column; - gap: 0.75rem; - padding: 0.85rem 1rem; - min-width: 12rem; +.page-container { + max-width: 1344px; + margin-inline: auto; + padding-inline: 32px; + padding-block: 36px 48px; } -.page-container { - padding: 0.75rem 1.5rem 2rem; +.page-container > .app-version { + margin-top: 48px; +} + +.page-container code { + overflow-wrap: anywhere; } @keyframes dug-fade-in { @@ -451,7 +420,6 @@ a { .metric-card, .summary-card, -.app-nav-menu .mud-nav-link, .mud-button-root { transition: border-color var(--dug-transition), background-color var(--dug-transition); } @@ -465,7 +433,8 @@ a { outline-offset: 2px; } -.app-nav-menu .mud-nav-link:focus-visible, +.app-nav__link:focus-visible, +.app-brand:focus-visible, .mud-button-root:focus-visible { outline: 2px solid var(--dug-primary); outline-offset: 2px; @@ -1096,19 +1065,24 @@ a { margin-bottom: 1rem; } -@media (max-width: 1280px) { - .app-topbar__menu-button { - display: inline-flex; +@media (min-width: 1360px) { + .app-header__menu-button, + .app-drawer, + .mud-drawer-overlay { + display: none !important; } } -@media (max-width: 960px) { - .app-topbar { - margin-inline: 1rem; +@media (max-width: 1359.98px) { + .app-header .app-nav { + display: none; } +} - .page-container { - padding-inline: 1rem; +@media (max-width: 960px) { + .page-container, + .app-header__inner { + padding-inline: 16px; } .hero-panel { @@ -1201,34 +1175,9 @@ a { align-items: flex-start; } - .app-topbar { - margin: 1rem 0.75rem 0.5rem; - padding: 0.5rem 0.75rem; - } - - .app-topbar__brand { - gap: 0.75rem; - } - - .app-topbar__logo { - width: 2rem; - height: 2rem; - } - - .app-topbar__title { - font-size: 1.05rem; - } - - .app-topbar__meta--full { - display: none; - } - - .app-topbar__meta--compact { - display: block; - } - - .page-container { - padding-inline: 0.75rem; + .page-container, + .app-header__inner { + padding-inline: 12px; } .section-paper, @@ -1247,7 +1196,7 @@ a { } @media (max-width: 399.98px) { - .app-topbar__title { + .app-brand__title { display: none; } } diff --git a/src/DockerUpdateGuard/wwwroot/favicon.svg b/src/DockerUpdateGuard/wwwroot/favicon.svg index 56d36e7b..0683c389 100644 --- a/src/DockerUpdateGuard/wwwroot/favicon.svg +++ b/src/DockerUpdateGuard/wwwroot/favicon.svg @@ -1,11 +1,3 @@ - - - - - - - - - DG + diff --git a/src/DockerUpdateGuard/wwwroot/logo-dg-shield.svg b/src/DockerUpdateGuard/wwwroot/logo-dg-shield.svg index 54cbdb0d..ccfbe476 100644 --- a/src/DockerUpdateGuard/wwwroot/logo-dg-shield.svg +++ b/src/DockerUpdateGuard/wwwroot/logo-dg-shield.svg @@ -1,13 +1,5 @@ DockerUpdateGuard logo - Shield icon with the letters DG - - - - - - - - - DG + Shield icon + diff --git a/src/Tests/DockerUpdateGuard.Tests/AppBrandAssetsTests.cs b/src/Tests/DockerUpdateGuard.Tests/AppBrandAssetsTests.cs new file mode 100644 index 00000000..2779701c --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/AppBrandAssetsTests.cs @@ -0,0 +1,112 @@ +using System.Xml.Linq; + +using DockerUpdateGuard.Tests.Helper; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for the shipped brand assets wwwroot/favicon.svg and wwwroot/logo-dg-shield.svg +/// +[TestClass] +public class AppBrandAssetsTests +{ + #region Constants + + /// + /// Outer shield path of the brand + /// + private const string ShieldPath = "M64 8c20 14 37 18 52 20v34c0 28-18 47-52 58C30 109 12 90 12 62V28c15-2 32-6 52-20Z"; + + /// + /// Light accent color of the brand, the only color of the flat shield + /// + private const string AccentColor = "#2563EB"; + + #endregion // Constants + + #region Fields + + /// + /// Local names of the elements of a gradient, a letter or a second layer, which the flat shield must not have + /// + private static readonly string[] _bannedElements = ["linearGradient", "radialGradient", "stop", "defs", "text", "filter"]; + + #endregion // Fields + + #region Methods + + /// + /// Verify an asset is the flat one-color shield, a single outer shield path in the accent color without gradient, letters or opacity + /// + /// Path of the asset below the host project directory + /// Expected accessible title, or null when the asset has none + /// Expected accessible description, or null when the asset has none + [TestMethod] + [TestCategory("AC8")] + [DataRow("wwwroot/favicon.svg", null, null)] + [DataRow("wwwroot/logo-dg-shield.svg", "DockerUpdateGuard logo", "Shield icon")] + public void AppBrandAssetsAreFlatOneColorShield(string path, string? title, string? description) + { + var document = XDocument.Parse(StylesheetReader.ReadHostFile(path)); + var mismatches = FindShieldMismatches(document).Concat(FindTextMismatches(document, "title", title)) + .Concat(FindTextMismatches(document, "desc", description)) + .ToList(); + + Assert.AreEqual(string.Empty, string.Join("; ", mismatches), $"{path} must be the flat one-color shield"); + } + + /// + /// Find the differences of a document from the flat one-color shield + /// + /// Parsed asset + /// One text per difference + private static IEnumerable FindShieldMismatches(XDocument document) + { + var elements = document.Descendants().ToList(); + var paths = elements.Where(element => element.Name.LocalName == "path").ToList(); + + if (document.Root?.Attribute("viewBox")?.Value != "0 0 128 128") + { + yield return "the view box is not 0 0 128 128"; + } + + if (paths.Count != 1) + { + yield return $"the asset has {paths.Count} paths instead of the one outer shield"; + } + + foreach (var path in paths.Where(path => path.Attribute("d")?.Value != ShieldPath || string.Equals(path.Attribute("fill")?.Value, AccentColor, StringComparison.OrdinalIgnoreCase) == false)) + { + yield return $"the path is not the outer shield filled {AccentColor}: d={path.Attribute("d")?.Value}, fill={path.Attribute("fill")?.Value}"; + } + + foreach (var banned in elements.Where(element => _bannedElements.Contains(element.Name.LocalName))) + { + yield return $"the asset has a {banned.Name.LocalName} element"; + } + + foreach (var attribute in elements.Attributes().Where(attribute => attribute.Name.LocalName is "opacity" or "fill-opacity" or "stroke")) + { + yield return $"the asset has the attribute {attribute.Name.LocalName}"; + } + } + + /// + /// Compare the text of an element with the expected one, or require the element to be absent + /// + /// Parsed asset + /// Local name of the element + /// Expected text, or null when there is no such element + /// One text per difference + private static IEnumerable FindTextMismatches(XDocument document, string name, string? expected) + { + var actual = document.Descendants().SingleOrDefault(element => element.Name.LocalName == name)?.Value; + + if (actual != expected) + { + yield return $"the {name} is '{actual}' instead of '{expected}'"; + } + } + + #endregion // Methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/AppStylesheetTests.cs b/src/Tests/DockerUpdateGuard.Tests/AppStylesheetTests.cs index 276f45de..81df361b 100644 --- a/src/Tests/DockerUpdateGuard.Tests/AppStylesheetTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/AppStylesheetTests.cs @@ -113,6 +113,21 @@ private static readonly (string Chip, string LightBackground, string LightText, "--dug-info", ]; + /// + /// Selectors the wide layout hides + /// + private static readonly string[] _wideHiddenSelectors = [".app-header__menu-button", ".app-drawer", ".mud-drawer-overlay"]; + + /// + /// Accepted spellings of 14 px + /// + private static readonly string[] _linkFontSizes = ["14px", "0.875rem"]; + + /// + /// Selectors that share the side padding of the content + /// + private static readonly string[] _paddedSelectors = [".page-container", ".app-header__inner"]; + /// /// Ground tokens text is drawn on /// @@ -376,7 +391,7 @@ public void AppStylesheetSetsTextAndDisplayFonts() [("font-family", "var(--dug-font-display)"), ("font-weight", "600")])) .Concat(FindDeclarationMismatches(".app-brand__title", StylesheetReader.GetDeclarations(css, ".app-brand__title"), - [("font-family", "var(--dug-font-display)"), ("font-weight", "600")])) + [("font-family", "var(--dug-font-display)"), ("font-weight", "700")])) .ToList(); AssertNoMismatches(mismatches, "Text, figures and the product name must use the fonts of the refresh"); @@ -502,7 +517,6 @@ public void AppStylesheetTransitionsAnimateOnlyBorderAndBackgroundColors() [DataRow(".section-paper")] [DataRow(".empty-state-panel")] [DataRow(".summary-card")] - [DataRow(".mud-paper.app-topbar")] public void AppStylesheetPanelsAreOpaqueSurfacesWithHairlineBorder(string selector) { var declarations = StylesheetReader.GetDeclarations(ReadStylesheet(), selector); @@ -528,30 +542,31 @@ public void AppStylesheetLayoutGroundIsPlainPageColor() } /// - /// Verify the drawer is a surface-colored panel with a hairline on its right and no shadow, with its texts in the token colors + /// Verify the drawer is a surface-colored panel with a hairline on its right and no shadow, and the navigation entries and the version line use the token colors /// [TestMethod] - [TestCategory("AC7")] + [TestCategory("AC3")] public void AppStylesheetDrawerIsSurfacePanelWithTokenTexts() { var css = ReadStylesheet(); var drawer = StylesheetReader.GetDeclarations(css, ".app-drawer .mud-drawer-content"); - var activeLink = StylesheetReader.GetDeclarations(css, ".mud-navmenu.app-nav-menu .mud-nav-link.active:not(.mud-nav-link-disabled)"); - var hoverLink = StylesheetReader.GetDeclarations(css, ".app-nav-menu .mud-nav-link:hover"); + var link = StylesheetReader.GetDeclarations(css, ".app-nav__link"); + var hoverLink = StylesheetReader.GetDeclarations(css, ".app-nav__link:hover"); + var activeLink = StylesheetReader.GetDeclarations(css, ".app-nav__link--active"); + var drawerActiveLink = StylesheetReader.GetDeclarations(css, ".app-drawer .app-nav__link--active"); var mismatches = FindDeclarationMismatches("drawer", ReadBackground(drawer), [("background", "var(--dug-surface)")]).Concat(FindDeclarationMismatches("drawer", drawer, [("border-right", HairlineBorder)])) - .Concat(FindDeclarationMismatches("active link", activeLink, [("font-weight", "600 !important"), ("color", "var(--dug-text)")])) - .Concat(FindDeclarationMismatches("active link", ReadBackground(activeLink), [("background", "var(--dug-surface-subtle)")])) - .Concat(FindDeclarationMismatches("hovered link", ReadBackground(hoverLink), [("background", "var(--dug-surface-subtle)")])) - .Concat(FindDeclarationMismatches(".nav-section-label", StylesheetReader.GetDeclarations(css, ".nav-section-label"), [("color", "var(--dug-text-muted)")])) - .Concat(FindDeclarationMismatches(".app-version__label", StylesheetReader.GetDeclarations(css, ".app-version__label"), [("color", "var(--dug-text-muted)")])) - .Concat(FindDeclarationMismatches(".app-version__value", StylesheetReader.GetDeclarations(css, ".app-version__value"), [("color", "var(--dug-text)")])) + .Concat(FindDeclarationMismatches("inactive entry", link, [("color", "var(--dug-text-muted)")])) + .Concat(FindDeclarationMismatches("hovered entry", hoverLink, [("color", "var(--dug-link)")])) + .Concat(FindDeclarationMismatches("active entry", activeLink, [("color", "var(--dug-text)"), ("font-weight", "600"), ("box-shadow", "inset 0 -2px 0 var(--dug-primary)")])) + .Concat(FindDeclarationMismatches("active entry in the drawer", ReadBackground(drawerActiveLink), [("background", "var(--dug-surface-subtle)")])) + .Concat(FindDeclarationMismatches(".app-version", StylesheetReader.GetDeclarations(css, ".app-version"), [("color", "var(--dug-text-muted)"), ("font-size", "13px")])) .Concat(FindDeclarationMismatches(".app-brand__title", StylesheetReader.GetDeclarations(css, ".app-brand__title"), [("color", "var(--dug-text)")])) .ToList(); Assert.IsFalse(drawer.TryGetValue("box-shadow", out var shadow) && shadow != "none", "The drawer must have no shadow"); - AssertNoMismatches(mismatches, "The drawer must be a flat surface panel with token texts"); + AssertNoMismatches(mismatches, "The drawer must be a flat surface panel with token texts, the entries and the version line included"); } /// @@ -660,6 +675,157 @@ public void AppStylesheetKeepsReducedMotionRule() "The reduced-motion rule must set both durations to 0.01ms !important for every element and pseudo-element"); } + /// + /// Verify from 1360 px the menu button, the drawer and its overlay are hidden, and below it the navigation row of the header + /// + [TestMethod] + [TestCategory("AC1")] + public void AppStylesheetWideLayoutHidesMenuButtonAndDrawer() + { + var css = ReadStylesheet(); + + var mismatches = _wideHiddenSelectors.Select(selector => FindHiddenIn(css, "@media (min-width: 1360px)", selector)) + .Append(FindHiddenIn(css, "@media (max-width: 1359.98px)", ".app-header .app-nav")) + .OfType() + .ToList(); + + AssertNoMismatches(mismatches, "The wide layout must hide the menu button, the drawer and the overlay, the narrow layout the navigation row, at the two sides of the 1360 px breakpoint"); + } + + /// + /// Verify the header is a sticky surface with a hairline below it, below the drawer, and its row is one non-wrapping line of the content width + /// + [TestMethod] + [TestCategory("AC1")] + public void AppStylesheetHeaderRowIsOneNonWrappingLineOfContentWidth() + { + var css = ReadStylesheet(); + + var header = StylesheetReader.GetDeclarations(css, ".app-header"); + var inner = StylesheetReader.GetDeclarations(css, ".app-header__inner"); + var row = StylesheetReader.GetDeclarations(css, ".app-nav"); + var link = StylesheetReader.GetDeclarations(css, ".app-nav__link"); + + var mismatches = FindDeclarationMismatches(".app-header", header, [("position", "sticky"), ("top", "0"), ("border-bottom", HairlineBorder)]).Concat(FindDeclarationMismatches(".app-header", ReadBackground(header), [("background", "var(--dug-surface)")])) + .Concat(FindDeclarationMismatches(".app-header__inner", inner, [("display", "flex"), ("flex-wrap", "nowrap"), ("align-items", "center"), ("max-width", "1344px"), ("margin-inline", "auto"), ("padding-inline", "32px")])) + .Concat(FindDeclarationMismatches(".app-header__inner", ReadGap(inner), [("gap", "28px")])) + .Concat(FindDeclarationMismatches(".app-nav", row, [("display", "flex"), ("flex-wrap", "nowrap")])) + .Concat(FindDeclarationMismatches(".app-nav__link", link, [("padding", "0 10px")])) + .ToList(); + + AssertNoMismatches(mismatches, "The header must be a sticky flat bar and its row one line of the content width that never wraps"); + Assert.AreEqual(60d, ReadPixels(link, "min-height", "height"), "A link of the row must be 60 px high, the height of the header"); + Assert.IsTrue(int.TryParse(header.GetValueOrDefault("z-index"), out var zIndex) && zIndex is > 0 and <= 1100, "The header must stack above the page and below the overlay and the drawer of MudBlazor, which start at 1101"); + Assert.Contains(link.GetValueOrDefault("font-size") ?? string.Empty, _linkFontSizes, "A link of the row must be 14 px"); + } + + /// + /// Verify the content container has the content width, the padding of the issue and the narrower padding below 960 px and 600 px + /// + [TestMethod] + [TestCategory("AC9")] + public void AppStylesheetContentContainerHasContentWidthAndPadding() + { + var css = ReadStylesheet(); + + var container = StylesheetReader.GetDeclarations(css, ".page-container"); + + var mismatches = FindDeclarationMismatches(".page-container", container, [("max-width", "1344px"), ("margin-inline", "auto"), ("padding-inline", "32px"), ("padding-block", "36px 48px")]).Concat(FindNarrowPaddingMismatches(css, "@media (max-width: 960px)", ["16px", "1rem"])) + .Concat(FindNarrowPaddingMismatches(css, "@media (max-width: 599.98px)", ["12px", "0.75rem"])) + .ToList(); + + Assert.DoesNotContain("padding", container.Keys, "The container must set its padding by direction only, so no shorthand overrides the side padding"); + AssertNoMismatches(mismatches, "The content must be centered with 1280 px of content and 32 px at the sides, narrower below 960 px and 600 px, with the same side padding in the header"); + } + + /// + /// Verify inline code in the content wraps anywhere, so a long digest or reference cannot widen the page + /// + [TestMethod] + [TestCategory("AC9")] + public void AppStylesheetContentCodeWrapsAnywhere() + { + var declarations = StylesheetReader.GetDeclarations(ReadStylesheet(), ".page-container code"); + + Assert.IsTrue(declarations.TryGetValue("overflow-wrap", out var value), "The rule for code in the content must declare overflow-wrap"); + Assert.AreEqual("anywhere", value, "Code in the content must wrap anywhere"); + } + + /// + /// Verify every control of the header and the drawer is at least 44 px high and the links draw the 2 px primary outline on keyboard focus + /// + [TestMethod] + [TestCategory("AC9")] + public void AppStylesheetHeaderControlsMeetTargetSizeAndFocusOutline() + { + var css = ReadStylesheet(); + + var sizes = new (string Selector, string[] Width, string[] Height)[] + { + (".app-header__menu-button", ["width", "min-width"], ["height", "min-height"]), + (".app-topbar__theme-toggle", ["width", "min-width"], ["height", "min-height"]), + (".app-brand", ["min-width"], ["height", "min-height"]), + (".app-nav__link", ["min-width"], ["height", "min-height"]), + (".app-drawer .app-nav__link", ["min-width"], ["height", "min-height"]) + }; + + var tooSmall = sizes.Where(size => ReadPixels(StylesheetReader.GetDeclarations(css, size.Selector), size.Height) < 44d) + .Select(size => $"{size.Selector} is lower than 44 px") + .Concat(sizes.Where(size => size.Selector is ".app-header__menu-button" or ".app-topbar__theme-toggle" && ReadPixels(StylesheetReader.GetDeclarations(css, size.Selector), size.Width) < 44d) + .Select(size => $"{size.Selector} is narrower than 44 px")) + .ToList(); + + var mismatches = FindDeclarationMismatches(".app-nav__link:focus-visible", StylesheetReader.GetDeclarations(css, ".app-nav__link:focus-visible"), [("outline", "2px solid var(--dug-primary)"), ("outline-offset", "2px")]).Concat(FindDeclarationMismatches(".app-brand:focus-visible", StylesheetReader.GetDeclarations(css, ".app-brand:focus-visible"), [("outline", "2px solid var(--dug-primary)"), ("outline-offset", "2px")])) + .Concat(FindDeclarationMismatches(".mud-button-root:focus-visible", StylesheetReader.GetDeclarations(css, ".mud-button-root:focus-visible"), [("outline", "2px solid var(--dug-primary)"), ("outline-offset", "2px")])) + .Concat(tooSmall) + .ToList(); + + AssertNoMismatches(mismatches, "The header and drawer controls must be 44 px targets with the focus outline of the refresh"); + } + + /// + /// Verify below 400 px the product name next to the shield is hidden + /// + [TestMethod] + [TestCategory("AC9")] + public void AppStylesheetNarrowestLayoutHidesProductName() + { + var hidden = FindHiddenIn(ReadStylesheet(), "@media (max-width: 399.98px)", ".app-brand__title"); + + Assert.IsNull(hidden, "Below 400 px the product name must be hidden and the shield stay"); + } + + /// + /// Verify the closed drawer is hidden from keyboard focus and assistive technology + /// + [TestMethod] + [TestCategory("AC9")] + public void AppStylesheetClosedDrawerIsHiddenFromFocusAndAssistiveTechnology() + { + var css = ReadStylesheet(); + + var hiding = StylesheetReader.GetRules(css) + .Where(rule => StylesheetReader.SplitTopLevel(rule.Selector, ',').Any(selector => selector.Contains(".app-drawer", StringComparison.Ordinal) && selector.Contains(".mud-drawer--closed", StringComparison.Ordinal))) + .SelectMany(rule => StylesheetReader.GetDeclarationList(rule.Body)) + .Where(declaration => declaration.Name == "visibility") + .Select(declaration => declaration.Value) + .ToList(); + + Assert.Contains("hidden", hiding, "The closed drawer must have visibility hidden, so its links cannot be focused and are not exposed as a second navigation"); + } + + /// + /// Verify the brand mark takes the primary color token of the active theme + /// + [TestMethod] + [TestCategory("AC8")] + public void AppStylesheetBrandMarkUsesPrimaryColorToken() + { + var mismatches = FindDeclarationMismatches(".app-brand__mark", StylesheetReader.GetDeclarations(ReadStylesheet(), ".app-brand__mark"), [("color", "var(--dug-primary)")]); + + AssertNoMismatches(mismatches, "The inline shield fills with the current color, which must be the primary token so it follows the theme"); + } + /// /// Verify neither the document nor the stylesheet names an external address: no http(s) address and no protocol-relative url /// @@ -855,6 +1021,80 @@ private static IEnumerable FindExternalAddresses(string relativePath) .Select(match => $"{relativePath} contains {match.Value}"); } + /// + /// Check that a selector is hidden by the rules of a media context + /// + /// Stylesheet text + /// Collapsed prelude of the media rule + /// Selector that must be hidden: a rule names it alone or as one compound selector that holds it + /// A text when the selector is not hidden there, otherwise null + private static string? FindHiddenIn(string css, string context, string selector) + { + var display = StylesheetReader.GetRules(css) + .Where(rule => rule.Context == context && StylesheetReader.SplitTopLevel(rule.Selector, ',').Any(entry => entry == selector || (entry.Contains(' ', StringComparison.Ordinal) == false && entry.Contains(selector, StringComparison.Ordinal)))) + .SelectMany(rule => StylesheetReader.GetDeclarationList(rule.Body)) + .Where(declaration => declaration.Name == "display") + .Select(declaration => declaration.Value.Replace("!important", string.Empty, StringComparison.Ordinal).Trim()) + .ToList(); + + return display.Contains("none") ? null : $"{selector} is not hidden in {context}"; + } + + /// + /// Compare the side padding of the content container and the header row inside a media context + /// + /// Stylesheet text + /// Collapsed prelude of the media rule + /// Accepted spellings of the padding + /// One text per selector whose padding differs + private static IEnumerable FindNarrowPaddingMismatches(string css, string context, string[] accepted) + { + return _paddedSelectors.Where(selector => StylesheetReader.GetRules(css) + .Where(rule => rule.Context == context && StylesheetReader.SplitTopLevel(rule.Selector, ',').Contains(selector)) + .SelectMany(rule => StylesheetReader.GetDeclarationList(rule.Body)) + .Where(declaration => declaration.Name == "padding-inline") + .Select(declaration => declaration.Value) + .Intersect(accepted) + .Any() == false) + .Select(selector => $"{selector} in {context} must have a side padding of {accepted[0]}"); + } + + /// + /// Pick the gap of a row, as gap, whichever of gap and column-gap it uses + /// + /// Declarations of the rule + /// Map with the gap entry, empty when the rule sets none + private static Dictionary ReadGap(Dictionary declarations) + { + var gap = new Dictionary(StringComparer.Ordinal); + + if (declarations.TryGetValue("column-gap", out var column)) + { + gap["gap"] = column; + } + else if (declarations.TryGetValue("gap", out var shorthand)) + { + gap["gap"] = shorthand; + } + + return gap; + } + + /// + /// Read the first of the given properties that is set in pixels + /// + /// Declarations of the rule + /// Property names in the order they are tried + /// Value in pixels, or -1 when none of the properties is set in pixels + private static double ReadPixels(Dictionary declarations, params string[] names) + { + return names.Select(name => declarations.GetValueOrDefault(name) ?? string.Empty) + .Where(value => value.EndsWith("px", StringComparison.Ordinal)) + .Select(value => double.TryParse(value[..^2], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var pixels) ? pixels : -1d) + .DefaultIfEmpty(-1d) + .First(); + } + /// /// Assert there is nothing to report /// diff --git a/src/Tests/DockerUpdateGuard.Tests/ApplicationTelemetryTests.cs b/src/Tests/DockerUpdateGuard.Tests/ApplicationTelemetryTests.cs index 4865bda4..b102a7df 100644 --- a/src/Tests/DockerUpdateGuard.Tests/ApplicationTelemetryTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/ApplicationTelemetryTests.cs @@ -238,7 +238,7 @@ await telemetry.RefreshInventoryMetricsAsync(dbContext, TestContext.Cancellation /// /// Task [TestMethod] - [TestCategory("AC4")] + [TestCategory("AC5")] public async Task ApplicationTelemetryRefreshInventoryMetricsMatchesDashboardRuntimeContainerCountAsync() { var dbContext = CreateDbContext(); @@ -262,7 +262,7 @@ await dbContext.SaveChangesAsync(TestContext.CancellationToken) await telemetry.RefreshInventoryMetricsAsync(dbContext, TestContext.CancellationToken) .ConfigureAwait(false); - var summary = await service.GetDashboardSummaryAsync(TestContext.CancellationToken) + var summary = await service.GetDashboardAsync(TestContext.CancellationToken) .ConfigureAwait(false); var containers = await service.GetRuntimeContainersAsync(TestContext.CancellationToken) .ConfigureAwait(false); diff --git a/src/Tests/DockerUpdateGuard.Tests/MainLayoutPersistentStateTests.cs b/src/Tests/DockerUpdateGuard.Tests/MainLayoutPersistentStateTests.cs new file mode 100644 index 00000000..300c2055 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/MainLayoutPersistentStateTests.cs @@ -0,0 +1,191 @@ +using Bunit; + +using DockerUpdateGuard.Components.Layout; +using DockerUpdateGuard.Configuration; +using DockerUpdateGuard.Tests.Helper; +using DockerUpdateGuard.UI; + +using Microsoft.AspNetCore.Components; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +using MudBlazor; + +using NSubstitute; + +namespace DockerUpdateGuard.Tests; + +/// +/// Persistent-state tests for +/// +[TestClass] +public class MainLayoutPersistentStateTests +{ + #region Constants + + /// + /// Persistent-state key used by the layout + /// + private const string StateKey = "MainLayout.Navigation"; + + /// + /// Selector of the navigation row in the header + /// + private const string HeaderNavigation = "header.app-header nav[aria-label=\"Main\"]"; + + #endregion // Constants + + #region Methods + + /// + /// Verify the layout reuses the persisted navigation state: no second base-image check, the entries and the version of the first render + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task MainLayoutWithPersistedNavigationDoesNotCheckBaseImagesAgain() + { + var viewService = CreateViewService(hasBaseImages: false); + var testContext = CreateContext(viewService, [], new DockerHubOptions()); + + await using (testContext) + { + testContext.GetPersistentComponentState() + .Persist(StateKey, + new NavigationViewData + { + ShowMyImages = true, + ShowBaseImages = true, + DisplayVersion = "9.9.9", + }); + + var component = testContext.Render(parameters => parameters.Add(layout => layout.Body, "body")); + + Assert.HasCount(1, component.FindAll($"{HeaderNavigation} a[href=\"my-images\"]"), "The My Images entry of the first render must be restored"); + Assert.HasCount(1, component.FindAll($"{HeaderNavigation} a[href=\"base-images\"]"), "The Base Images entry of the first render must be restored"); + Assert.AreEqual("DockerUpdateGuard 9.9.9", component.Find("main.page-container .app-version").TextContent.Trim(), "The version of the first render must be restored"); + + await viewService.DidNotReceive().HasBaseImagesAsync(Arg.Any()).ConfigureAwait(false); + } + } + + /// + /// Verify the layout persists the two navigation flags and the version once it has loaded them + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task MainLayoutPersistsNavigationFlagsAndVersion() + { + var settings = new Dictionary + { + ["DockerUpdateGuard:DisplayVersion"] = "1.2.3" + }; + var testContext = CreateContext(CreateViewService(hasBaseImages: true), + settings, + new DockerHubOptions + { + UserName = "alice", + Pat = "token" + }); + + await using (testContext) + { + var component = testContext.Render(parameters => parameters.Add(layout => layout.Body, "body")); + + await component.WaitForAssertionAsync(() => Assert.HasCount(1, component.FindAll($"{HeaderNavigation} a[href=\"base-images\"]"), "The base-image check must have finished"), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + + var persistentState = testContext.GetPersistentComponentState(); + + persistentState.TriggerOnPersisting(); + + Assert.IsTrue(persistentState.TryTake(StateKey, out var persisted), "The layout must persist its navigation state"); + Assert.IsTrue(persisted!.ShowMyImages, "The My Images flag must be persisted"); + Assert.IsTrue(persisted.ShowBaseImages, "The Base Images flag must be persisted"); + Assert.AreEqual("1.2.3", persisted.DisplayVersion, "The displayed version must be persisted"); + } + } + + /// + /// Verify a first render that persists its state and an interactive render that restores it check the base images once together + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task MainLayoutPrerenderThenInteractiveRenderChecksBaseImagesOnce() + { + var prerenderService = CreateViewService(hasBaseImages: true); + var interactiveService = CreateViewService(hasBaseImages: true); + var settings = new Dictionary + { + ["DockerUpdateGuard:DisplayVersion"] = "2.0.0" + }; + var prerenderContext = CreateContext(prerenderService, settings, new DockerHubOptions()); + var interactiveContext = CreateContext(interactiveService, settings, new DockerHubOptions()); + + await using (prerenderContext) + await using (interactiveContext) + { + var prerender = prerenderContext.Render(parameters => parameters.Add(layout => layout.Body, "body")); + + await prerender.WaitForAssertionAsync(() => Assert.HasCount(1, prerender.FindAll($"{HeaderNavigation} a[href=\"base-images\"]"), "The base-image check must have finished"), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + + var persistentState = prerenderContext.GetPersistentComponentState(); + + persistentState.TriggerOnPersisting(); + + Assert.IsTrue(persistentState.TryTake(StateKey, out var persisted), "The first render must persist its navigation state"); + + interactiveContext.GetPersistentComponentState().Persist(StateKey, persisted!); + + var interactive = interactiveContext.Render(parameters => parameters.Add(layout => layout.Body, "body")); + + Assert.HasCount(1, interactive.FindAll($"{HeaderNavigation} a[href=\"base-images\"]"), "The interactive render must show the Base Images entry of the first render"); + + await prerenderService.Received(1).HasBaseImagesAsync(Arg.Any()).ConfigureAwait(false); + await interactiveService.DidNotReceive().HasBaseImagesAsync(Arg.Any()).ConfigureAwait(false); + } + } + + /// + /// Create a view service whose base-image check returns a value + /// + /// Whether shared base images exist + /// View service substitute + private static IApplicationViewService CreateViewService(bool hasBaseImages) + { + var viewService = Substitute.For(); + + viewService.HasBaseImagesAsync(Arg.Any()) + .Returns(Task.FromResult(hasBaseImages)); + + return viewService; + } + + /// + /// Create a bUnit test context wired up with the services required to render the layout + /// + /// View service the layout reads + /// Configuration values + /// Docker Hub options + /// Configured test context + private static BunitContext CreateContext(IApplicationViewService viewService, Dictionary settings, DockerHubOptions dockerHub) + { + var testContext = BlazorTestContextFactory.Create(); + + testContext.Services.AddSingleton(viewService); + testContext.Services.AddSingleton(new DashboardRefreshState()); + testContext.Services.AddSingleton(new ConfigurationBuilder().AddInMemoryCollection(settings).Build()); + testContext.Services.AddSingleton(Options.Create(new DockerUpdateGuardOptions + { + DockerHub = dockerHub + })); + testContext.Services.AddSingleton(Substitute.For()); + testContext.Services.AddSingleton(new ResourceAssetCollection([])); + + return testContext; + } + + #endregion // Methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/MainLayoutRenderTests.cs b/src/Tests/DockerUpdateGuard.Tests/MainLayoutRenderTests.cs index b9a30894..070e654f 100644 --- a/src/Tests/DockerUpdateGuard.Tests/MainLayoutRenderTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/MainLayoutRenderTests.cs @@ -1,3 +1,5 @@ +using System.Runtime.CompilerServices; + using Bunit; using Bunit.TestDoubles; @@ -8,12 +10,15 @@ using DockerUpdateGuard.UI; using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Web; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using Microsoft.JSInterop; using MudBlazor; +using MudBlazor.Services; using MudBlazor.Utilities; using NSubstitute; @@ -26,8 +31,62 @@ namespace DockerUpdateGuard.Tests; [TestClass] public class MainLayoutRenderTests { + #region Constants + + /// + /// Selector of the main navigation, in the header row and in the drawer + /// + private const string MainNavigation = "nav[aria-label=\"Main\"]"; + + /// + /// Selector of the navigation row in the header + /// + private const string HeaderNavigation = "header.app-header " + MainNavigation; + + /// + /// Selector of the navigation in the drawer + /// + private const string DrawerNavigation = ".app-drawer " + MainNavigation; + + /// + /// Selector of the menu button + /// + private const string MenuButton = ".app-header__menu-button"; + + /// + /// Selector of the drawer + /// + private const string Drawer = ".app-drawer"; + + /// + /// Name of the attribute bUnit writes for a key-down handler + /// + private const string KeyDownAttribute = "blazor:onkeydown"; + + /// + /// Entries of the navigation with every optional entry shown, as label and link target + /// + private const string AllEntries = "Dashboard|;My Images|my-images;Observed Images|observed-images;Runtime Containers|runtime-containers;Docker Instances|docker-instances;Base Images|base-images;Vulnerabilities|vulnerabilities;Scan History|scan-history"; + + /// + /// Entries of the navigation without the optional entries, as label and link target + /// + private const string MandatoryEntries = "Dashboard|;Observed Images|observed-images;Runtime Containers|runtime-containers;Docker Instances|docker-instances;Vulnerabilities|vulnerabilities;Scan History|scan-history"; + + /// + /// Outer shield of the brand assets + /// + private const string ShieldPath = "M64 8c20 14 37 18 52 20v34c0 28-18 47-52 58C30 109 12 90 12 62V28c15-2 32-6 52-20Z"; + + #endregion // Constants + #region Fields + /// + /// Link targets that lead to the dashboard + /// + private static readonly string[] _brandTargets = [string.Empty, "/"]; + /// /// Inter stack of the theme /// @@ -43,174 +102,632 @@ public class MainLayoutRenderTests #region Methods /// - /// Verify the compact status pill and the full meta cards are rendered once the dashboard summary is available + /// Verify the header holds, in this order, the menu button, the brand link with the shield mark and the product name, the navigation row and the dark-mode toggle /// /// Task [TestMethod] - public async Task MainLayoutWithDashboardSummaryRendersCompactPillAndFullMeta() + [TestCategory("AC1")] + public async Task MainLayoutRendersHeaderWithBrandNavigationAndThemeToggle() { - var testContext = CreateContext(new DashboardSummaryViewData - { - ObservedImageCount = 2, - MyImageCount = 1, - RuntimeContainerCount = 4, - }); + var testContext = CreateContext(); await using (testContext) { - var component = testContext.Render(parameters => parameters.Add(layout => layout.Body, string.Empty)); - var markup = component.Markup; + var component = RenderLayout(testContext, "body marker"); + var header = component.Find("header.app-header"); + var inner = header.QuerySelector(".app-header__inner"); + + Assert.IsNotNull(inner, "The header must hold the inner row that centers its content"); + + var children = inner.Children.ToList(); + var menuIndex = children.FindIndex(child => child.ClassList.Contains("app-header__menu-button")); + var brandIndex = children.FindIndex(child => child.ClassList.Contains("app-brand")); + var navigationIndex = children.FindIndex(child => child.ClassList.Contains("app-nav")); + var toggleIndex = children.FindIndex(child => child.ClassList.Contains("app-topbar__theme-toggle")); + + Assert.IsGreaterThanOrEqualTo(0, menuIndex, "The header row must hold the menu button"); + Assert.IsGreaterThan(menuIndex, brandIndex, "The brand must follow the menu button"); + Assert.IsGreaterThan(brandIndex, navigationIndex, "The navigation row must follow the brand"); + Assert.IsGreaterThan(navigationIndex, toggleIndex, "The dark-mode toggle must follow the navigation row"); + Assert.AreEqual("Toggle navigation", children[menuIndex].GetAttribute("aria-label"), "The menu button must be named for assistive technology"); + Assert.AreEqual("Toggle dark mode", children[toggleIndex].GetAttribute("aria-label"), "The dark-mode toggle must keep its name"); + Assert.AreEqual("A", children[brandIndex].TagName, "The brand must be a link"); + Assert.Contains(children[brandIndex].GetAttribute("href") ?? "?", _brandTargets, "The brand must link to the dashboard"); + Assert.AreEqual("DockerUpdateGuard", children[brandIndex].QuerySelector(".app-brand__title")?.TextContent.Trim(), "The brand must show the product name"); + Assert.IsNotNull(header.QuerySelector(MainNavigation), "The navigation row must be inside the header"); + Assert.IsNull(component.Find("main.page-container").QuerySelector("header"), "The header must not be part of the content"); + } + } + + /// + /// Verify the row and the drawer list the same entries, in order, with the optional entries when their conditions hold + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task MainLayoutRendersSameEntriesInRowAndDrawer() + { + var viewService = CreateViewService(hasBaseImages: true); + var testContext = CreateContext(viewService, + dockerHub: new DockerHubOptions + { + UserName = "alice", + Pat = "token" + }); + + await using (testContext) + { + var component = RenderLayout(testContext); + + await component.WaitForAssertionAsync(() => Assert.AreEqual(AllEntries, ReadEntries(component, HeaderNavigation), "The row must list every entry"), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + + Assert.HasCount(2, component.FindAll(MainNavigation), "The layout must render the navigation twice, in the row and in the drawer"); + Assert.AreEqual(AllEntries, ReadEntries(component, DrawerNavigation), "The drawer must list the same entries as the row"); + } + } + + /// + /// Verify the entries without the optional ones are the same in the row and the drawer when neither condition holds + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task MainLayoutWithoutOptionalConditionsRendersMandatoryEntriesInRowAndDrawer() + { + var testContext = CreateContext(); + + await using (testContext) + { + var component = RenderLayout(testContext); + + await component.WaitForAssertionAsync(() => Assert.AreEqual(MandatoryEntries, ReadEntries(component, HeaderNavigation), "The row must list the mandatory entries"), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); - Assert.Contains("app-topbar__meta--full", markup, "The full meta cards must render when the dashboard summary is available"); - Assert.Contains("app-topbar__meta--compact", markup, "The compact status pill must render when the dashboard summary is available"); - Assert.Contains("app-topbar__pill", markup, "The compact status pill chip must render when the dashboard summary is available"); + Assert.AreEqual(MandatoryEntries, ReadEntries(component, DrawerNavigation), "The drawer must list the same entries as the row"); + } + } - var menu = component.FindComponent(); + /// + /// Verify the base-image check runs once although the navigation is rendered twice + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task MainLayoutCallsBaseImageCheckOnce() + { + var viewService = CreateViewService(hasBaseImages: true); + var testContext = CreateContext(viewService); - await component.InvokeAsync(() => menu.Instance.OpenMenuAsync(EventArgs.Empty)).ConfigureAwait(false); + await using (testContext) + { + var component = RenderLayout(testContext); - Assert.Contains("app-topbar__meta-popover", component.Markup, "Opening the compact pill must reveal the popover exposing both metrics"); + await component.WaitForAssertionAsync(() => Assert.HasCount(2, component.FindAll("a[href=\"base-images\"]"), "The Base Images entry must be shown in the row and the drawer"), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + await viewService.Received(1).HasBaseImagesAsync(Arg.Any()).ConfigureAwait(false); } } /// - /// Verify the last activity of the top bar is rendered as a UTC timestamp + /// Verify a failing base-image check hides the Base Images entry in the row and the drawer, keeps the other entries, shows no error text and logs the failure once + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task MainLayoutBaseImageCheckFailureHidesEntryAndLogs() + { + var exception = new InvalidOperationException("secret text"); + var logger = new TestLogger(); + var viewService = Substitute.For(); + + viewService.HasBaseImagesAsync(Arg.Any()) + .Returns(Task.FromException(exception)); + + var testContext = CreateContext(viewService); + + await using (testContext) + { + testContext.Services.AddSingleton>(logger); + + var component = RenderLayout(testContext, "layout body marker"); + + await component.WaitForAssertionAsync(() => DetailPageAssert.AssertLoadLoggedOnce(logger, "LoadNavigation", exception), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + + Assert.AreEqual(MandatoryEntries, ReadEntries(component, HeaderNavigation), "The row must keep the other entries and hide Base Images"); + Assert.AreEqual(MandatoryEntries, ReadEntries(component, DrawerNavigation), "The drawer must keep the other entries and hide Base Images"); + Assert.Contains("layout body marker", component.Markup, "The layout must render its body"); + Assert.DoesNotContain("secret text", component.Markup, "The layout must not show the exception's text"); + } + } + + /// + /// Verify a navigation moves the active entry in the row and the drawer, once the layout renders the new page /// /// Task [TestMethod] [TestCategory("AC3")] - public async Task MainLayoutWithLatestScanRendersLastActivityInUtc() + public async Task MainLayoutNavigationMovesActiveEntryToTheNewRoute() { - var testContext = CreateContext(new DashboardSummaryViewData - { - LatestScan = new ScanHistoryItemData - { - StartedAtUtc = new DateTimeOffset(2026, 11, 24, 0, 27, 0, TimeSpan.FromHours(2)), - }, - }); + var testContext = CreateContext(); await using (testContext) { - var component = testContext.Render(parameters => parameters.Add(layout => layout.Body, string.Empty)); + var component = RenderLayout(testContext, "first page"); + + Assert.AreEqual("Dashboard", ReadActiveEntries(component, HeaderNavigation), "The dashboard must be the active entry of the row at the base address"); + Assert.AreEqual("Dashboard", ReadActiveEntries(component, DrawerNavigation), "The dashboard must be the active entry of the drawer at the base address"); + + await component.InvokeAsync(() => testContext.Services.GetRequiredService().NavigateTo("vulnerabilities?page=2")).ConfigureAwait(false); - Assert.Contains("2026-11-23 22:27 UTC", component.Markup, "The last activity must be rendered in UTC with the zone suffix"); + component.Render(parameters => parameters.Add(layout => layout.Body, "second page")); + + await component.WaitForAssertionAsync(() => Assert.AreEqual("Vulnerabilities", ReadActiveEntries(component, HeaderNavigation), "The row must mark the entry of the new route"), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + + Assert.AreEqual("Vulnerabilities", ReadActiveEntries(component, DrawerNavigation), "The drawer must mark the entry of the new route"); } } /// - /// Verify a fixed-size skeleton is rendered while the dashboard summary is still loading + /// Verify the drawer starts closed on every page load /// /// Task [TestMethod] - public async Task MainLayoutWithoutDashboardSummaryRendersLoadingSkeleton() + [TestCategory("AC4")] + public async Task MainLayoutDrawerStartsClosed() { - var testContext = CreateContext(dashboardSummary: null); + var testContext = CreateContext(); await using (testContext) { - var component = testContext.Render(parameters => parameters.Add(layout => layout.Body, string.Empty)); + var component = RenderLayout(testContext); - Assert.Contains("app-topbar__status-skeleton", component.Markup, "A skeleton must render while the dashboard summary is loading to avoid a top-bar height jump"); + Assert.IsFalse(IsDrawerOpen(component), "The drawer must be closed when a page loads"); + Assert.IsTrue(IsDrawerClosed(component), "The drawer must carry the closed state of the temporary drawer"); } } /// - /// Verify toggling the dark-mode button applies the dark layout class + /// Verify the menu button opens the drawer with the entries and the version line, and a click outside, left at the default of the drawer, closes it /// /// Task [TestMethod] - public async Task MainLayoutTogglingDarkModeButtonAppliesDarkLayoutClass() + [TestCategory("AC4")] + public async Task MainLayoutMenuButtonOpensDrawerWithEntriesAndVersion() { - var testContext = CreateContext(dashboardSummary: null); + var testContext = CreateContext(settings: new Dictionary + { + ["DockerUpdateGuard:DisplayVersion"] = "1.2.3" + }); await using (testContext) { - var component = testContext.Render(parameters => parameters.Add(layout => layout.Body, string.Empty)); + var component = RenderLayout(testContext); - Assert.DoesNotContain("dug-dark", component.Markup, "The layout must start in light mode when no preference is stored and the system reports light mode"); + await component.Find(MenuButton).ClickAsync().ConfigureAwait(false); - await component.Find(".app-topbar__theme-toggle").ClickAsync().ConfigureAwait(false); + var drawer = component.FindComponent().Instance; + var version = component.Find($"{Drawer} .app-version"); - Assert.Contains("dug-dark", component.Markup, "Toggling the dark-mode button must apply the dark layout class"); + Assert.IsTrue(IsDrawerOpen(component), "The menu button must open the drawer"); + Assert.AreEqual(DrawerVariant.Temporary, drawer.Variant, "The drawer must be temporary, over the content"); + Assert.AreEqual(Anchor.Start, drawer.Anchor, "The drawer must open from the left"); + Assert.IsTrue(drawer.OverlayAutoClose, "A click on the overlay must close the drawer, the default of the drawer"); + Assert.AreEqual(MandatoryEntries, ReadEntries(component, DrawerNavigation), "The drawer must list the entries"); + Assert.AreEqual("DockerUpdateGuard 1.2.3", version.TextContent.Trim(), "The drawer must end with the version line"); + } + } + + /// + /// Verify following an entry of the drawer closes it + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task MainLayoutFollowingEntryClosesDrawer() + { + var testContext = CreateContext(); + + await using (testContext) + { + var component = RenderLayout(testContext); + + await component.Find(MenuButton).ClickAsync().ConfigureAwait(false); + + Assert.IsTrue(IsDrawerOpen(component), "The drawer must be open before an entry is followed"); + + await component.Find($"{DrawerNavigation} a[href=\"vulnerabilities\"]").ClickAsync().ConfigureAwait(false); + + Assert.IsFalse(IsDrawerOpen(component), "Following an entry must close the drawer"); + } + } + + /// + /// Verify Escape closes the open drawer and another key does not + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task MainLayoutEscapeClosesDrawer() + { + var testContext = CreateContext(); + + await using (testContext) + { + var component = RenderLayout(testContext); + + await component.Find(MenuButton).ClickAsync().ConfigureAwait(false); + await FindKeyDownHandlers(component).Single().KeyDownAsync(new KeyboardEventArgs + { + Key = "a" + }).ConfigureAwait(false); + + Assert.IsTrue(IsDrawerOpen(component), "A key other than Escape must not close the drawer"); + + await FindKeyDownHandlers(component).Single().KeyDownAsync(new KeyboardEventArgs + { + Key = "Escape" + }).ConfigureAwait(false); + + Assert.IsFalse(IsDrawerOpen(component), "Escape must close the open drawer"); + } + } + + /// + /// Verify no key-down handler is attached while the drawer is closed, so no keystroke of a page goes to the server, and one is attached while it is open + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task MainLayoutAttachesKeyDownHandlerOnlyWhileDrawerIsOpen() + { + var testContext = CreateContext(); + + await using (testContext) + { + var component = RenderLayout(testContext); + + Assert.IsEmpty(FindKeyDownHandlers(component), "No key-down handler may be attached while the drawer is closed"); + + await component.Find(MenuButton).ClickAsync().ConfigureAwait(false); + + Assert.HasCount(1, FindKeyDownHandlers(component), "Exactly one key-down handler must be attached while the drawer is open"); + + await component.Find(MenuButton).ClickAsync().ConfigureAwait(false); + + Assert.IsEmpty(FindKeyDownHandlers(component), "The key-down handler must be detached again once the drawer is closed"); } } /// - /// Verify a failed first summary load renders the layout with its body, hides the summary and the skeleton, and logs the failure once + /// Verify the layout subscribes to the window width without the breakpoint-only restriction and without an immediate event, and unsubscribes when it is disposed + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task MainLayoutSubscribesToWindowWidthAndUnsubscribesOnDispose() + { + var callback = new StrongBox?>(); + var viewport = CreateViewportService(callback); + var testContext = CreateContext(viewport: viewport); + + await using (testContext) + { + var component = RenderLayout(testContext); + + await component.WaitForAssertionAsync(() => Assert.IsNotNull(callback.Value, "The layout must subscribe to the viewport service"), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + + await viewport.Received(1).SubscribeAsync(Arg.Any(), Arg.Any>(), Arg.Is(options => options.NotifyOnBreakpointOnly == false), false).ConfigureAwait(false); + + await component.Instance.DisposeAsync().ConfigureAwait(false); + await viewport.Received(1).UnsubscribeAsync(Arg.Any()).ConfigureAwait(false); + } + } + + /// + /// Verify a window that reaches the wide layout closes the open drawer and a narrower one does not + /// + /// Window width in pixels + /// Whether the drawer is still open afterwards + /// Task + [TestMethod] + [TestCategory("AC4")] + [DataRow(1360, false)] + [DataRow(1920, false)] + [DataRow(1359, true)] + [DataRow(390, true)] + public async Task MainLayoutWideViewportClosesOpenDrawer(int width, bool expectedOpen) + { + var callback = new StrongBox?>(); + var testContext = CreateContext(viewport: CreateViewportService(callback)); + + await using (testContext) + { + var component = RenderLayout(testContext); + + await component.WaitForAssertionAsync(() => Assert.IsNotNull(callback.Value, "The layout must subscribe to the viewport service"), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + await component.Find(MenuButton).ClickAsync().ConfigureAwait(false); + await RaiseViewportChangeAsync(component, callback, width).ConfigureAwait(false); + + Assert.AreEqual(expectedOpen, IsDrawerOpen(component), $"A window of {width} px must {(expectedOpen ? "keep" : "close")} the open drawer"); + } + } + + /// + /// Verify a window narrowed again after it was widened shows the drawer closed + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task MainLayoutNarrowingAfterWideningKeepsDrawerClosed() + { + var callback = new StrongBox?>(); + var testContext = CreateContext(viewport: CreateViewportService(callback)); + + await using (testContext) + { + var component = RenderLayout(testContext); + + await component.WaitForAssertionAsync(() => Assert.IsNotNull(callback.Value, "The layout must subscribe to the viewport service"), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + await component.Find(MenuButton).ClickAsync().ConfigureAwait(false); + await RaiseViewportChangeAsync(component, callback, 1400).ConfigureAwait(false); + await RaiseViewportChangeAsync(component, callback, 1000).ConfigureAwait(false); + + Assert.IsFalse(IsDrawerOpen(component), "The drawer must stay closed when the window is narrowed again"); + } + } + + /// + /// Verify the drawer's width is set through the drawer itself or its custom property, because the closed drawer is moved off screen by that width + /// + /// Task + [TestMethod] + [TestCategory("AC9")] + public async Task MainLayoutDrawerDefinesItsWidthWhereTheClosedDrawerLeavesTheScreen() + { + var testContext = CreateContext(); + + await using (testContext) + { + var component = RenderLayout(testContext); + var style = component.Find(Drawer).GetAttribute("style") ?? string.Empty; + var rule = StylesheetReader.GetDeclarations(StylesheetReader.ReadHostFile("wwwroot/app.css"), Drawer); + + Assert.IsTrue(style.Contains("--mud-drawer-width", StringComparison.Ordinal) || rule.ContainsKey("--mud-drawer-width"), + "The drawer width must be set as --mud-drawer-width (the Width of the drawer or its rule), not by width alone, so the closed drawer leaves the screen completely"); + } + } + + /// + /// Verify the page ends with the version line after its body, with a configured and with a resolved version + /// + /// Configured display version, or null when unset + /// Expected start of the version line + /// Task + [TestMethod] + [TestCategory("AC6")] + [DataRow("1.2.3", "DockerUpdateGuard 1.2.3")] + [DataRow(null, "DockerUpdateGuard ")] + public async Task MainLayoutRendersVersionLineAfterBody(string? configuredVersion, string expectedStart) + { + var settings = configuredVersion is null + ? null + : new Dictionary + { + ["DockerUpdateGuard:DisplayVersion"] = configuredVersion + }; + var testContext = CreateContext(settings: settings); + + await using (testContext) + { + var component = RenderLayout(testContext, "layout body marker"); + var content = component.Find("main.page-container"); + var version = content.LastElementChild; + var text = version?.TextContent.Trim() ?? string.Empty; + + Assert.IsNotNull(version, "The content must end with an element"); + Assert.IsTrue(version.ClassList.Contains("app-version"), "The last element of the content must be the version line"); + Assert.StartsWith(expectedStart, text, "The version line must name the product and the configured version, when there is one"); + Assert.IsLessThan(content.TextContent.IndexOf(text, StringComparison.Ordinal), content.TextContent.IndexOf("layout body marker", StringComparison.Ordinal), "The version line must come after the body"); + + Assert.AreNotEqual("DockerUpdateGuard unknown", text, "The version must be resolved, not unknown, in a test host with an assembly version"); + Assert.HasCount(2, component.FindAll(".app-version"), "The version line must be at the end of the page and at the bottom of the drawer"); + } + } + + /// + /// Verify the layout shows neither the protected-asset count nor the last activity and asks the view service only for the base-image check /// /// Task [TestMethod] [TestCategory("AC5")] - public async Task MainLayoutSummaryLoadFailureRendersBodyWithoutSummaryAndLogs() + public async Task MainLayoutRendersNoTopBarValues() { - var exception = new InvalidOperationException("secret text"); - var logger = new TestLogger(); - var viewService = Substitute.For(); + var viewService = CreateViewService(hasBaseImages: true); + var testContext = CreateContext(viewService); - viewService.GetDashboardSummaryAsync(Arg.Any()) - .Returns(Task.FromException(exception)); - viewService.HasBaseImagesAsync(Arg.Any()) - .Returns(Task.FromResult(false)); + await using (testContext) + { + var component = RenderLayout(testContext, "layout body marker"); + + await component.WaitForAssertionAsync(() => Assert.HasCount(2, component.FindAll("a[href=\"base-images\"]"), "The navigation must be loaded"), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + + Assert.DoesNotContain("Protected assets", component.Markup, "The layout must not show the protected-asset count"); + Assert.DoesNotContain("Last activity", component.Markup, "The layout must not show the last activity"); + Assert.AreEqual(string.Empty, string.Join(", ", ReadRequestedMethods(viewService).Where(method => method != nameof(IApplicationViewService.HasBaseImagesAsync))), "The layout must request nothing from the view service but the base-image check"); + } + } + /// + /// Verify neither a navigation nor the dashboard refresh signal makes the layout call the view service again + /// + /// Task + [TestMethod] + [TestCategory("AC5")] + public async Task MainLayoutNavigationAndRefreshSignalLoadNothing() + { + var viewService = CreateViewService(hasBaseImages: true); var testContext = CreateContext(viewService); await using (testContext) { - testContext.Services.AddSingleton>(logger); + var component = RenderLayout(testContext, "first page"); - var component = testContext.Render(parameters => parameters.Add(layout => layout.Body, "layout body marker")); + await component.WaitForAssertionAsync(() => Assert.HasCount(1, ReadRequestedMethods(viewService), "The navigation must be loaded once"), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); - await component.WaitForAssertionAsync(() => DetailPageAssert.AssertLoadLoggedOnce(logger, "LoadDashboardSummary", exception), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + await component.InvokeAsync(() => testContext.Services.GetRequiredService().NavigateTo("vulnerabilities")).ConfigureAwait(false); - Assert.Contains("layout body marker", component.Markup, "The layout must render its body"); - Assert.DoesNotContain("app-topbar__status-skeleton", component.Markup, "A failed load must not show the status skeleton"); - Assert.DoesNotContain("Protected assets", component.Markup, "A failed load must not show the summary values"); - Assert.DoesNotContain("Last activity", component.Markup, "A failed load must not show the summary values"); - Assert.DoesNotContain("secret text", component.Markup, "The layout must not show the exception's text"); + component.Render(parameters => parameters.Add(layout => layout.Body, "second page")); + + await component.InvokeAsync(() => testContext.Services.GetRequiredService().NotifyChanged()).ConfigureAwait(false); + + Assert.HasCount(1, ReadRequestedMethods(viewService), "A navigation and a refresh signal must not call the view service again"); + Assert.Contains("second page", component.Markup, "The layout must render the new page"); } } /// - /// Verify a reload on navigation that fails keeps the top bar values and logs the failure once + /// Verify the display version falls back to the environment variable when no configuration value is set, and ignores a blank one + /// + /// Value of the environment variable + /// Expected version text, or null when the resolved assembly version is expected + /// Task + [TestMethod] + [TestCategory("AC6")] + [DataRow("4.5.6", "4.5.6")] + [DataRow(" ", null)] + public async Task MainLayoutDisplayVersionComesFromEnvironmentVariable(string environmentValue, string? expectedVersion) + { + const string variableName = "DockerUpdateGuard__DisplayVersion"; + + var previousValue = Environment.GetEnvironmentVariable(variableName); + + try + { + Environment.SetEnvironmentVariable(variableName, environmentValue); + + var testContext = CreateContext(); + + await using (testContext) + { + var component = RenderLayout(testContext); + var text = component.Find("main.page-container .app-version").TextContent.Trim(); + + if (expectedVersion is null) + { + Assert.DoesNotContain("DockerUpdateGuard unknown", text, "A blank environment variable must fall through to the assembly version"); + Assert.StartsWith("DockerUpdateGuard ", text, "The version line must name the product"); + Assert.IsGreaterThan("DockerUpdateGuard ".Length, text.Length, "The version line must carry a resolved version"); + } + else + { + Assert.AreEqual($"DockerUpdateGuard {expectedVersion}", text, "The environment variable must supply the version"); + } + } + } + finally + { + Environment.SetEnvironmentVariable(variableName, previousValue); + } + } + + /// + /// Verify disposing the layout after its circuit is gone does not throw + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task MainLayoutDisposeAfterDisconnectedCircuitDoesNotThrow() + { + var callback = new StrongBox?>(); + var viewport = CreateViewportService(callback); + + viewport.UnsubscribeAsync(Arg.Any()) + .Returns(Task.FromException(new JSDisconnectedException("The circuit is gone"))); + + var testContext = CreateContext(viewport: viewport); + + await using (testContext) + { + var component = RenderLayout(testContext); + + await component.WaitForAssertionAsync(() => Assert.IsNotNull(callback.Value, "The layout must subscribe to the viewport service"), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + await component.Instance.DisposeAsync().ConfigureAwait(false); + await viewport.Received(1).UnsubscribeAsync(Arg.Any()).ConfigureAwait(false); + } + } + + /// + /// Verify toggling the dark-mode button applies the dark layout class /// /// Task [TestMethod] [TestCategory("AC7")] - public async Task MainLayoutFailedReloadOnNavigationKeepsSummaryAndLogs() + public async Task MainLayoutTogglingDarkModeButtonAppliesDarkLayoutClass() { - var exception = new InvalidOperationException("secret text"); - var logger = new TestLogger(); - var viewService = Substitute.For(); - var summary = new DashboardSummaryViewData - { - LatestScan = new ScanHistoryItemData - { - StartedAtUtc = new DateTimeOffset(2026, 11, 24, 0, 27, 0, TimeSpan.FromHours(2)), - }, - }; - - viewService.GetDashboardSummaryAsync(Arg.Any()) - .Returns(Task.FromResult(summary), Task.FromException(exception)); - viewService.HasBaseImagesAsync(Arg.Any()) - .Returns(Task.FromResult(false)); + var testContext = CreateContext(); - var testContext = CreateContext(viewService); + await using (testContext) + { + var component = RenderLayout(testContext); + + Assert.DoesNotContain("dug-dark", component.Markup, "The layout must start in light mode when no preference is stored and the system reports light mode"); + + await component.Find(".app-topbar__theme-toggle").ClickAsync().ConfigureAwait(false); + + Assert.Contains("dug-dark", component.Markup, "Toggling the dark-mode button must apply the dark layout class"); + } + } + + /// + /// Verify the toggle in the header shows a moon in the light theme and a sun in the dark theme + /// + /// Task + [TestMethod] + [TestCategory("AC7")] + public async Task MainLayoutThemeToggleShowsMoonInLightAndSunInDark() + { + var testContext = CreateContext(); await using (testContext) { - testContext.Services.AddSingleton>(logger); + var component = RenderLayout(testContext); - var component = testContext.Render(parameters => parameters.Add(layout => layout.Body, string.Empty)); - var navigation = testContext.Services.GetRequiredService(); + Assert.IsNotNull(component.Find("header.app-header").QuerySelector(".app-topbar__theme-toggle"), "The toggle must be in the header"); + Assert.AreEqual(Icons.Material.Filled.DarkMode, FindToggle(component).Instance.Icon, "The light theme must offer the moon"); - Assert.Contains("2026-11-23 22:27 UTC", component.Markup, "The first load must show the summary"); + await component.Find(".app-topbar__theme-toggle").ClickAsync().ConfigureAwait(false); - await component.InvokeAsync(() => navigation.NavigateTo("/elsewhere")).ConfigureAwait(false); - await component.WaitForAssertionAsync(() => DetailPageAssert.AssertLoadLoggedOnce(logger, "LoadDashboardSummary", exception), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + Assert.AreEqual(Icons.Material.Filled.LightMode, FindToggle(component).Instance.Icon, "The dark theme must offer the sun"); + Assert.AreEqual("Toggle dark mode", component.Find(".app-topbar__theme-toggle").GetAttribute("aria-label"), "The toggle must keep its name"); + } + } - Assert.Contains("2026-11-23 22:27 UTC", component.Markup, "A failed reload must keep the top bar values"); - Assert.DoesNotContain("app-topbar__status-skeleton", component.Markup, "A failed reload must not show the status skeleton"); - Assert.DoesNotContain("secret text", component.Markup, "The layout must not show the exception's text"); + /// + /// Verify the brand mark is an inline flat shield with the accessible name, filled by the current color that the stylesheet sets to the primary token + /// + /// Task + [TestMethod] + [TestCategory("AC8")] + public async Task MainLayoutBrandMarkIsInlineShieldInPrimaryColor() + { + var testContext = CreateContext(); + + await using (testContext) + { + var component = RenderLayout(testContext); + var brand = component.Find("header.app-header a.app-brand"); + var mark = brand.QuerySelector("svg.app-brand__mark"); + + Assert.IsNotNull(mark, "The brand must hold an inline svg mark"); + Assert.IsNull(brand.QuerySelector("img"), "The brand mark must not be an image file"); + Assert.AreEqual("img", mark.GetAttribute("role"), "The mark must be exposed as an image"); + Assert.AreEqual("DockerUpdateGuard logo", mark.GetAttribute("aria-label"), "The mark must have the accessible name of the logo"); + Assert.AreEqual("0 0 128 128", mark.GetAttribute("viewBox"), "The mark must use the viewbox of the brand shield"); + + var paths = mark.QuerySelectorAll("path"); + + Assert.HasCount(1, paths, "The mark must be the single outer shield"); + Assert.AreEqual(ShieldPath, paths[0].GetAttribute("d"), "The mark must be the outer shield of the brand assets"); + Assert.AreEqual("currentColor", paths[0].GetAttribute("fill"), "The shield must take the text color the stylesheet sets to the primary token"); + Assert.IsEmpty(mark.QuerySelectorAll("linearGradient, text, defs"), "The mark must have no gradient and no letters"); } } @@ -370,7 +887,7 @@ public async Task MainLayoutThemeSwitchesOffElevationShadows() /// Theme of the provider private static async Task RenderThemeAsync(bool toggleDarkMode) { - var testContext = CreateContext(dashboardSummary: null); + var testContext = CreateContext(); await using (testContext) { @@ -461,35 +978,159 @@ private static string ToHex(MudColor color) } /// - /// Create a bUnit test context wired up with the services required to render the layout + /// Find the dark-mode toggle component /// - /// Dashboard summary returned by the view service, or null to keep the loading state - /// Configured test context - private static BunitContext CreateContext(DashboardSummaryViewData? dashboardSummary) + /// Rendered layout + /// Toggle button + private static IRenderedComponent FindToggle(IRenderedComponent component) + { + return component.FindComponents().Single(button => button.Instance.Class?.Contains("app-topbar__theme-toggle", StringComparison.Ordinal) == true); + } + + /// + /// Read the entries of a navigation as label and link target + /// + /// Rendered layout + /// Selector of the navigation + /// Entries separated by a semicolon, each as label, a vertical bar and the link target + private static string ReadEntries(IRenderedComponent component, string navigationSelector) + { + return string.Join(";", component.Find(navigationSelector).QuerySelectorAll("a").Select(link => $"{link.TextContent.Trim()}|{link.GetAttribute("href")}")); + } + + /// + /// Read the labels of the entries a navigation marks as the current page + /// + /// Rendered layout + /// Selector of the navigation + /// Labels separated by a semicolon + private static string ReadActiveEntries(IRenderedComponent component, string navigationSelector) + { + return string.Join(";", component.Find(navigationSelector).QuerySelectorAll("a[aria-current]").Select(link => link.TextContent.Trim())); + } + + /// + /// Find the elements with a key-down handler + /// + /// Rendered layout + /// Elements that handle key-down events + private static List FindKeyDownHandlers(IRenderedComponent component) + { + return [.. component.FindAll("*").Where(element => element.HasAttribute(KeyDownAttribute))]; + } + + /// + /// Tell whether the drawer is open + /// + /// Rendered layout + /// True when the drawer carries the open state + private static bool IsDrawerOpen(IRenderedComponent component) + { + return component.Find(Drawer).ClassList.Contains("mud-drawer--open"); + } + + /// + /// Tell whether the drawer is closed + /// + /// Rendered layout + /// True when the drawer carries the closed state + private static bool IsDrawerClosed(IRenderedComponent component) + { + return component.Find(Drawer).ClassList.Contains("mud-drawer--closed"); + } + + /// + /// Report a window width to the layout through the callback it registered + /// + /// Rendered layout + /// Callback the layout registered + /// Window width in pixels + /// Task + private static async Task RaiseViewportChangeAsync(IRenderedComponent component, StrongBox?> callback, int width) + { + var arguments = new BrowserViewportEventArgs(Guid.NewGuid(), + new BrowserWindowSize + { + Width = width, + Height = 800, + }, + Breakpoint.Xl, + false); + + await component.InvokeAsync(() => callback.Value!(arguments)).ConfigureAwait(false); + } + + /// + /// Render the layout with a body + /// + /// bUnit test context + /// Body text of the page + /// Rendered layout + private static IRenderedComponent RenderLayout(BunitContext testContext, string body = "") + { + return testContext.Render(parameters => parameters.Add(layout => layout.Body, body)); + } + + /// + /// Read the names of the methods called on a view service substitute + /// + /// View service substitute + /// One method name per call + private static List ReadRequestedMethods(IApplicationViewService viewService) + { + return [.. viewService.ReceivedCalls().Select(call => call.GetMethodInfo().Name)]; + } + + /// + /// Create a view service whose base-image check returns a value + /// + /// Whether shared base images exist + /// View service substitute + private static IApplicationViewService CreateViewService(bool hasBaseImages) { var viewService = Substitute.For(); - viewService.GetDashboardSummaryAsync(Arg.Any()) - .Returns(Task.FromResult(dashboardSummary!)); viewService.HasBaseImagesAsync(Arg.Any()) - .Returns(Task.FromResult(false)); + .Returns(Task.FromResult(hasBaseImages)); - return CreateContext(viewService); + return viewService; } /// - /// Create a bUnit test context wired up with the services required to render the layout around a view service + /// Create a viewport service substitute that hands the layout's callback to a holder /// - /// View service the layout reads + /// Holder of the callback the layout registers + /// Viewport service substitute + private static IBrowserViewportService CreateViewportService(StrongBox?> callback) + { + var viewport = Substitute.For(); + + viewport.SubscribeAsync(Arg.Any(), Arg.Do>(handler => callback.Value = handler), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); + + return viewport; + } + + /// + /// Create a bUnit test context wired up with the services required to render the layout + /// + /// View service the layout reads, or null for one without shared base images + /// Configuration values, or null for none + /// Docker Hub options, or null for none + /// Viewport service, or null for one that records nothing /// Configured test context - private static BunitContext CreateContext(IApplicationViewService viewService) + private static BunitContext CreateContext(IApplicationViewService? viewService = null, Dictionary? settings = null, DockerHubOptions? dockerHub = null, IBrowserViewportService? viewport = null) { var testContext = BlazorTestContextFactory.Create(); - testContext.Services.AddSingleton(viewService); + testContext.Services.AddSingleton(viewService ?? CreateViewService(hasBaseImages: false)); testContext.Services.AddSingleton(new DashboardRefreshState()); - testContext.Services.AddSingleton(new ConfigurationBuilder().Build()); - testContext.Services.AddSingleton(Options.Create(new DockerUpdateGuardOptions())); + testContext.Services.AddSingleton(new ConfigurationBuilder().AddInMemoryCollection(settings ?? []).Build()); + testContext.Services.AddSingleton(Options.Create(new DockerUpdateGuardOptions + { + DockerHub = dockerHub ?? new DockerHubOptions() + })); + testContext.Services.AddSingleton(viewport ?? CreateViewportService(new StrongBox?>())); testContext.Services.AddSingleton(new ResourceAssetCollection([])); testContext.AddBunitPersistentComponentState(); diff --git a/src/Tests/DockerUpdateGuard.Tests/MainLayoutTests.cs b/src/Tests/DockerUpdateGuard.Tests/MainLayoutTests.cs index c3e55d6f..982b6bdd 100644 --- a/src/Tests/DockerUpdateGuard.Tests/MainLayoutTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/MainLayoutTests.cs @@ -1,7 +1,7 @@ using System.Reflection; using DockerUpdateGuard.Components.Layout; -using DockerUpdateGuard.UI; +using DockerUpdateGuard.Configuration; namespace DockerUpdateGuard.Tests; @@ -14,56 +14,96 @@ public class MainLayoutTests #region Fields /// - /// Non-public protected-assets resolver + /// Non-public Docker Hub configuration visibility resolver /// - private static readonly MethodInfo _getProtectedAssetCountMethod = typeof(MainLayout).GetMethod("GetProtectedAssetCount", - BindingFlags.NonPublic | BindingFlags.Instance) - ?? throw new InvalidOperationException("MainLayout must expose the non-public GetProtectedAssetCount method"); - - private static readonly FieldInfo _dashboardSummaryField = typeof(MainLayout).GetField("_dashboardSummary", - BindingFlags.NonPublic | BindingFlags.Instance) - ?? throw new InvalidOperationException("MainLayout must expose the _dashboardSummary field for test setup"); + private static readonly MethodInfo _isDockerHubAccountConfiguredMethod = typeof(MainLayout).GetMethod("IsDockerHubAccountConfigured", + BindingFlags.NonPublic | BindingFlags.Static, + [typeof(DockerHubOptions)]) + ?? throw new InvalidOperationException("MainLayout must expose the non-public static IsDockerHubAccountConfigured(DockerHubOptions) overload for testability"); #endregion // Fields #region Methods /// - /// Verify protected assets include manual images, own images, and runtime containers + /// Verify the My Images link is shown when both credentials are present + /// + /// Docker Hub user name + /// Personal access token + [TestMethod] + [TestCategory("AC2")] + [DataRow("alice", "my-pat")] + [DataRow("bob", "another-token")] + [DataRow(" user ", " token ")] + public void MainLayoutIsDockerHubAccountConfiguredBothCredentialsSetReturnsTrue(string userName, string pat) + { + var options = new DockerHubOptions + { + UserName = userName, + Pat = pat, + }; + + var result = (bool)_isDockerHubAccountConfiguredMethod.Invoke(null, [options])!; + + Assert.IsTrue(result, $"My Images navigation must be visible when both UserName ('{userName}') and Pat are set"); + } + + /// + /// Verify the My Images link is hidden when UserName is absent /// + /// Missing or blank user name [TestMethod] - public void MainLayoutGetProtectedAssetCountReturnsCombinedObservedMyImagesAndRuntimeContainers() + [TestCategory("AC2")] + [DataRow(null)] + [DataRow("")] + [DataRow(" ")] + public void MainLayoutIsDockerHubAccountConfiguredMissingUserNameReturnsFalse(string? userName) { - var layout = new MainLayout(); + var options = new DockerHubOptions + { + UserName = userName, + Pat = "valid-token", + }; + + var result = (bool)_isDockerHubAccountConfiguredMethod.Invoke(null, [options])!; + + Assert.IsFalse(result, "My Images navigation must be hidden when UserName is absent or blank"); + } - _dashboardSummaryField.SetValue(layout, - new DashboardSummaryViewData - { - ObservedImageCount = 3, - MyImageCount = 2, - RuntimeContainerCount = 5, - }); + /// + /// Verify the My Images link is hidden when Pat is absent + /// + /// Missing or blank personal access token + [TestMethod] + [TestCategory("AC2")] + [DataRow(null)] + [DataRow("")] + [DataRow(" ")] + public void MainLayoutIsDockerHubAccountConfiguredMissingPatReturnsFalse(string? pat) + { + var options = new DockerHubOptions + { + UserName = "alice", + Pat = pat, + }; - var protectedAssetCount = (int)_getProtectedAssetCountMethod.Invoke(layout, [])!; + var result = (bool)_isDockerHubAccountConfiguredMethod.Invoke(null, [options])!; - Assert.AreEqual(10, - protectedAssetCount, - "Protected assets must include manual observed images, discovery-owned images, and runtime containers"); + Assert.IsFalse(result, "My Images navigation must be hidden when Pat is absent or blank"); } /// - /// Verify protected assets return zero when no dashboard summary is loaded yet + /// Verify the My Images link is hidden when neither credential is configured /// [TestMethod] - public void MainLayoutGetProtectedAssetCountWithoutDashboardSummaryReturnsZero() + [TestCategory("AC2")] + public void MainLayoutIsDockerHubAccountConfiguredBothCredentialsMissingReturnsFalse() { - var layout = new MainLayout(); + var options = new DockerHubOptions(); - var protectedAssetCount = (int)_getProtectedAssetCountMethod.Invoke(layout, [])!; + var result = (bool)_isDockerHubAccountConfiguredMethod.Invoke(null, [options])!; - Assert.AreEqual(0, - protectedAssetCount, - "Protected assets must return zero before the dashboard summary is available"); + Assert.IsFalse(result, "My Images navigation must be hidden when neither UserName nor Pat is configured"); } #endregion // Methods diff --git a/src/Tests/DockerUpdateGuard.Tests/NavMenuTests.cs b/src/Tests/DockerUpdateGuard.Tests/NavMenuTests.cs index d0e0112e..53750ae9 100644 --- a/src/Tests/DockerUpdateGuard.Tests/NavMenuTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/NavMenuTests.cs @@ -3,17 +3,10 @@ using Bunit; using DockerUpdateGuard.Components.Layout; -using DockerUpdateGuard.Configuration; -using DockerUpdateGuard.Tests.Data; using DockerUpdateGuard.Tests.Helper; -using DockerUpdateGuard.UI; -using Microsoft.Extensions.Configuration; +using Microsoft.AspNetCore.Components; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; - -using NSubstitute; namespace DockerUpdateGuard.Tests; @@ -23,230 +16,294 @@ namespace DockerUpdateGuard.Tests; [TestClass] public class NavMenuTests { - #region Fields + #region Constants /// - /// Non-public Docker Hub configuration visibility resolver + /// Suffix of the attribute bUnit writes for an event handler that prevents the default action /// - private static readonly MethodInfo _isDockerHubAccountConfiguredMethod = typeof(NavMenu).GetMethod("IsDockerHubAccountConfigured", - BindingFlags.NonPublic | BindingFlags.Static, - [typeof(DockerHubOptions)]) - ?? throw new InvalidOperationException("NavMenu must expose the non-public static IsDockerHubAccountConfigured(DockerHubOptions) overload for testability"); + private const string PreventDefaultSuffix = ":preventdefault"; - #endregion // Fields + #endregion // Constants #region Methods /// - /// Verify the My Images link is shown when both credentials are present + /// Verify the entries, their labels and their order for each pair of the My Images and Base Images conditions /// - /// Docker Hub user name - /// Personal access token + /// Whether the My Images entry is shown + /// Whether the Base Images entry is shown + /// Expected labels in order, separated by a semicolon + /// Task [TestMethod] - [DataRow("alice", "my-pat")] - [DataRow("bob", "another-token")] - [DataRow(" user ", " token ")] - public void NavMenuIsDockerHubAccountConfiguredBothCredentialsSetReturnsTrue(string userName, string pat) + [TestCategory("AC2")] + [DataRow(false, false, "Dashboard;Observed Images;Runtime Containers;Docker Instances;Vulnerabilities;Scan History")] + [DataRow(true, false, "Dashboard;My Images;Observed Images;Runtime Containers;Docker Instances;Vulnerabilities;Scan History")] + [DataRow(false, true, "Dashboard;Observed Images;Runtime Containers;Docker Instances;Base Images;Vulnerabilities;Scan History")] + [DataRow(true, true, "Dashboard;My Images;Observed Images;Runtime Containers;Docker Instances;Base Images;Vulnerabilities;Scan History")] + public async Task NavMenuRendersEntriesInOrderWithLabels(bool showMyImages, bool showBaseImages, string expectedLabels) { - var options = new DockerHubOptions - { - UserName = userName, - Pat = pat, - }; + var testContext = BlazorTestContextFactory.Create(); - var result = (bool)_isDockerHubAccountConfiguredMethod.Invoke(null, [options])!; + await using (testContext) + { + var component = RenderNavMenu(testContext, showMyImages, showBaseImages); + var links = component.Find("nav[aria-label=\"Main\"]").QuerySelectorAll("a"); - Assert.IsTrue(result, $"My Images navigation must be visible when both UserName ('{userName}') and Pat are set"); + Assert.AreEqual(expectedLabels, + string.Join(";", links.Select(link => link.TextContent.Trim())), + "The entries must appear with the labels and in the order of the navigation, the optional ones only when their condition holds"); + } } /// - /// Verify the My Images link is hidden when UserName is absent + /// Verify each entry links to the route of its page, the dashboard to the base address /// - /// Missing or blank user name + /// Task [TestMethod] - [DataRow(null)] - [DataRow("")] - [DataRow(" ")] - public void NavMenuIsDockerHubAccountConfiguredMissingUserNameReturnsFalse(string? userName) + [TestCategory("AC2")] + public async Task NavMenuEntriesLinkToTheirRoutes() { - var options = new DockerHubOptions - { - UserName = userName, - Pat = "valid-token", - }; + var testContext = BlazorTestContextFactory.Create(); - var result = (bool)_isDockerHubAccountConfiguredMethod.Invoke(null, [options])!; + await using (testContext) + { + var component = RenderNavMenu(testContext, true, true); + var hrefs = component.Find("nav[aria-label=\"Main\"]").QuerySelectorAll("a").Select(link => link.GetAttribute("href")); - Assert.IsFalse(result, "My Images navigation must be hidden when UserName is absent or blank"); + Assert.AreEqual(";my-images;observed-images;runtime-containers;docker-instances;base-images;vulnerabilities;scan-history", + string.Join(";", hrefs), + "Every entry must link to the route of its page relative to the base address, Base Images to its unchanged route"); + } } /// - /// Verify the My Images link is hidden when Pat is absent + /// Verify the entries are plain links, with no button, icon or handler that prevents the navigation, so they navigate before the page is interactive /// - /// Missing or blank personal access token + /// Task [TestMethod] - [DataRow(null)] - [DataRow("")] - [DataRow(" ")] - public void NavMenuIsDockerHubAccountConfiguredMissingPatReturnsFalse(string? pat) + [TestCategory("AC2")] + public async Task NavMenuEntriesAreLinksWithoutInteractivity() { - var options = new DockerHubOptions - { - UserName = "alice", - Pat = pat, - }; - - var result = (bool)_isDockerHubAccountConfiguredMethod.Invoke(null, [options])!; + var testContext = BlazorTestContextFactory.Create(); - Assert.IsFalse(result, "My Images navigation must be hidden when Pat is absent or blank"); + await using (testContext) + { + var component = RenderNavMenu(testContext, true, true); + var links = component.FindAll("nav[aria-label=\"Main\"] a"); + var preventing = links.SelectMany(link => link.Attributes) + .Where(attribute => attribute.Name.EndsWith(PreventDefaultSuffix, StringComparison.Ordinal)) + .Select(attribute => attribute.Name) + .ToList(); + + Assert.HasCount(8, links, "Every entry must be a link element"); + Assert.IsTrue(links.All(link => link.HasAttribute("href")), "Every link must have a target to navigate to without the circuit"); + Assert.IsEmpty(preventing, "No entry may prevent the default navigation of its link"); + Assert.IsEmpty(component.FindAll("button"), "The navigation must not contain a button"); + Assert.IsEmpty(component.FindAll("svg"), "The entries must have no icons"); + Assert.DoesNotContain("mud-nav", component.Markup, "The entries must not be MudBlazor navigation links"); + } } /// - /// Verify the My Images link is hidden when neither credential is configured + /// Verify selecting an entry invokes the callback of the layout without preventing the navigation /// + /// Task [TestMethod] - public void NavMenuIsDockerHubAccountConfiguredBothCredentialsMissingReturnsFalse() + [TestCategory("AC4")] + public async Task NavMenuClickingEntryInvokesEntrySelectedCallback() { - var options = new DockerHubOptions(); + var testContext = BlazorTestContextFactory.Create(); - var result = (bool)_isDockerHubAccountConfiguredMethod.Invoke(null, [options])!; + await using (testContext) + { + var calls = 0; + var callback = EventCallback.Factory.Create(this, () => calls++); + + var component = testContext.Render(parameters => parameters.Add(menu => menu.Navigation, new NavigationViewData()) + .Add(menu => menu.OnEntrySelected, callback)); - Assert.IsFalse(result, "My Images navigation must be hidden when neither UserName nor Pat is configured"); + await component.Find("nav[aria-label=\"Main\"] a[href=\"vulnerabilities\"]").ClickAsync().ConfigureAwait(false); + + Assert.AreEqual(1, calls, "Selecting an entry must invoke the entry callback once"); + } } /// - /// Verify the Vulnerabilities navigation entry is always rendered + /// Verify which entry a location marks as active + /// + /// Link target of the entry + /// Current location relative to the base address + /// Whether the entry is the active one + [TestMethod] + [TestCategory("AC3")] + [DataRow("", "", true)] + [DataRow("", "vulnerabilities", false)] + [DataRow("", "error", false)] + [DataRow("", "not-found", false)] + [DataRow("", "?tab=1", true)] + [DataRow("vulnerabilities", "vulnerabilities", true)] + [DataRow("vulnerabilities", "vulnerabilities?page=2", true)] + [DataRow("vulnerabilities", "vulnerabilities#top", true)] + [DataRow("vulnerabilities", "vulnerabilities/", true)] + [DataRow("vulnerabilities", "vulnerabilities-x", false)] + [DataRow("vulnerabilities", "Vulnerabilities", true)] + [DataRow("vulnerabilities", "", false)] + [DataRow("runtime-containers", "runtime-containers/a/b", true)] + [DataRow("observed-images", "observed-images/1", true)] + [DataRow("observed-images", "runtime-containers/a/b", false)] + [DataRow("my-images", "my-images/5", true)] + public void NavMenuIsActiveMatchesEntryRoute(string href, string relativePath, bool expected) + { + var isActive = NavMenu.IsActive(href, relativePath); + + Assert.AreEqual(expected, isActive, $"The entry '{href}' at the location '{relativePath}' must be {(expected ? "active" : "inactive")}"); + } + + /// + /// Verify on the dashboard only the Dashboard entry is marked, by its class and by aria-current /// /// Task [TestMethod] - public async Task NavMenuRendersVulnerabilitiesNavigationEntry() + [TestCategory("AC3")] + public async Task NavMenuOnDashboardMarksOnlyDashboard() { var testContext = BlazorTestContextFactory.Create(); await using (testContext) { - var viewService = Substitute.For(); + var component = RenderNavMenu(testContext, true, true); + var current = component.FindAll("nav[aria-label=\"Main\"] a[aria-current]"); + var active = component.FindAll("nav[aria-label=\"Main\"] a.app-nav__link--active"); + + Assert.HasCount(1, current, "Exactly one entry must carry aria-current"); + Assert.AreEqual("Dashboard", current[0].TextContent.Trim(), "The Dashboard entry must carry aria-current on the dashboard"); + Assert.AreEqual("page", current[0].GetAttribute("aria-current"), "The marked entry must be the current page"); + Assert.HasCount(1, active, "Exactly one entry must carry the active class"); + Assert.AreEqual("Dashboard", active[0].TextContent.Trim(), "The Dashboard entry must carry the active class on the dashboard"); + Assert.IsTrue(component.FindAll("nav[aria-label=\"Main\"] a").All(link => link.ClassList.Contains("app-nav__link")), "Every entry must carry the link class"); + } + } - viewService.HasBaseImagesAsync(Arg.Any()) - .Returns(false); + /// + /// Verify a list route, a route below it and a query string mark exactly the entry of the list + /// + /// Location relative to the base address + /// Label of the entry marked as active + /// Task + [TestMethod] + [TestCategory("AC3")] + [DataRow("vulnerabilities", "Vulnerabilities")] + [DataRow("vulnerabilities?page=2", "Vulnerabilities")] + [DataRow("runtime-containers/a/b", "Runtime Containers")] + [DataRow("observed-images/1", "Observed Images")] + [DataRow("base-images", "Base Images")] + public async Task NavMenuOnRouteOfEntryMarksOnlyThatEntry(string location, string expectedLabel) + { + var testContext = BlazorTestContextFactory.Create(); - testContext.Services.AddSingleton(viewService); - testContext.Services.AddSingleton(new ConfigurationBuilder().Build()); - testContext.Services.AddSingleton(Options.Create(new DockerUpdateGuardOptions())); + await using (testContext) + { + testContext.Services.GetRequiredService().NavigateTo(location); - var component = testContext.Render(); - var vulnerabilitiesLink = component.FindAll("a").SingleOrDefault(link => link.TextContent.Trim() == "Vulnerabilities"); + var component = RenderNavMenu(testContext, true, true); + var current = component.FindAll("nav[aria-label=\"Main\"] a[aria-current]"); - Assert.IsNotNull(vulnerabilitiesLink, "The Vulnerabilities navigation entry must always be rendered"); - Assert.IsTrue(vulnerabilitiesLink.GetAttribute("href")?.Contains("vulnerabilities", StringComparison.OrdinalIgnoreCase), - "The Vulnerabilities navigation entry must link to the vulnerabilities page"); + Assert.HasCount(1, current, "Exactly one entry must carry aria-current"); + Assert.AreEqual(expectedLabel, current[0].TextContent.Trim(), $"The location '{location}' must mark the entry '{expectedLabel}'"); } } /// - /// Verify the Shared Base Images navigation entry is rendered when shared base images exist + /// Verify the error page, the not-found page and an unknown route mark no entry /// + /// Location relative to the base address /// Task [TestMethod] - [TestCategory("AC7")] - public async Task NavMenuWithSharedBaseImagesRendersSharedBaseImagesEntryAsync() + [TestCategory("AC3")] + [DataRow("error")] + [DataRow("not-found")] + [DataRow("no/such/page")] + public async Task NavMenuOnPageWithoutEntryMarksNoEntry(string location) { var testContext = BlazorTestContextFactory.Create(); await using (testContext) { - var component = RenderNavMenu(testContext, true); + testContext.Services.GetRequiredService().NavigateTo(location); - await component.WaitForAssertionAsync(() => Assert.IsNotNull(FindSharedBaseImagesLink(component), "The Shared Base Images entry must be rendered when shared base images exist")); + var component = RenderNavMenu(testContext, true, true); - Assert.AreEqual("base-images", - FindSharedBaseImagesLink(component)!.GetAttribute("href"), - "The Shared Base Images entry must link to the base images page"); + Assert.IsEmpty(component.FindAll("a[aria-current]"), $"The location '{location}' must not mark an entry with aria-current"); + Assert.IsEmpty(component.FindAll("a.app-nav__link--active"), $"The location '{location}' must not mark an entry as active"); } } /// - /// Verify the Shared Base Images navigation entry is hidden without shared base images + /// Verify the detail route of a hidden entry marks no entry /// /// Task [TestMethod] - [TestCategory("AC7")] - public async Task NavMenuWithoutSharedBaseImagesHidesSharedBaseImagesEntryAsync() + [TestCategory("AC3")] + public async Task NavMenuOnHiddenEntryDetailMarksNoEntry() { var testContext = BlazorTestContextFactory.Create(); await using (testContext) { - var component = RenderNavMenu(testContext, false); + testContext.Services.GetRequiredService().NavigateTo("my-images/7"); - await component.WaitForAssertionAsync(() => Assert.IsNotNull(component.Find("a"), "The navigation menu must have finished rendering")); + var component = RenderNavMenu(testContext, false, false); - Assert.IsNull(FindSharedBaseImagesLink(component), "The Shared Base Images entry must not be rendered without shared base images"); + Assert.IsEmpty(component.FindAll("a[aria-current]"), "The detail of a hidden entry must not mark another entry with aria-current"); + Assert.IsEmpty(component.FindAll("a.app-nav__link--active"), "The detail of a hidden entry must not mark another entry as active"); } } /// - /// Verify a failing base images check hides the Shared Base Images entry, keeps the other entries, shows no error text and logs the failure once + /// Verify the navigation subscribes to location changes while it lives and unsubscribes when it is disposed /// /// Task [TestMethod] - [TestCategory("AC6")] - public async Task NavMenuBaseImagesCheckFailureHidesEntryAndLogs() + [TestCategory("AC3")] + public async Task NavMenuUnsubscribesFromLocationChangesWhenDisposed() { - var exception = new InvalidOperationException("secret text"); - var logger = new TestLogger(); var testContext = BlazorTestContextFactory.Create(); await using (testContext) { - var viewService = Substitute.For(); - - viewService.HasBaseImagesAsync(Arg.Any()) - .Returns(Task.FromException(exception)); + var navigationManager = testContext.Services.GetRequiredService(); + var handlersField = typeof(NavigationManager).GetField("_locationChanged", BindingFlags.NonPublic | BindingFlags.Instance) + ?? throw new InvalidOperationException("NavigationManager must hold its LocationChanged handlers in _locationChanged"); + var before = (handlersField.GetValue(navigationManager) as Delegate)?.GetInvocationList().Length ?? 0; + var component = RenderNavMenu(testContext, false, false); + var during = (handlersField.GetValue(navigationManager) as Delegate)?.GetInvocationList().Length ?? 0; - testContext.Services.AddSingleton(viewService); - testContext.Services.AddSingleton(new ConfigurationBuilder().Build()); - testContext.Services.AddSingleton(Options.Create(new DockerUpdateGuardOptions())); - testContext.Services.AddSingleton>(logger); + Assert.AreEqual(before + 1, during, "The navigation must subscribe to location changes while it is rendered"); - var component = testContext.Render(); + await component.InvokeAsync(component.Instance.Dispose).ConfigureAwait(false); - await component.WaitForAssertionAsync(() => DetailPageAssert.AssertLoadLoggedOnce(logger, "LoadNavigation", exception), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + var after = (handlersField.GetValue(navigationManager) as Delegate)?.GetInvocationList().Length ?? 0; - Assert.IsNotNull(component.FindAll("a").SingleOrDefault(link => link.TextContent.Trim() == "Vulnerabilities"), "The other entries must stay rendered"); - Assert.IsNull(FindSharedBaseImagesLink(component), "The Shared Base Images entry must be hidden"); - Assert.DoesNotContain("secret text", component.Markup, "The menu must not show the exception's text"); + Assert.AreEqual(before, after, "Disposing the navigation must remove its location-change handler"); } } /// - /// Render the navigation menu for a base images flag + /// Render the navigation for the two conditions /// /// bUnit test context - /// Whether the view service reports shared base images + /// Whether the My Images entry is shown + /// Whether the Base Images entry is shown /// Rendered component - private static IRenderedComponent RenderNavMenu(BunitContext testContext, bool hasBaseImages) + private static IRenderedComponent RenderNavMenu(BunitContext testContext, bool showMyImages, bool showBaseImages) { - var viewService = Substitute.For(); - - viewService.HasBaseImagesAsync(Arg.Any()) - .Returns(hasBaseImages); + var navigation = new NavigationViewData + { + ShowMyImages = showMyImages, + ShowBaseImages = showBaseImages, + }; - testContext.Services.AddSingleton(viewService); - testContext.Services.AddSingleton(new ConfigurationBuilder().Build()); - testContext.Services.AddSingleton(Options.Create(new DockerUpdateGuardOptions())); - - return testContext.Render(); - } - - /// - /// Find the Shared Base Images navigation link - /// - /// Rendered navigation menu - /// Link element, or null when it is not rendered - private static AngleSharp.Dom.IElement? FindSharedBaseImagesLink(IRenderedComponent component) - { - return component.FindAll("a").SingleOrDefault(link => link.TextContent.Trim() == "Shared Base Images"); + return testContext.Render(parameters => parameters.Add(menu => menu.Navigation, navigation)); } #endregion // Methods