diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 60917c36..6d1b2b2c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -391,11 +391,32 @@ behavior is in [Registries](areas/registries.md). Blazor Server (**Interactive Server** render mode, applied at the `App` root — no WebAssembly, no Auto mode) with **MudBlazor** as the component -library, plus a hand-rolled CSS design-system layer -(`wwwroot\app.css`, light/dark via a `.dug-dark` class) on top of it. +library, plus a hand-rolled CSS token layer (`wwwroot\app.css`) on top of it. Pages, routes and what each page shows or triggers are specified in [Web UI](areas/web-ui.md). +- **Design tokens** (`wwwroot\app.css`) are the `--dug-*` custom properties + for colors, radii, fonts and the transition. The light values sit in + `:root`; the dark values sit in one block with the selector + `:is(.dug-dark, :root:has(.dug-dark))`, which applies while the layout + carries `dug-dark` and reaches the whole document, so menus, popovers and + dialogs that MudBlazor renders beside the layout take the dark values too + ([decision 0077](decisions/0077-the-dark-theme-tokens-apply-to-the-whole-document-while-the-layout-is-dark.md)). + Every rule outside the two token blocks uses tokens only, with no blur, + gradient or drop shadow. +- **Fonts** are self-hosted from `wwwroot\fonts` and declared with + `@font-face` and `font-display: swap`: Inter for text and Space Grotesk + (variable latin subset, with its SIL Open Font License text) for page + titles, entity names and figures. `App.razor` preloads both files; the + page loads no font or style from another host. +- **MudBlazor theme** is the private `_theme` of `MainLayout`; it mirrors + the tokens: a 6 px default radius, the Inter stack as default font with + Space Grotesk for headings `h1`–`h4`, 14 px text with a line height of + 1.45, both palettes with the token colors, the page ground color as + contrast text of the dark status colors, and all 26 elevation shadows set + to `none` + ([decision 0078](decisions/0078-mudblazor-elevation-shadows-are-switched-off-in-the-theme.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 53bc3375..6605f700 100644 --- a/docs/areas/web-ui.md +++ b/docs/areas/web-ui.md @@ -173,6 +173,16 @@ never their values. - If the browser storage cannot be read or written, the toggle still works for the session and the choice is not remembered. - Users who ask their system for reduced motion get (practically) no transitions or animations. +- Both themes are flat and come from one set of design values with a light and a dark variant: opaque surfaces + with a 1 px hairline border, no blur, gradient or drop shadow (including the shadows MudBlazor draws under tables, + the drawer and filled buttons), and no lift, scaling or shadow when a card, link or button is hovered or pressed. + Menus, popovers (tooltips excepted) and dialogs are separated from the content by a hairline border; dialogs and snackbars also keep the drop shadow MudBlazor's own stylesheet gives them. +- In the dark theme the dark values apply to the whole document, so menus, popovers and dialogs are dark too. +- Text and status labels keep a contrast of at least 4.5:1 against their background in both themes; filled status + chips and buttons of the dark theme draw their label in the dark page color. +- Text is set in Inter; page titles, entity names, the figures of the dashboard's metric cards and the product name + are set in Space Grotesk. Both fonts and the styles are served by the application itself; the browser loads + nothing from another host for them, and until a font has loaded the text shows in a fallback font. ### Secrets @@ -258,6 +268,10 @@ never their values. missing record or a failed load inline. - [0060](../decisions/0060-a-detail-page-acts-only-on-the-state-of-its-current-route.md) — A detail page acts only on the state of its current route. +- [0077](../decisions/0077-the-dark-theme-tokens-apply-to-the-whole-document-while-the-layout-is-dark.md) — The dark + theme's tokens apply to the whole document while the layout is dark. +- [0078](../decisions/0078-mudblazor-elevation-shadows-are-switched-off-in-the-theme.md) — MudBlazor elevation + shadows are switched off in the theme. ## Not here diff --git a/docs/decisions/0077-the-dark-theme-tokens-apply-to-the-whole-document-while-the-layout-is-dark.md b/docs/decisions/0077-the-dark-theme-tokens-apply-to-the-whole-document-while-the-layout-is-dark.md new file mode 100644 index 00000000..5a14c513 --- /dev/null +++ b/docs/decisions/0077-the-dark-theme-tokens-apply-to-the-whole-document-while-the-layout-is-dark.md @@ -0,0 +1,38 @@ +# 0077: The dark theme's tokens apply to the whole document while the layout is dark + +- **Status:** Accepted +- **Date:** 2026-11-28 +- **Area:** Web UI +- **Source:** Issue #451 +- **Supersedes:** — + +## Context + +The dark theme sets the class `dug-dark` on the layout element, and `app.css` overrides the `--dug-*` tokens under +that class. MudBlazor renders menus, popovers and dialogs in providers that sit beside the layout, not inside it +(`Components/Layout/MainLayout.razor`), and the page body is outside it too, so their tokens resolve to the light +values while the rest of the page is dark. Once the flat refresh colors these surfaces from the tokens, a muted text in +the top bar's compact menu would read 2.9:1 on the dark surface. The class must stay on the layout: the layout tests +and the toggle rely on it ([Web UI](../areas/web-ui.md#light-and-dark-mode)). + +## Options considered + +1. **The dark token block also matches the document root while it contains the dark layout (chosen)** — one selector + in `app.css`, no markup or script; the body and every provider inherit the dark values. It needs `:has()` + (all current browsers); wrapped in the forgiving `:is()`, an older browser keeps at least the dark layout. +2. **Carry the class to an element that wraps the providers and the layout** — works for the providers, but changes + the layout's markup and where the class sits, and leaves the body light. +3. **Set the class on `` through JavaScript interop** — reaches everything, but adds a script no unit test + covers, a second source of the theme state and a flash before the call runs. + +## Decision + +The dark token block's selector is `:is(.dug-dark, :root:has(.dug-dark))`, so the dark values apply to the whole +document while the layout carries `dug-dark`; the class stays on the layout. Theme switching itself is unchanged +([Web UI](../areas/web-ui.md#light-and-dark-mode)). + +## Consequences + +Later sub-issues of #450 may color any surface, also one MudBlazor renders outside the layout, from the tokens. A +browser without `:has()` shows the dark layout with light menus and dialogs. Moving the theme state off the layout +element would make this selector obsolete. diff --git a/docs/decisions/0078-mudblazor-elevation-shadows-are-switched-off-in-the-theme.md b/docs/decisions/0078-mudblazor-elevation-shadows-are-switched-off-in-the-theme.md new file mode 100644 index 00000000..a164539e --- /dev/null +++ b/docs/decisions/0078-mudblazor-elevation-shadows-are-switched-off-in-the-theme.md @@ -0,0 +1,36 @@ +# 0078: MudBlazor elevation shadows are switched off in the theme + +- **Status:** Accepted +- **Date:** 2026-11-28 +- **Area:** Web UI +- **Source:** Issue #451 +- **Supersedes:** — + +## Context + +The flat refresh (#450) draws no shadows: panels are separated by hairlines. Besides the shadows of `app.css`, +MudBlazor draws its own: every surface with an elevation above zero (each table, the dashboard's hero panel, the +drawer) takes it from the theme's elevation levels, and filled buttons carry shadows written into MudBlazor's +stylesheet. Menus and popovers use the same elevation levels to stand out from the content below; dialogs and snackbars carry shadows written into MudBlazor's stylesheet. The pages +themselves are rebuilt only in later sub-issues, so this one may not change their markup. + +## Options considered + +1. **Every elevation level of the theme is `none`, filled buttons lose their shadow in `app.css`, and menus, + popovers and dialogs get a hairline border (chosen)** — one place for all present and future surfaces, checkable + in the theme; floating layers are separated the flat way. +2. **Override the shadow of each affected surface in `app.css`** — keeps the shadows of floating layers, but is a list + every new component of the later sub-issues must extend. +3. **Set `Elevation="0"` on each surface in the markup** — about twenty edits in pages this sub-issue must not + change, and filled buttons keep their shadow. + +## Decision + +The MudBlazor theme sets all of its elevation levels to `none`; `app.css` removes the shadow of filled buttons in +every state and borders menus, popovers and dialogs with the border token +([Web UI](../areas/web-ui.md#light-and-dark-mode)). + +## Consequences + +No component can show a shadow through its elevation any more; one that needs to stand out gets a border. A MudBlazor +update that adds literal shadows to another component needs a rule in `app.css`. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 1563d0d8..c3479c23 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -137,4 +137,6 @@ once in the [area document](../areas/README.md) of the record's area, and the re | [0074](0074-a-docker-engine-stats-or-image-inspect-answer-that-is-not-a-json-object-is-an-invalid-response.md) | A Docker Engine stats or image inspect answer that is not a JSON object is an invalid response | Accepted | 2026-11-28 | | [0075](0075-a-docker-engine-container-list-or-image-history-that-is-not-a-json-array-is-an-invalid-response.md) | A Docker Engine container list or image history that is not a JSON array is an invalid response | Accepted | 2026-11-28 | | [0076](0076-the-dotnet-release-index-is-parsed-as-a-remote-json-object-and-an-entry-that-is-not-one-is-left-out.md) | The .NET release index is parsed as a remote JSON object, and an entry that is not one is left out | Accepted | 2026-11-28 | +| [0077](0077-the-dark-theme-tokens-apply-to-the-whole-document-while-the-layout-is-dark.md) | The dark theme's tokens apply to the whole document while the layout is dark | Accepted | 2026-11-28 | +| [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 | \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/App.razor b/src/DockerUpdateGuard/Components/App.razor index 8513ee7d..5f0c8d13 100644 --- a/src/DockerUpdateGuard/Components/App.razor +++ b/src/DockerUpdateGuard/Components/App.razor @@ -6,6 +6,7 @@ + diff --git a/src/DockerUpdateGuard/Components/Layout/MainLayout.razor.cs b/src/DockerUpdateGuard/Components/Layout/MainLayout.razor.cs index 49c9c65e..07c3da7d 100644 --- a/src/DockerUpdateGuard/Components/Layout/MainLayout.razor.cs +++ b/src/DockerUpdateGuard/Components/Layout/MainLayout.razor.cs @@ -27,10 +27,25 @@ public sealed partial class MainLayout : LayoutComponentBase, IDisposable /// private const string DarkModeStorageKey = "dug-dark-mode"; + /// + /// Contrast text of the dark status colors, the page ground color of the dark theme + /// + private const string DarkContrastText = "#0F1216"; + #endregion // Constants #region Fields + /// + /// Font stack of text, the same as --dug-font-text in app.css + /// + private static readonly string[] _textFonts = ["Inter", "Segoe UI", "Arial", "Helvetica", "sans-serif"]; + + /// + /// Font stack of titles and figures, the same as --dug-font-display in app.css + /// + private static readonly string[] _displayFonts = ["Space Grotesk", "Inter", "Segoe UI", "Arial", "sans-serif"]; + /// /// Application theme /// @@ -38,37 +53,107 @@ public sealed partial class MainLayout : LayoutComponentBase, IDisposable { LayoutProperties = new LayoutProperties { - DefaultBorderRadius = "18px", + DefaultBorderRadius = "6px", }, + Shadows = new Shadow + { + Elevation = [.. Enumerable.Repeat("none", 26)], + }, + Typography = new Typography + { + Default = new DefaultTypography + { + FontFamily = _textFonts, + FontSize = ".875rem", + LineHeight = "1.45", + FontWeight = "400", + }, + Body1 = new Body1Typography + { + FontFamily = _textFonts, + FontSize = ".875rem", + LineHeight = "1.45", + FontWeight = "400", + }, + H1 = new H1Typography + { + FontFamily = _displayFonts, + }, + H2 = new H2Typography + { + FontFamily = _displayFonts, + }, + H3 = new H3Typography + { + FontFamily = _displayFonts, + FontSize = "1.75rem", + FontWeight = "600", + LetterSpacing = "-0.02em", + LineHeight = "1.2", + }, + H4 = new H4Typography + { + FontFamily = _displayFonts, + FontSize = "1.25rem", + FontWeight = "600", + LetterSpacing = "0", + LineHeight = "1.3", + }, + H5 = new H5Typography + { + FontSize = ".9375rem", + FontWeight = "600", + LetterSpacing = "0", + LineHeight = "1.4", + }, + }, PaletteLight = new PaletteLight { - Primary = "#2563eb", - Secondary = "#0891b2", - Info = "#0284c7", - Success = "#15803d", - Warning = "#b45309", - Error = "#b91c1c", - Background = "#f3f6fb", - Surface = "#ffffff", - AppbarBackground = "rgba(255,255,255,0.82)", - DrawerBackground = "#0f172a", - DrawerText = "#e2e8f0", + Primary = "#2563EB", + Secondary = "#5B6471", + Info = "#1D4ED8", + Success = "#067647", + Warning = "#B54708", + Error = "#B42318", + Background = "#F6F7F9", + Surface = "#FFFFFF", + AppbarBackground = "#FFFFFF", + DrawerBackground = "#FFFFFF", + DrawerText = "#16191D", + TextPrimary = "#16191D", + TextSecondary = "#5B6471", + Divider = "#E3E6EB", + LinesDefault = "#E3E6EB", + TableLines = "#EEF0F3", + LinesInputs = "#C9CED6", + TableHover = "#FAFBFC", }, PaletteDark = new PaletteDark { - Primary = "#3b82f6", - Secondary = "#22d3ee", - Info = "#38bdf8", - Success = "#4ade80", - Warning = "#fbbf24", - Error = "#f87171", - Background = "#0b1220", - Surface = "#111a2e", - AppbarBackground = "rgba(15, 23, 42, 0.82)", - DrawerBackground = "#0b1220", - DrawerText = "#e2e8f0", - TextPrimary = "#e2e8f0", - TextSecondary = "#94a3b8", + Primary = "#7AA7FF", + Secondary = "#9BA5B3", + Info = "#9CC0FF", + Success = "#5FD39A", + Warning = "#F2A54A", + Error = "#FF8A80", + PrimaryContrastText = DarkContrastText, + SecondaryContrastText = DarkContrastText, + InfoContrastText = DarkContrastText, + SuccessContrastText = DarkContrastText, + WarningContrastText = DarkContrastText, + ErrorContrastText = DarkContrastText, + Background = "#0F1216", + Surface = "#171B21", + AppbarBackground = "#171B21", + DrawerBackground = "#171B21", + DrawerText = "#E7EAEE", + TextPrimary = "#E7EAEE", + TextSecondary = "#9BA5B3", + Divider = "#272D36", + LinesDefault = "#272D36", + TableLines = "#20262E", + LinesInputs = "#3A424E", + TableHover = "#1B2027", }, }; diff --git a/src/DockerUpdateGuard/wwwroot/app.css b/src/DockerUpdateGuard/wwwroot/app.css index 930aaacd..712169ae 100644 --- a/src/DockerUpdateGuard/wwwroot/app.css +++ b/src/DockerUpdateGuard/wwwroot/app.css @@ -6,88 +6,110 @@ font-display: swap; } -:root { - --dug-primary: #2563eb; - --dug-primary-strong: #1d4ed8; - --dug-secondary: #0891b2; - --dug-bg-page: #f3f6fb; - --dug-surface: rgba(255, 255, 255, 0.82); - --dug-surface-solid: #ffffff; - --dug-border: rgba(148, 163, 184, 0.2); - --dug-text: #0f172a; - --dug-text-muted: #475569; - --dug-text-faint: #64748b; - --dug-success: #15803d; - --dug-warning: #b45309; - --dug-danger: #b91c1c; - --dug-info: #0284c7; - --dug-sev-critical: #dc2626; - --dug-sev-high: #ea580c; - --dug-sev-medium: #0284c7; - --dug-sev-low: #15803d; - --dug-radius-lg: 1.5rem; - --dug-radius-md: 1rem; - --dug-shadow-card: 0 20px 45px rgba(15, 23, 42, 0.08); - --dug-shadow-hover: 0 24px 48px rgba(15, 23, 42, 0.14); - --dug-blur: blur(12px); - --dug-transition: 0.18s ease; - --dug-bg-gradient: - radial-gradient(circle at top left, rgba(59, 130, 246, 0.12), transparent 24rem), - radial-gradient(circle at top right, rgba(14, 165, 233, 0.12), transparent 22rem), - linear-gradient(180deg, #eef4ff 0%, #f8fafc 35%, #f3f6fb 100%); -} - -.dug-dark { - --dug-bg-page: #0b1220; - --dug-surface: rgba(17, 26, 46, 0.82); - --dug-surface-solid: #111a2e; - --dug-border: rgba(148, 163, 184, 0.16); - --dug-text: #e2e8f0; - --dug-text-muted: #94a3b8; - --dug-text-faint: #64748b; - --dug-shadow-card: 0 20px 45px rgba(0, 0, 0, 0.35); - --dug-shadow-hover: 0 24px 48px rgba(0, 0, 0, 0.45); - --dug-bg-gradient: - radial-gradient(circle at top left, rgba(59, 130, 246, 0.16), transparent 24rem), - radial-gradient(circle at top right, rgba(14, 165, 233, 0.14), transparent 22rem), - linear-gradient(180deg, #0b1220 0%, #0d1526 35%, #0b1220 100%); -} - -.dug-dark .mud-paper.app-topbar { - background: rgba(17, 26, 46, 0.72); -} - -.dug-dark .app-topbar__meta-card { - background: rgba(17, 26, 46, 0.78); -} - -.dug-dark .hero-panel { - background: - linear-gradient(135deg, rgba(37, 99, 235, 0.22), rgba(14, 165, 233, 0.16)), - rgba(17, 26, 46, 0.92); -} - -.dug-dark .section-paper--accent { - background: - linear-gradient(135deg, rgba(37, 99, 235, 0.16), rgba(14, 165, 233, 0.1)), - rgba(17, 26, 46, 0.92); -} - -.dug-dark .metric-card--warning { - background: - linear-gradient(135deg, rgba(180, 83, 9, 0.22), rgba(17, 26, 46, 0.9)), - rgba(17, 26, 46, 0.92); +@font-face { + font-family: "Space Grotesk"; + src: url("fonts/SpaceGrotesk-Variable-latin.woff2") format("woff2"); + font-weight: 300 700; + font-style: normal; + font-display: swap; } -.dug-dark .metric-card--danger { - background: - linear-gradient(135deg, rgba(185, 28, 28, 0.2), rgba(17, 26, 46, 0.9)), - rgba(17, 26, 46, 0.92); +:root { + --dug-bg-page: #F6F7F9; + --dug-surface: #FFFFFF; + --dug-surface-solid: #FFFFFF; + --dug-surface-subtle: #FAFBFC; + --dug-border: #E3E6EB; + --dug-border-inner: #EEF0F3; + --dug-border-control: #C9CED6; + --dug-text: #16191D; + --dug-text-muted: #5B6471; + --dug-text-faint: #5B6471; + --dug-icon: #3D4551; + --dug-primary: #2563EB; + --dug-on-primary: #FFFFFF; + --dug-link: #1D4ED8; + --dug-attention: #B54708; + --dug-danger: #B42318; + --dug-success: #067647; + --dug-info: #1D4ED8; + --dug-sev-critical: #7A1C12; + --dug-sev-high: #D9480F; + --dug-sev-medium: #E8A33D; + --dug-sev-low: #C9CED6; + --dug-scan-succeeded: #9FB3C8; + --dug-scan-partial: #E8A33D; + --dug-scan-failed: #7A1C12; + --dug-chip-critical-bg: #7A1C12; + --dug-chip-critical-fg: #FFFFFF; + --dug-chip-high-bg: #FFF1E6; + --dug-chip-high-fg: #9A3D00; + --dug-chip-medium-bg: #FDF3D7; + --dug-chip-medium-fg: #7A5200; + --dug-chip-low-bg: #EEF0F3; + --dug-chip-low-fg: #3D4551; + --dug-chip-success-bg: #E6F4EC; + --dug-chip-success-fg: #05603A; + --dug-chip-info-bg: #E8EFFD; + --dug-chip-info-fg: #1D4ED8; + --dug-chart-cpu: #2563EB; + --dug-chart-cpu-fill: #E8EFFD; + --dug-chart-memory: #6D4AC4; + --dug-chart-memory-fill: #EFEAFA; + --dug-chart-net-rx: #0F766E; + --dug-chart-net-tx: #B54708; + --dug-radius-lg: 8px; + --dug-radius-md: 6px; + --dug-radius-sm: 4px; + --dug-font-text: Inter, "Segoe UI", Arial, Helvetica, sans-serif; + --dug-font-display: "Space Grotesk", Inter, "Segoe UI", Arial, sans-serif; + --dug-transition: 0.18s ease; } -.dug-dark .section-table .mud-table-container { - background: rgba(17, 26, 46, 0.88); - border-color: rgba(148, 163, 184, 0.18); +:is(.dug-dark, :root:has(.dug-dark)) { + --dug-bg-page: #0F1216; + --dug-surface: #171B21; + --dug-surface-solid: #171B21; + --dug-surface-subtle: #1B2027; + --dug-border: #272D36; + --dug-border-inner: #20262E; + --dug-border-control: #3A424E; + --dug-text: #E7EAEE; + --dug-text-muted: #9BA5B3; + --dug-text-faint: #9BA5B3; + --dug-icon: #C5CCD6; + --dug-primary: #7AA7FF; + --dug-on-primary: #0F1216; + --dug-link: #7AA7FF; + --dug-attention: #F2A54A; + --dug-danger: #FF8A80; + --dug-success: #5FD39A; + --dug-info: #9CC0FF; + --dug-sev-critical: #FF7B72; + --dug-sev-high: #E0762B; + --dug-sev-medium: #A67C1F; + --dug-sev-low: #4A5361; + --dug-scan-succeeded: #46566B; + --dug-scan-partial: #E0A23D; + --dug-scan-failed: #FF7B72; + --dug-chip-critical-bg: #FF7B72; + --dug-chip-critical-fg: #1A0B0A; + --dug-chip-high-bg: #3A2413; + --dug-chip-high-fg: #FFB877; + --dug-chip-medium-bg: #3A3013; + --dug-chip-medium-fg: #F0CF7A; + --dug-chip-low-bg: #272D36; + --dug-chip-low-fg: #C5CCD6; + --dug-chip-success-bg: #12301F; + --dug-chip-success-fg: #7BD8A4; + --dug-chip-info-bg: #172A4D; + --dug-chip-info-fg: #9CC0FF; + --dug-chart-cpu: #7AA7FF; + --dug-chart-cpu-fill: #172A4D; + --dug-chart-memory: #A98BEB; + --dug-chart-memory-fill: #2A2145; + --dug-chart-net-rx: #4FD1C5; + --dug-chart-net-tx: #F2A54A; } html, @@ -99,7 +121,9 @@ body { margin: 0; background: var(--dug-bg-page); color: var(--dug-text); - font-family: Inter, "Segoe UI", Arial, Helvetica, sans-serif; + font-family: var(--dug-font-text); + font-size: 0.875rem; + line-height: 1.45; } a { @@ -108,7 +132,7 @@ a { .app-layout { min-height: 100vh; - background: var(--dug-bg-gradient); + background: var(--dug-bg-page); } .app-drawer { @@ -117,10 +141,10 @@ a { .app-drawer .mud-drawer-content { padding: 1.75rem 1.25rem 1.5rem; - color: #e2e8f0; - background: linear-gradient(180deg, #0f172a 0%, #172554 100%); + color: var(--dug-text); + background: var(--dug-surface); border-right: 1px solid var(--dug-border); - box-shadow: 0 24px 60px rgba(15, 23, 42, 0.22); + box-shadow: none; } .app-drawer-content { @@ -132,21 +156,21 @@ a { height: 3rem; flex: 0 0 auto; border-radius: 0.9rem; - box-shadow: 0 10px 25px rgba(14, 165, 233, 0.25); } .app-brand__title { min-width: fit-content; - color: #f8fafc; + color: var(--dug-text); + font-family: var(--dug-font-display); font-size: clamp(1.15rem, 1.2rem + 0.3vw, 1.35rem); - font-weight: 800; + font-weight: 600; letter-spacing: -0.02em; white-space: nowrap; overflow-wrap: normal; } .app-nav-shell { - color: #e2e8f0; + color: var(--dug-text); display: flex; flex: 1 1 auto; flex-direction: column; @@ -164,7 +188,7 @@ a { } .nav-section-label { - color: rgba(191, 219, 254, 0.72); + color: var(--dug-text-muted); padding-inline: 0.75rem; } @@ -175,23 +199,25 @@ a { .app-nav-menu .mud-nav-link { margin-bottom: 0.35rem; padding: 1rem 1.05rem; - color: #e2e8f0; + color: var(--dug-text); border: 1px solid transparent; border-radius: var(--dug-radius-md); - transition: background 0.2s ease, transform 0.2s ease, border-color 0.2s ease; } .app-nav-menu .mud-nav-link:hover { - color: #ffffff; - background: linear-gradient(rgba(148, 163, 184, 0.12), rgba(148, 163, 184, 0.12)), #0f172a; - border-color: rgba(191, 219, 254, 0.12); - transform: translateX(2px); + color: var(--dug-text); + background: var(--dug-surface-subtle); } -.app-nav-menu .mud-nav-link.active { - background: linear-gradient(135deg, rgba(59, 130, 246, 0.22), rgba(6, 182, 212, 0.18)); - border-color: rgba(125, 211, 252, 0.22); - box-shadow: inset 0 0 0 1px rgba(125, 211, 252, 0.08); +.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) { + 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 { @@ -209,7 +235,7 @@ a { } .app-version__label { - color: #bfdbfe; + color: var(--dug-text-muted); font-size: 0.72rem; letter-spacing: 0.06em; text-transform: uppercase; @@ -217,7 +243,7 @@ a { .app-version__value { margin-top: 0.2rem; - color: rgba(226, 232, 240, 0.88); + color: var(--dug-text); font-size: 0.78rem; } @@ -226,7 +252,10 @@ a { } .mud-paper.app-topbar { - background: rgba(255, 255, 255, 0.72); + background: var(--dug-surface); + border: 1px solid var(--dug-border); + border-radius: var(--dug-radius-lg); + box-shadow: none; } .app-topbar { @@ -235,10 +264,6 @@ a { z-index: 1100; margin: 1.5rem 1.5rem 0.75rem; padding: 0.9rem 1.35rem; - backdrop-filter: blur(12px); - border: 1px solid var(--dug-border); - border-radius: var(--dug-radius-lg); - box-shadow: var(--dug-shadow-card); } .app-topbar__content { @@ -262,6 +287,7 @@ a { .app-topbar__title { color: var(--dug-text); + font-family: var(--dug-font-display); } .app-topbar__menu-button { @@ -286,7 +312,7 @@ a { .app-topbar__meta-card { min-width: 9rem; flex: 0 1 auto; - background: rgba(255, 255, 255, 0.78); + background: var(--dug-surface-subtle); } .app-topbar__status { @@ -343,15 +369,6 @@ a { gap: 1.25rem; } -.page-header h1, -.hero-panel h1, -.empty-state-panel h1 { - margin: 0; - font-size: clamp(1.8rem, 2.4vw, 2.6rem); - font-weight: 750; - letter-spacing: -0.03em; -} - .page-description, .hero-description, .section-description, @@ -371,32 +388,13 @@ a { .empty-state-panel, .summary-card { background: var(--dug-surface); - backdrop-filter: blur(10px); border: 1px solid var(--dug-border); border-radius: var(--dug-radius-lg); - box-shadow: var(--dug-shadow-card); -} - -.hero-panel, -.section-paper--accent { - position: relative; - overflow: hidden; -} - -.hero-panel::before, -.section-paper--accent::before { - content: ""; - position: absolute; - inset: 0 0 auto 0; - height: 3px; - background: linear-gradient(90deg, var(--dug-primary), var(--dug-secondary)); + box-shadow: none; } .hero-panel { padding: 2rem; - background: - linear-gradient(135deg, rgba(37, 99, 235, 0.10), rgba(14, 165, 233, 0.08)), - rgba(255, 255, 255, 0.9); } .hero-meta-card, @@ -423,8 +421,8 @@ a { } .metric-card--warning .metric-card__icon { - background: color-mix(in srgb, var(--dug-warning) 14%, transparent); - color: var(--dug-warning); + background: color-mix(in srgb, var(--dug-attention) 14%, transparent); + color: var(--dug-attention); } .metric-card--danger .metric-card__icon { @@ -432,6 +430,14 @@ a { color: var(--dug-danger); } +.metric-card--warning .metric-value { + color: var(--dug-attention); +} + +.metric-card--danger .metric-value { + color: var(--dug-danger); +} + .metric-card-link { display: block; height: 100%; @@ -447,48 +453,34 @@ a { .summary-card, .app-nav-menu .mud-nav-link, .mud-button-root { - transition: transform var(--dug-transition), box-shadow var(--dug-transition), border-color var(--dug-transition), background-color var(--dug-transition); -} - -.metric-card-link:hover .metric-card, -.metric-card-link:focus-visible .metric-card { - transform: translateY(-2px); - border-color: rgba(37, 99, 235, 0.35); - box-shadow: var(--dug-shadow-hover); + transition: border-color var(--dug-transition), background-color var(--dug-transition); } -.metric-card:hover, -.summary-card:hover, -.app-nav-menu .mud-nav-link:hover, -.mud-button-root:hover { - box-shadow: var(--dug-shadow-hover); +.metric-card-link:hover .metric-card { + border-color: var(--dug-border-control); } -.metric-card:active, -.summary-card:active, -.app-nav-menu .mud-nav-link:active, -.mud-button-root:active { - transform: scale(0.99); +.metric-card-link:focus-visible .metric-card { + outline: 2px solid var(--dug-primary); + outline-offset: 2px; } -.metric-card:focus-visible, -.summary-card:focus-visible, .app-nav-menu .mud-nav-link:focus-visible, .mud-button-root:focus-visible { outline: 2px solid var(--dug-primary); outline-offset: 2px; } -.metric-card--warning { - background: - linear-gradient(135deg, rgba(245, 158, 11, 0.12), rgba(255, 255, 255, 0.88)), - rgba(255, 255, 255, 0.92); +.mud-button-filled, +.mud-button-filled:hover, +.mud-button-filled:active, +.mud-button-filled:focus-visible { + box-shadow: none; } -.metric-card--danger { - background: - linear-gradient(135deg, rgba(239, 68, 68, 0.10), rgba(255, 255, 255, 0.88)), - rgba(255, 255, 255, 0.92); +.mud-popover:not(.mud-tooltip), +.mud-dialog { + border: 1px solid var(--dug-border); } .metric-label { @@ -500,9 +492,10 @@ a { .metric-value { display: block; margin-top: 0.5rem; + font-family: var(--dug-font-display); font-size: clamp(1.5rem, 5vw, 1.95rem); font-variant-numeric: tabular-nums; - font-weight: 750; + font-weight: 600; letter-spacing: -0.03em; } @@ -510,22 +503,10 @@ a { padding: 1.5rem 1.6rem; } -.section-paper--accent { - background: - linear-gradient(135deg, rgba(37, 99, 235, 0.08), rgba(14, 165, 233, 0.05)), - rgba(255, 255, 255, 0.92); -} - .section-header { margin-bottom: 1.25rem; } -.section-header h2 { - margin: 0; - font-size: 1.2rem; - font-weight: 700; -} - .summary-grid { gap: 1rem; } @@ -554,11 +535,7 @@ a { } .summary-remediation--warning { - color: var(--dug-warning); -} - -.dug-dark .summary-remediation--warning { - color: #f59e0b; + color: var(--dug-attention); } .summary-card__detail-toggle.mud-button-root { @@ -606,12 +583,13 @@ a { } .table-link { - color: var(--dug-primary-strong); + color: var(--dug-link); font-weight: 600; } .table-link:hover { - color: #1e40af; + color: var(--dug-link); + text-decoration: underline; } .table-secondary { @@ -635,12 +613,13 @@ a { .section-table .mud-table-container { border-radius: var(--dug-radius-md); - border: 1px solid rgba(226, 232, 240, 0.92); - background: rgba(255, 255, 255, 0.88); + border: 1px solid var(--dug-border); + background: var(--dug-surface); } .section-table .mud-table-head .mud-table-cell { color: var(--dug-text-muted); + border-bottom: 1px solid var(--dug-border); font-size: 0.8rem; font-weight: 700; letter-spacing: 0.05em; @@ -707,7 +686,7 @@ a { } .runtime-containers-table .runtime-containers-table__name-icon-link:hover { - color: var(--dug-primary-strong); + color: var(--dug-link); } .runtime-containers-table .runtime-containers-table__name-icon { @@ -735,19 +714,19 @@ a { } .runtime-containers-table .runtime-containers-table__sparkline-line--cpu { - stroke: var(--dug-primary); + stroke: var(--dug-chart-cpu); } .runtime-containers-table .runtime-containers-table__sparkline-line--memory { - stroke: #7c3aed; + stroke: var(--dug-chart-memory); } .runtime-containers-table .runtime-containers-table__sparkline-line--network-rx { - stroke: var(--dug-secondary); + stroke: var(--dug-chart-net-rx); } .runtime-containers-table .runtime-containers-table__sparkline-line--network-tx { - stroke: #ea580c; + stroke: var(--dug-chart-net-tx); } .details-grid { @@ -797,10 +776,9 @@ a { display: block; margin-bottom: 0.75rem; padding: 0.9rem 1rem; - background: var(--dug-surface-solid); + background: var(--dug-surface); border: 1px solid var(--dug-border); border-radius: var(--dug-radius-md); - box-shadow: var(--dug-shadow-card); } .section-table .mud-table-body .mud-table-cell { @@ -842,22 +820,6 @@ a { .dug-chart { height: 240px; } - - .section-table .mud-table-body .mud-table-row.dug-rail-critical { - box-shadow: var(--dug-shadow-card), inset 3px 0 0 var(--dug-sev-critical); - } - - .section-table .mud-table-body .mud-table-row.dug-rail-high { - box-shadow: var(--dug-shadow-card), inset 3px 0 0 var(--dug-sev-high); - } - - .section-table .mud-table-body .mud-table-row.dug-rail-medium { - box-shadow: var(--dug-shadow-card), inset 3px 0 0 var(--dug-sev-medium); - } - - .section-table .mud-table-body .mud-table-row.dug-rail-low { - box-shadow: var(--dug-shadow-card), inset 3px 0 0 var(--dug-sev-low); - } } @media (max-width: 599.98px) { @@ -924,4 +886,4 @@ a { transition-duration: 0.01ms !important; animation-duration: 0.01ms !important; } -} +} \ No newline at end of file diff --git a/src/DockerUpdateGuard/wwwroot/fonts/SpaceGrotesk-OFL.txt b/src/DockerUpdateGuard/wwwroot/fonts/SpaceGrotesk-OFL.txt new file mode 100644 index 00000000..d5666d70 --- /dev/null +++ b/src/DockerUpdateGuard/wwwroot/fonts/SpaceGrotesk-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2020 The Space Grotesk Project Authors (https://github.com/floriankarsten/space-grotesk) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/src/DockerUpdateGuard/wwwroot/fonts/SpaceGrotesk-Variable-latin.woff2 b/src/DockerUpdateGuard/wwwroot/fonts/SpaceGrotesk-Variable-latin.woff2 new file mode 100644 index 00000000..0f3474ee Binary files /dev/null and b/src/DockerUpdateGuard/wwwroot/fonts/SpaceGrotesk-Variable-latin.woff2 differ diff --git a/src/Tests/DockerUpdateGuard.Tests/AppStylesheetTests.cs b/src/Tests/DockerUpdateGuard.Tests/AppStylesheetTests.cs new file mode 100644 index 00000000..ef5909ca --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/AppStylesheetTests.cs @@ -0,0 +1,866 @@ +using System.Reflection; +using System.Text.RegularExpressions; + +using DockerUpdateGuard.Tests.Helper; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for the shipped stylesheet wwwroot/app.css: tokens, banned constructs, fonts and the rules of the flat refresh +/// +[TestClass] +public class AppStylesheetTests +{ + #region Constants + + /// + /// Selector of the dark token block: it reaches the document root while the layout is dark + /// + private const string DarkBlockSelector = ":is(.dug-dark, :root:has(.dug-dark))"; + + /// + /// Minimum contrast of a text against its background (WCAG AA for normal text) + /// + private const double MinimumContrast = 4.5; + + /// + /// Shipped stylesheet below the host project directory + /// + private const string StylesheetPath = "wwwroot/app.css"; + + /// + /// Value of a panel's hairline border + /// + private const string HairlineBorder = "1px solid var(--dug-border)"; + + /// + /// Media context of the card layout of table rows + /// + private const string RowCardContext = "@media (max-width: 959.98px)"; + + #endregion // Constants + + #region Fields + + /// + /// Tokens of issue #451 section 1: name, light value, dark value (null when the table gives none) + /// + private static readonly (string Name, string Light, string? Dark)[] _tokens = [ + ("--dug-bg-page", "#F6F7F9", "#0F1216"), + ("--dug-surface", "#FFFFFF", "#171B21"), + ("--dug-surface-solid", "#FFFFFF", "#171B21"), + ("--dug-surface-subtle", "#FAFBFC", "#1B2027"), + ("--dug-border", "#E3E6EB", "#272D36"), + ("--dug-border-inner", "#EEF0F3", "#20262E"), + ("--dug-border-control", "#C9CED6", "#3A424E"), + ("--dug-text", "#16191D", "#E7EAEE"), + ("--dug-text-muted", "#5B6471", "#9BA5B3"), + ("--dug-text-faint", "#5B6471", "#9BA5B3"), + ("--dug-icon", "#3D4551", "#C5CCD6"), + ("--dug-primary", "#2563EB", "#7AA7FF"), + ("--dug-on-primary", "#FFFFFF", "#0F1216"), + ("--dug-link", "#1D4ED8", "#7AA7FF"), + ("--dug-attention", "#B54708", "#F2A54A"), + ("--dug-danger", "#B42318", "#FF8A80"), + ("--dug-success", "#067647", "#5FD39A"), + ("--dug-info", "#1D4ED8", "#9CC0FF"), + ("--dug-sev-critical", "#7A1C12", "#FF7B72"), + ("--dug-sev-high", "#D9480F", "#E0762B"), + ("--dug-sev-medium", "#E8A33D", "#A67C1F"), + ("--dug-sev-low", "#C9CED6", "#4A5361"), + ("--dug-scan-succeeded", "#9FB3C8", "#46566B"), + ("--dug-scan-partial", "#E8A33D", "#E0A23D"), + ("--dug-scan-failed", "#7A1C12", "#FF7B72"), + ("--dug-chart-cpu", "#2563EB", "#7AA7FF"), + ("--dug-chart-cpu-fill", "#E8EFFD", "#172A4D"), + ("--dug-chart-memory", "#6D4AC4", "#A98BEB"), + ("--dug-chart-memory-fill", "#EFEAFA", "#2A2145"), + ("--dug-chart-net-rx", "#0F766E", "#4FD1C5"), + ("--dug-chart-net-tx", "#B54708", "#F2A54A"), + ("--dug-radius-lg", "8px", null), + ("--dug-radius-md", "6px", null), + ("--dug-radius-sm", "4px", null), + ("--dug-font-text", "Inter, \"Segoe UI\", Arial, Helvetica, sans-serif", null), + ("--dug-font-display", "\"Space Grotesk\", Inter, \"Segoe UI\", Arial, sans-serif", null), + ("--dug-transition", "0.18s ease", null), + ]; + + /// + /// Chip tokens of issue #451 section 1: chip name, light background, light text, dark background, dark text + /// + private static readonly (string Chip, string LightBackground, string LightText, string DarkBackground, string DarkText)[] _chips = [ + ("critical", "#7A1C12", "#FFFFFF", "#FF7B72", "#1A0B0A"), + ("high", "#FFF1E6", "#9A3D00", "#3A2413", "#FFB877"), + ("medium", "#FDF3D7", "#7A5200", "#3A3013", "#F0CF7A"), + ("low", "#EEF0F3", "#3D4551", "#272D36", "#C5CCD6"), + ("success", "#E6F4EC", "#05603A", "#12301F", "#7BD8A4"), + ("info", "#E8EFFD", "#1D4ED8", "#172A4D", "#9CC0FF"), + ]; + + /// + /// Text tokens whose contrast is checked on each ground + /// + private static readonly string[] _textTokens = [ + "--dug-text", + "--dug-text-muted", + "--dug-text-faint", + "--dug-icon", + "--dug-primary", + "--dug-link", + "--dug-attention", + "--dug-danger", + "--dug-success", + "--dug-info", + ]; + + /// + /// Ground tokens text is drawn on + /// + private static readonly string[] _groundTokens = [ + "--dug-bg-page", + "--dug-surface", + "--dug-surface-subtle", + ]; + + /// + /// Tokens removed by the refresh + /// + private static readonly string[] _removedTokens = [ + "--dug-secondary", + "--dug-primary-strong", + "--dug-warning", + "--dug-shadow-card", + "--dug-shadow-hover", + "--dug-blur", + "--dug-bg-gradient", + ]; + + /// + /// Properties that take a color + /// + private static readonly Regex _colorPropertyPattern = new("^(color|background|background-color|border|border-(top|right|bottom|left)(-color)?|border-color|outline|outline-color|fill|stroke|text-decoration|text-decoration-color|caret-color|accent-color|column-rule)$", + RegexOptions.CultureInvariant, + TimeSpan.FromSeconds(5)); + + /// + /// Color notations and hexadecimal colors a rule outside the token blocks may not carry + /// + private static readonly Regex _colorLiteralPattern = new(@"#[0-9a-fA-F]{3,8}\b|\b(rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color)\(", + RegexOptions.CultureInvariant, + TimeSpan.FromSeconds(5)); + + /// + /// Named colors a color property of a rule outside the token blocks may not carry + /// + private static readonly Regex _namedColorPattern = new("(? + /// Box shadow declaration of a stylesheet + /// + private static readonly Regex _boxShadowPattern = new(@"box-shadow\s*:\s*([^;}]+)", + RegexOptions.CultureInvariant, + TimeSpan.FromSeconds(5)); + + /// + /// An http(s) address or a protocol-relative url() target + /// + private static readonly Regex _externalAddressPattern = new(@"https?://|url\(\s*[""']?//", + RegexOptions.CultureInvariant | RegexOptions.IgnoreCase, + TimeSpan.FromSeconds(5)); + + #endregion // Fields + + #region Static methods + + /// + /// Contrast pairs of both themes: theme, text token, ground token + /// + /// Rows of theme, text token and ground token + public static IEnumerable GetContrastPairs() + { + foreach (var theme in new[] { "light", "dark" }) + { + foreach (var textToken in _textTokens) + { + foreach (var groundToken in _groundTokens) + { + yield return [theme, textToken, groundToken]; + } + } + + yield return [theme, "--dug-on-primary", "--dug-primary"]; + + foreach (var chip in _chips) + { + yield return [theme, $"--dug-chip-{chip.Chip}-fg", $"--dug-chip-{chip.Chip}-bg"]; + } + } + } + + /// + /// Name a contrast row by its pair + /// + /// Test method + /// Data row + /// Display name + public static string GetPairDisplayName(MethodInfo methodInfo, object?[] data) + { + return $"{methodInfo.Name} ({data[0]}: {data[1]} on {data[2]})"; + } + + #endregion // Static methods + + #region Methods + + /// + /// Verify the stylesheet carries no blur, no gradient and no box shadow that is neither none nor an inset line + /// + [TestMethod] + [TestCategory("AC1")] + public void AppStylesheetContainsNoBlurGradientOrElevationShadow() + { + var css = StylesheetReader.StripComments(ReadStylesheet()); + + Assert.DoesNotContain("backdrop-filter", css, "The stylesheet must not blur what is behind a surface"); + Assert.DoesNotContain("blur(", css, "The stylesheet must not blur anything"); + Assert.DoesNotContain("gradient(", css, "The stylesheet must not draw a gradient"); + AssertNoMismatches(FindElevationShadows(css), "Every box-shadow must be none or an inset line"); + } + + /// + /// Verify none of the removed tokens is declared or used + /// + [TestMethod] + [TestCategory("AC1")] + public void AppStylesheetContainsNoRemovedToken() + { + var css = StylesheetReader.StripComments(ReadStylesheet()); + + var found = _removedTokens.Where(token => Regex.IsMatch(css, Regex.Escape(token) + @"(?![\w-])", RegexOptions.None, TimeSpan.FromSeconds(5))) + .ToList(); + + AssertNoMismatches(found, "No removed token may remain declared or referenced"); + } + + /// + /// Verify the only rule that names the dark class is the dark token block, and it holds nothing but custom properties + /// + [TestMethod] + [TestCategory("AC1")] + [TestCategory("AC2")] + public void AppStylesheetHasNoDarkRuleBesideTokenBlock() + { + var darkRules = StylesheetReader.GetRules(ReadStylesheet()) + .Where(rule => rule.Selector.Contains(".dug-dark", StringComparison.Ordinal)) + .ToList(); + + Assert.HasCount(1, darkRules, "Exactly one rule may name .dug-dark: the dark token block"); + Assert.AreEqual(DarkBlockSelector, darkRules[0].Selector, "The dark token block must use the document-wide selector"); + + var declarations = StylesheetReader.GetDeclarationList(darkRules[0].Body); + var customProperties = StylesheetReader.GetCustomProperties(darkRules[0].Body); + + Assert.HasCount(declarations.Count, customProperties, "The dark token block must hold only custom properties"); + } + + /// + /// Verify rules outside the two token blocks use no color literal, only token references, inherit, transparent, currentColor or a color-mix of tokens + /// + [TestMethod] + [TestCategory("AC1")] + public void AppStylesheetRulesOutsideTokenBlocksUseOnlyTokenColors() + { + var rules = StylesheetReader.GetRules(ReadStylesheet()) + .Where(rule => rule.Selector != ":root" && rule.Selector != DarkBlockSelector && rule.Selector != "@font-face") + .ToList(); + + var offenders = rules.SelectMany(FindColorLiterals).ToList(); + + AssertNoMismatches(offenders, "Outside the token blocks every color must be a token reference"); + } + + /// + /// Verify :root holds every light token of the issue's tables with its light value + /// + [TestMethod] + [TestCategory("AC2")] + public void AppStylesheetRootBlockHoldsEveryLightToken() + { + var properties = GetRootTokens(); + + var expected = _tokens.Select(token => (token.Name, token.Light)) + .Concat(_chips.SelectMany(chip => new[] { ($"--dug-chip-{chip.Chip}-bg", chip.LightBackground), ($"--dug-chip-{chip.Chip}-fg", chip.LightText) })); + + AssertNoMismatches(FindTokenMismatches(properties, expected), "The :root block must hold every light token"); + } + + /// + /// Verify the dark block holds every token of the issue's tables that has a dark value, with that value + /// + [TestMethod] + [TestCategory("AC2")] + public void AppStylesheetDarkBlockHoldsEveryDarkToken() + { + var properties = GetDarkBlockTokens(); + + var expected = _tokens.Where(token => token.Dark is not null) + .Select(token => (token.Name, token.Dark!)) + .Concat(_chips.SelectMany(chip => new[] { ($"--dug-chip-{chip.Chip}-bg", chip.DarkBackground), ($"--dug-chip-{chip.Chip}-fg", chip.DarkText) })); + + AssertNoMismatches(FindTokenMismatches(properties, expected), "The dark block must hold every dark token"); + } + + /// + /// Verify the dark block reaches the whole document while the layout carries the dark class and wins over :root + /// + [TestMethod] + [TestCategory("AC2")] + public void AppStylesheetDarkBlockAppliesToDocumentWhileLayoutIsDark() + { + var rules = StylesheetReader.GetRules(ReadStylesheet()).ToList(); + + var rootIndex = rules.FindIndex(rule => rule.Selector == ":root"); + var darkIndex = rules.FindIndex(rule => rule.Selector == DarkBlockSelector); + + Assert.IsGreaterThanOrEqualTo(0, rootIndex, "The :root block must exist"); + Assert.IsGreaterThan(rootIndex, darkIndex, "The dark block must follow :root so that it wins at equal specificity"); + } + + /// + /// Verify Space Grotesk is declared as a variable latin font face with a swap display, after Inter's + /// + [TestMethod] + [TestCategory("AC3")] + public void AppStylesheetDeclaresSpaceGroteskFontFace() + { + var fontFaces = StylesheetReader.GetRules(ReadStylesheet()) + .Where(rule => rule.Selector == "@font-face") + .Select(rule => StylesheetReader.GetDeclarationList(rule.Body).ToDictionary(declaration => declaration.Name, declaration => declaration.Value)) + .ToList(); + + var interIndex = fontFaces.FindIndex(face => face.GetValueOrDefault("font-family") == "\"Inter\""); + var groteskIndex = fontFaces.FindIndex(face => face.GetValueOrDefault("font-family") == "\"Space Grotesk\""); + + Assert.IsGreaterThanOrEqualTo(0, interIndex, "Inter's font face must stay"); + Assert.IsGreaterThan(interIndex, groteskIndex, "The Space Grotesk font face must be declared after Inter's"); + + var grotesk = fontFaces[groteskIndex]; + var expected = new (string Name, string Value)[] + { + ("src", "url(\"fonts/SpaceGrotesk-Variable-latin.woff2\") format(\"woff2\")"), + ("font-weight", "300 700"), + ("font-style", "normal"), + ("font-display", "swap") + }; + + AssertNoMismatches(FindDeclarationMismatches("@font-face Space Grotesk", grotesk, expected), "The Space Grotesk font face must name the shipped file, its weights and swap"); + } + + /// + /// Verify the body uses the text font at 14 px with a line height of 1.45 and figures and the product name use the display font + /// + [TestMethod] + [TestCategory("AC4")] + public void AppStylesheetSetsTextAndDisplayFonts() + { + var css = ReadStylesheet(); + + var mismatches = FindDeclarationMismatches("body", + StylesheetReader.GetDeclarations(css, "body"), + [("font-family", "var(--dug-font-text)"), ("font-size", "0.875rem"), ("line-height", "1.45")]).Concat(FindDeclarationMismatches(".metric-value", + StylesheetReader.GetDeclarations(css, ".metric-value"), + [("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")])) + .ToList(); + + AssertNoMismatches(mismatches, "Text, figures and the product name must use the fonts of the refresh"); + } + + /// + /// Verify the dead heading rules that match no element are deleted, because the theme sizes the headings + /// + [TestMethod] + [TestCategory("AC4")] + public void AppStylesheetHasNoRuleForHeadingsThatDoNotExist() + { + var selectors = StylesheetReader.GetRules(ReadStylesheet()) + .Select(rule => rule.Selector) + .Where(selector => selector.Contains(".page-header h1", StringComparison.Ordinal) || selector.Contains(".section-header h2", StringComparison.Ordinal)) + .ToList(); + + AssertNoMismatches(selectors, "No rule may target .page-header h1 or .section-header h2"); + } + + /// + /// Verify each text and chip pair of the token tables reaches the minimum contrast in the theme + /// + /// Theme: light or dark + /// Text token + /// Ground token + [TestMethod] + [TestCategory("AC6")] + [DynamicData(nameof(GetContrastPairs), DynamicDataDisplayName = nameof(GetPairDisplayName))] + public void AppStylesheetTokenPairsReachMinimumContrast(string theme, string textToken, string groundToken) + { + var tokens = theme == "dark" ? GetEffectiveDarkTokens() : GetRootTokens(); + + var ratio = ContrastRatio.Calculate(GetColor(tokens, textToken), GetColor(tokens, groundToken)); + + Assert.IsGreaterThanOrEqualTo(MinimumContrast, ratio, $"{textToken} on {groundToken} in the {theme} theme has a contrast of {ratio:0.00}:1"); + } + + /// + /// Verify no hover or active rule moves, scales or rotates an element + /// + [TestMethod] + [TestCategory("AC7")] + public void AppStylesheetInteractionRulesNeitherMoveNorScale() + { + string[] movingProperties = ["transform", "translate", "scale", "rotate"]; + + var offenders = StylesheetReader.GetRules(ReadStylesheet()) + .Where(rule => rule.Selector.Contains(":hover", StringComparison.Ordinal) || rule.Selector.Contains(":active", StringComparison.Ordinal)) + .SelectMany(rule => StylesheetReader.GetDeclarationList(rule.Body) + .Where(declaration => movingProperties.Contains(declaration.Name)) + .Select(declaration => $"{rule.Selector} sets {declaration.Name}")) + .ToList(); + + AssertNoMismatches(offenders, "Hovering or pressing must neither move nor scale anything"); + } + + /// + /// Verify a dashboard metric card changes only its border on hover, shows the 2 px primary outline on keyboard focus of its link, and the link has no own outline + /// + [TestMethod] + [TestCategory("AC7")] + public void AppStylesheetMetricCardHoverChangesOnlyBorderAndFocusDrawsPrimaryOutline() + { + var css = ReadStylesheet(); + + var hover = StylesheetReader.GetDeclarations(css, ".metric-card-link:hover .metric-card"); + var focus = StylesheetReader.GetDeclarations(css, ".metric-card-link:focus-visible .metric-card"); + var link = StylesheetReader.GetDeclarations(css, ".metric-card-link:focus-visible"); + + var mismatches = FindDeclarationMismatches(".metric-card-link:hover .metric-card", hover, [("border-color", "var(--dug-border-control)")]).Concat(FindDeclarationMismatches(".metric-card-link:focus-visible .metric-card", focus, [("outline", "2px solid var(--dug-primary)"), ("outline-offset", "2px")])) + .ToList(); + + Assert.HasCount(1, hover, "The hover rule of a metric card may change only its border color"); + Assert.DoesNotContain("outline", link.Keys, "The link itself must not draw an outline, the card does"); + AssertNoMismatches(mismatches, "The metric card must change its border on hover and draw the primary outline on focus"); + } + + /// + /// Verify summary cards, which are not clickable, have no hover rule and no focus rule of their own + /// + [TestMethod] + [TestCategory("AC7")] + public void AppStylesheetSummaryAndMetricCardsHaveNoOwnHoverOrFocusRule() + { + var selectors = StylesheetReader.GetRules(ReadStylesheet()) + .SelectMany(rule => StylesheetReader.SplitTopLevel(rule.Selector, ',')) + .Where(selector => selector is ".summary-card:hover" or ".summary-card:active" or ".summary-card:focus-visible" or ".metric-card:hover" or ".metric-card:active" or ".metric-card:focus-visible") + .ToList(); + + AssertNoMismatches(selectors, "Only the link of a metric card reacts to hover and focus"); + } + + /// + /// Verify transitions animate only border and background colors + /// + [TestMethod] + [TestCategory("AC7")] + public void AppStylesheetTransitionsAnimateOnlyBorderAndBackgroundColors() + { + string[] allowed = ["border-color", "background-color", "none"]; + + var offenders = StylesheetReader.GetRules(ReadStylesheet()) + .SelectMany(rule => StylesheetReader.GetDeclarationList(rule.Body) + .Where(declaration => declaration.Name is "transition" or "transition-property") + .SelectMany(declaration => StylesheetReader.SplitTopLevel(declaration.Value, ',') + .Select(part => part.Split(' ')[0]) + .Where(property => allowed.Contains(property) == false) + .Select(property => $"{rule.Selector} transitions {property}"))) + .ToList(); + + AssertNoMismatches(offenders, "Only border-color and background-color may transition"); + } + + /// + /// Verify each panel is an opaque surface with a hairline border and the large radius, and the page ground is the plain page color + /// + /// Panel selector + [TestMethod] + [TestCategory("AC7")] + [DataRow(".hero-panel")] + [DataRow(".metric-card")] + [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); + var mismatches = FindDeclarationMismatches(selector, declarations, [("border", HairlineBorder), ("border-radius", "var(--dug-radius-lg)")]).ToList(); + + mismatches.AddRange(FindDeclarationMismatches(selector, ReadBackground(declarations), [("background", "var(--dug-surface)")])); + + AssertNoMismatches(mismatches, $"{selector} must be a flat surface panel"); + } + + /// + /// Verify the layout ground is the plain page color + /// + [TestMethod] + [TestCategory("AC7")] + public void AppStylesheetLayoutGroundIsPlainPageColor() + { + var declarations = StylesheetReader.GetDeclarations(ReadStylesheet(), ".app-layout"); + + var mismatches = FindDeclarationMismatches(".app-layout", ReadBackground(declarations), [("background", "var(--dug-bg-page)")]); + + AssertNoMismatches(mismatches, "The layout must have the plain page ground"); + } + + /// + /// Verify the drawer is a surface-colored panel with a hairline on its right and no shadow, with its texts in the token colors + /// + [TestMethod] + [TestCategory("AC7")] + 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 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(".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"); + } + + /// + /// Verify links use the link color and the sparklines the four chart line colors + /// + [TestMethod] + [TestCategory("AC7")] + public void AppStylesheetLinksAndSparklinesUseTokenColors() + { + var css = ReadStylesheet(); + const string sparkline = ".runtime-containers-table .runtime-containers-table__sparkline-line--"; + + var mismatches = FindDeclarationMismatches(".table-link", StylesheetReader.GetDeclarations(css, ".table-link"), [("color", "var(--dug-link)")]).Concat(FindDeclarationMismatches(".table-link:hover", StylesheetReader.GetDeclarations(css, ".table-link:hover"), [("color", "var(--dug-link)"), ("text-decoration", "underline")])) + .Concat(FindDeclarationMismatches("cpu sparkline", StylesheetReader.GetDeclarations(css, sparkline + "cpu"), [("stroke", "var(--dug-chart-cpu)")])) + .Concat(FindDeclarationMismatches("memory sparkline", StylesheetReader.GetDeclarations(css, sparkline + "memory"), [("stroke", "var(--dug-chart-memory)")])) + .Concat(FindDeclarationMismatches("received sparkline", StylesheetReader.GetDeclarations(css, sparkline + "network-rx"), [("stroke", "var(--dug-chart-net-rx)")])) + .Concat(FindDeclarationMismatches("sent sparkline", StylesheetReader.GetDeclarations(css, sparkline + "network-tx"), [("stroke", "var(--dug-chart-net-tx)")])) + .ToList(); + + AssertNoMismatches(mismatches, "Links and sparklines must use the link and chart tokens"); + } + + /// + /// Verify the warning and danger metric cards differ from other cards only by the color of their figure and icon + /// + [TestMethod] + [TestCategory("AC7")] + public void AppStylesheetWarningAndDangerCardsColorOnlyFigureAndIcon() + { + var css = ReadStylesheet(); + + var mismatches = FindDeclarationMismatches(".metric-card--warning .metric-value", StylesheetReader.GetDeclarations(css, ".metric-card--warning .metric-value"), [("color", "var(--dug-attention)")]).Concat(FindDeclarationMismatches(".metric-card--danger .metric-value", StylesheetReader.GetDeclarations(css, ".metric-card--danger .metric-value"), [("color", "var(--dug-danger)")])) + .Concat(FindDeclarationMismatches(".metric-card--warning .metric-card__icon", StylesheetReader.GetDeclarations(css, ".metric-card--warning .metric-card__icon"), [("color", "var(--dug-attention)")])) + .Concat(FindDeclarationMismatches(".metric-card--danger .metric-card__icon", StylesheetReader.GetDeclarations(css, ".metric-card--danger .metric-card__icon"), [("color", "var(--dug-danger)")])) + .Concat(FindTintedBackgrounds(css, ".metric-card--warning")) + .Concat(FindTintedBackgrounds(css, ".metric-card--danger")) + .ToList(); + + AssertNoMismatches(mismatches, "Warning and danger cards must look like other cards except for their figure and icon color"); + } + + /// + /// Verify below 960 px a table row is a flat card: surface, hairline border, control radius + /// + [TestMethod] + [TestCategory("AC7")] + public void AppStylesheetRowCardsBelowBreakpointAreFlatSurfaceCards() + { + var body = StylesheetReader.GetRules(ReadStylesheet()) + .Where(rule => rule.Context == RowCardContext && rule.Selector == ".section-table .mud-table-body .mud-table-row") + .Select(rule => rule.Body) + .FirstOrDefault(); + + Assert.IsNotNull(body, "The row card rule must stay below 960 px"); + + var declarations = StylesheetReader.GetDeclarationList(body).ToDictionary(declaration => declaration.Name, declaration => declaration.Value); + + var mismatches = FindDeclarationMismatches("row card", declarations, [("border", HairlineBorder), ("border-radius", "var(--dug-radius-md)")]).Concat(FindDeclarationMismatches("row card", ReadBackground(declarations), [("background", "var(--dug-surface)")])) + .ToList(); + + AssertNoMismatches(mismatches, "A row card must be flat"); + } + + /// + /// Verify filled buttons show no shadow in any state and popovers other than tooltips and dialogs get a hairline border + /// + [TestMethod] + [TestCategory("AC8")] + public void AppStylesheetFlattensFilledButtonsAndBordersFloatingLayers() + { + var css = ReadStylesheet(); + string[] buttonSelectors = [".mud-button-filled", ".mud-button-filled:hover", ".mud-button-filled:active", ".mud-button-filled:focus-visible"]; + + var mismatches = buttonSelectors.SelectMany(selector => FindDeclarationMismatches(selector, StylesheetReader.GetDeclarations(css, selector), [("box-shadow", "none")])) + .Concat(FindDeclarationMismatches(".mud-dialog", StylesheetReader.GetDeclarations(css, ".mud-dialog"), [("border", HairlineBorder)])) + .ToList(); + + var popover = StylesheetReader.GetDeclarations(css, ".mud-popover:not(.mud-tooltip)"); + + if (popover.Count == 0) + { + popover = StylesheetReader.GetDeclarations(css, ".mud-popover"); + } + + mismatches.AddRange(FindDeclarationMismatches(".mud-popover", popover, [("border", HairlineBorder)])); + + AssertNoMismatches(mismatches, "Filled buttons must be flat and floating layers must be bordered"); + } + + /// + /// Verify the reduced-motion media rule stays and zeroes the transition and animation durations of every element + /// + [TestMethod] + [TestCategory("AC7")] + public void AppStylesheetKeepsReducedMotionRule() + { + const string context = "@media (prefers-reduced-motion: reduce)"; + + var declarations = StylesheetReader.GetRules(ReadStylesheet()) + .Where(rule => rule.Context == context && rule.Selector == "*, *::before, *::after") + .SelectMany(rule => StylesheetReader.GetDeclarationList(rule.Body)) + .ToList(); + + Assert.AreSequenceEqual(new[] { ("transition-duration", "0.01ms !important"), ("animation-duration", "0.01ms !important") }, + declarations, + "The reduced-motion rule must set both durations to 0.01ms !important for every element and pseudo-element"); + } + + /// + /// Verify neither the document nor the stylesheet names an external address: no http(s) address and no protocol-relative url + /// + [TestMethod] + [TestCategory("AC3")] + public void AppAndStylesheetReferenceNoExternalAddress() + { + var offenders = new[] { "Components/App.razor", StylesheetPath }.SelectMany(path => FindExternalAddresses(path)) + .ToList(); + + AssertNoMismatches(offenders, "App.razor and app.css must not reference an external address"); + } + + #endregion // Methods + + #region Helper methods + + /// + /// Read the shipped stylesheet with normalized line endings + /// + /// Stylesheet text + private static string ReadStylesheet() + { + return StylesheetReader.ReadHostFile(StylesheetPath); + } + + /// + /// Read the custom properties of the :root block + /// + /// Custom property name to value + private static Dictionary GetRootTokens() + { + var body = StylesheetReader.GetRuleBody(ReadStylesheet(), ":root"); + + Assert.IsNotNull(body, "The stylesheet must have a :root block"); + + return StylesheetReader.GetCustomProperties(body); + } + + /// + /// Read the custom properties of the dark token block + /// + /// Custom property name to value + private static Dictionary GetDarkBlockTokens() + { + var body = StylesheetReader.GetRuleBody(ReadStylesheet(), DarkBlockSelector); + + Assert.IsNotNull(body, "The stylesheet must have the dark token block"); + + return StylesheetReader.GetCustomProperties(body); + } + + /// + /// Read the tokens a dark layout resolves: the light tokens overridden by the dark block + /// + /// Custom property name to value + private static Dictionary GetEffectiveDarkTokens() + { + var tokens = GetRootTokens(); + + foreach (var (name, value) in GetDarkBlockTokens()) + { + tokens[name] = value; + } + + return tokens; + } + + /// + /// Read a color token, failing the test when it is missing + /// + /// Resolved tokens + /// Token name + /// Color as #RRGGBB + private static string GetColor(Dictionary tokens, string name) + { + if (tokens.TryGetValue(name, out var value) == false) + { + Assert.Fail($"The token {name} must be declared"); + } + + return value; + } + + /// + /// Pick the background declaration of a rule, as background, whichever of background and background-color it uses + /// + /// Declarations of the rule + /// Map with the background entry, empty when the rule sets none + private static Dictionary ReadBackground(Dictionary declarations) + { + var background = new Dictionary(StringComparer.Ordinal); + + if (declarations.TryGetValue("background-color", out var color)) + { + background["background"] = color; + } + else if (declarations.TryGetValue("background", out var shorthand)) + { + background["background"] = shorthand; + } + + return background; + } + + /// + /// Compare a token map with expected token values, ignoring the letter case of the values + /// + /// Declared tokens + /// Expected name and value pairs + /// One text per missing or different token + private static List FindTokenMismatches(Dictionary actual, IEnumerable<(string Name, string Value)> expected) + { + var mismatches = new List(); + + foreach (var (name, value) in expected) + { + if (actual.TryGetValue(name, out var declared) == false) + { + mismatches.Add($"{name} is missing"); + } + else if (string.Equals(declared, value, StringComparison.OrdinalIgnoreCase) == false) + { + mismatches.Add($"{name} is '{declared}', expected '{value}'"); + } + } + + return mismatches; + } + + /// + /// Compare declarations with expected values + /// + /// Name of what is checked + /// Declared properties + /// Expected property and value pairs + /// One text per missing or different declaration + private static IEnumerable FindDeclarationMismatches(string subject, Dictionary actual, (string Name, string Value)[] expected) + { + return FindTokenMismatches(actual, expected).Select(mismatch => $"{subject}: {mismatch}"); + } + + /// + /// Find the box shadows of a stylesheet that are neither none nor an inset line + /// + /// Stylesheet text + /// One text per offending shadow + private static List FindElevationShadows(string css) + { + return _boxShadowPattern.Matches(css) + .SelectMany(match => StylesheetReader.SplitTopLevel(match.Groups[1].Value, ',')) + .Where(shadow => shadow != "none" && shadow.StartsWith("inset ", StringComparison.Ordinal) == false) + .Select(shadow => $"box-shadow: {shadow}") + .ToList(); + } + + /// + /// Find the color literals and named colors in the declarations of a rule + /// + /// Rule + /// One text per offending declaration + private static IEnumerable FindColorLiterals((string Selector, string Body, string Context) rule) + { + return StylesheetReader.GetDeclarationList(rule.Body) + .Where(declaration => _colorLiteralPattern.IsMatch(declaration.Value) + || (_colorPropertyPattern.IsMatch(declaration.Name) && _namedColorPattern.IsMatch(declaration.Value))) + .Select(declaration => $"{rule.Selector} {{ {declaration.Name}: {declaration.Value} }}"); + } + + /// + /// Find a background of a metric card variant: the card must not be tinted + /// + /// Stylesheet text + /// Card variant selector + /// One text when the variant sets a background + private static IEnumerable FindTintedBackgrounds(string css, string selector) + { + var declarations = StylesheetReader.GetDeclarations(css, selector); + + return declarations.Keys.Where(name => name.StartsWith("background", StringComparison.Ordinal)) + .Select(name => $"{selector} sets {name}"); + } + + /// + /// Find the external addresses of a host file + /// + /// Path below the host project directory + /// Findings naming the file and the address + private static IEnumerable FindExternalAddresses(string relativePath) + { + return _externalAddressPattern.Matches(StylesheetReader.ReadHostFile(relativePath)) + .Select(match => $"{relativePath} contains {match.Value}"); + } + + /// + /// Assert there is nothing to report + /// + /// Findings + /// What must hold + private static void AssertNoMismatches(IEnumerable mismatches, string message) + { + Assert.AreEqual(string.Empty, string.Join("; ", mismatches), message); + } + + #endregion // Helper methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/AppTests.cs b/src/Tests/DockerUpdateGuard.Tests/AppTests.cs new file mode 100644 index 00000000..660657d7 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/AppTests.cs @@ -0,0 +1,93 @@ +using System.Text.RegularExpressions; + +using DockerUpdateGuard.Tests.Helper; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for the shipped document Components/App.razor and the static assets it points at +/// +[TestClass] +public class AppTests +{ + #region Constants + + /// + /// Document component below the host project directory + /// + private const string AppPath = "Components/App.razor"; + + /// + /// Preload line of the Inter font + /// + private const string InterPreload = ""; + + /// + /// Preload line of the Space Grotesk font + /// + private const string SpaceGroteskPreload = ""; + + #endregion // Constants + + #region Fields + + /// + /// Asset path of a preload line + /// + private static readonly Regex _preloadPathPattern = new("[^\"]+)\"\\]\"", + RegexOptions.CultureInvariant, + TimeSpan.FromSeconds(5)); + + #endregion // Fields + + #region Methods + + /// + /// Verify the document preloads Space Grotesk after Inter, in the same form, and every preloaded asset exists + /// + [TestMethod] + [TestCategory("AC3")] + public void AppPreloadsShippedSpaceGroteskFont() + { + var lines = StylesheetReader.ReadHostFile(AppPath) + .Split('\n') + .Select(line => line.Trim()) + .ToList(); + + var interIndex = lines.IndexOf(InterPreload); + var groteskIndex = lines.IndexOf(SpaceGroteskPreload); + + Assert.IsGreaterThanOrEqualTo(0, interIndex, "The preload of Inter must stay"); + Assert.IsGreaterThan(interIndex, groteskIndex, "The preload of Space Grotesk must follow Inter's in the same form"); + + var missing = lines.Select(line => _preloadPathPattern.Match(line)) + .Where(match => match.Success) + .Select(match => match.Groups["path"].Value) + .Where(path => File.Exists(Path.Combine(HostProjectDirectory.GetPath(), "wwwroot", path)) == false) + .ToList(); + + Assert.AreEqual(string.Empty, string.Join(", ", missing), "Every preload must point at an existing asset of wwwroot"); + } + + /// + /// Verify the variable latin font and its license text are shipped in wwwroot/fonts + /// + [TestMethod] + [TestCategory("AC3")] + public void AppShipsSpaceGroteskFontWithItsLicense() + { + var fontPath = Path.Combine(HostProjectDirectory.GetPath(), "wwwroot", "fonts", "SpaceGrotesk-Variable-latin.woff2"); + + Assert.IsTrue(File.Exists(fontPath), "The Space Grotesk font file must be in wwwroot/fonts"); + + var header = File.ReadAllBytes(fontPath).Take(4).ToArray(); + + Assert.AreSequenceEqual("wOF2"u8.ToArray(), header, "The font file must be a woff2 file"); + + var license = StylesheetReader.ReadHostFile("wwwroot/fonts/SpaceGrotesk-OFL.txt"); + + Assert.Contains("SIL OPEN FONT LICENSE Version 1.1", license, StringComparison.OrdinalIgnoreCase, "The license text must be the SIL Open Font License 1.1 and sit next to the font"); + } + + #endregion // Methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/ContrastRatioTests.cs b/src/Tests/DockerUpdateGuard.Tests/ContrastRatioTests.cs new file mode 100644 index 00000000..9e9cfb55 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/ContrastRatioTests.cs @@ -0,0 +1,79 @@ +using DockerUpdateGuard.Tests.Helper; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for +/// +[TestClass] +public class ContrastRatioTests +{ + #region Methods + + /// + /// Verify black on white is the maximum ratio of 21 + /// + [TestMethod] + [TestCategory("AC6")] + public void ContrastRatioCalculateBlackOnWhiteReturnsTwentyOne() + { + var ratio = ContrastRatio.Calculate("#000000", "#FFFFFF"); + + Assert.AreEqual(21d, ratio, 0.001, "Black on white must be the maximum contrast of 21:1"); + } + + /// + /// Verify the same color on itself is the minimum ratio of 1 + /// + [TestMethod] + [TestCategory("AC6")] + public void ContrastRatioCalculateSameColorReturnsOne() + { + var ratio = ContrastRatio.Calculate("#2563EB", "#2563EB"); + + Assert.AreEqual(1d, ratio, 0.001, "A color on itself must have the minimum contrast of 1:1"); + } + + /// + /// Verify the order of the colors and the letter case do not change the ratio + /// + [TestMethod] + [TestCategory("AC6")] + public void ContrastRatioCalculateIgnoresColorOrderAndLetterCase() + { + var whiteOnBlue = ContrastRatio.Calculate("#FFFFFF", "#2563EB"); + var blueOnWhite = ContrastRatio.Calculate("#2563eb", "#ffffff"); + + Assert.AreEqual(whiteOnBlue, blueOnWhite, 0.0001, "The ratio must not depend on the order or the letter case"); + } + + /// + /// Verify a known pair: white on the light primary color is 5.17:1 (hand calculation of the plan) + /// + [TestMethod] + [TestCategory("AC6")] + public void ContrastRatioCalculateWhiteOnLightPrimaryReturnsKnownValue() + { + var ratio = ContrastRatio.Calculate("#FFFFFF", "#2563EB"); + + Assert.AreEqual(5.17d, ratio, 0.01, "White on #2563EB must be 5.17:1"); + } + + /// + /// Verify a color that is not written as #RRGGBB is refused + /// + /// Malformed color + [TestMethod] + [TestCategory("AC6")] + [DataRow("FFFFFF")] + [DataRow("#FFF")] + [DataRow("#GGGGGG")] + [DataRow("")] + public void ContrastRatioCalculateMalformedColorThrowsArgumentException(string color) + { + Assert.Throws(() => ContrastRatio.Calculate(color, "#FFFFFF"), + $"The color '{color}' must be refused"); + } + + #endregion // Methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/Helper/ContrastRatio.cs b/src/Tests/DockerUpdateGuard.Tests/Helper/ContrastRatio.cs new file mode 100644 index 00000000..f1898371 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/Helper/ContrastRatio.cs @@ -0,0 +1,81 @@ +using System.Globalization; +using System.Text.RegularExpressions; + +namespace DockerUpdateGuard.Tests.Helper; + +/// +/// Computes the WCAG contrast ratio of two colors +/// +internal static partial class ContrastRatio +{ + #region Constants + + /// + /// Offset the WCAG formula adds to both relative luminances + /// + private const double LuminanceOffset = 0.05; + + #endregion // Constants + + #region Static methods + + /// + /// Match a color written as #RRGGBB + /// + /// Regular expression + [GeneratedRegex("^#[0-9A-Fa-f]{6}$", RegexOptions.None, 5000)] + private static partial Regex CreateColorPattern(); + + #endregion // Static methods + + #region Methods + + /// + /// Calculate the WCAG contrast ratio of two colors, from 1 (same color) to 21 (black on white) + /// + /// First color as #RRGGBB + /// Second color as #RRGGBB + /// Contrast ratio + internal static double Calculate(string first, string second) + { + var firstLuminance = GetRelativeLuminance(first); + var secondLuminance = GetRelativeLuminance(second); + var lighter = Math.Max(firstLuminance, secondLuminance); + var darker = Math.Min(firstLuminance, secondLuminance); + + return (lighter + LuminanceOffset) / (darker + LuminanceOffset); + } + + /// + /// Calculate the WCAG relative luminance of a color + /// + /// Color as #RRGGBB + /// Relative luminance from 0 to 1 + private static double GetRelativeLuminance(string color) + { + if (CreateColorPattern().IsMatch(color) == false) + { + throw new ArgumentException($"The color '{color}' must be written as #RRGGBB", nameof(color)); + } + + var red = GetLinearChannel(color.Substring(1, 2)); + var green = GetLinearChannel(color.Substring(3, 2)); + var blue = GetLinearChannel(color.Substring(5, 2)); + + return (0.2126 * red) + (0.7152 * green) + (0.0722 * blue); + } + + /// + /// Convert one sRGB channel to its linear value + /// + /// Two hexadecimal digits + /// Linear channel value from 0 to 1 + private static double GetLinearChannel(string hexChannel) + { + var channel = int.Parse(hexChannel, NumberStyles.HexNumber, CultureInfo.InvariantCulture) / 255d; + + return channel <= 0.03928 ? channel / 12.92 : Math.Pow((channel + 0.055) / 1.055, 2.4); + } + + #endregion // Methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/Helper/StylesheetReader.cs b/src/Tests/DockerUpdateGuard.Tests/Helper/StylesheetReader.cs new file mode 100644 index 00000000..d9b888e3 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/Helper/StylesheetReader.cs @@ -0,0 +1,372 @@ +using System.Text; +using System.Text.RegularExpressions; + +namespace DockerUpdateGuard.Tests.Helper; + +/// +/// Reads a shipped file of the host project and the rules of a stylesheet, for tests of the files themselves +/// +internal static partial class StylesheetReader +{ + #region Constants + + /// + /// Time limit of the stylesheet patterns in milliseconds + /// + private const int RegexTimeoutMilliseconds = 5000; + + #endregion // Constants + + #region Static methods + + /// + /// Match a CSS comment + /// + /// Regular expression + [GeneratedRegex(@"/\*.*?\*/", RegexOptions.Singleline, RegexTimeoutMilliseconds)] + private static partial Regex CreateCommentPattern(); + + /// + /// Match a run of white space + /// + /// Regular expression + [GeneratedRegex(@"\s+", RegexOptions.None, RegexTimeoutMilliseconds)] + private static partial Regex CreateWhitespacePattern(); + + #endregion // Static methods + + #region Methods + + /// + /// Read a file of the host project with line endings normalized to \n + /// + /// Path below the host project directory, with forward slashes + /// File text + internal static string ReadHostFile(string relativePath) + { + var path = Path.Combine(HostProjectDirectory.GetPath(), relativePath); + + Assert.IsTrue(File.Exists(path), $"The host file '{relativePath}' must exist"); + + return NormalizeLineEndings(File.ReadAllText(path, Encoding.UTF8)); + } + + /// + /// Replace \r\n line endings with \n, because a checkout may carry either + /// + /// Text to normalize + /// Text with \n line endings + internal static string NormalizeLineEndings(string text) + { + return text.Replace("\r\n", "\n", StringComparison.Ordinal); + } + + /// + /// Replace every run of white space with one space and trim the text + /// + /// Text to collapse + /// Collapsed text + internal static string CollapseWhitespace(string text) + { + return CreateWhitespacePattern().Replace(text, " ").Trim(); + } + + /// + /// Remove the comments of a stylesheet + /// + /// Stylesheet text + /// Stylesheet text without comments + internal static string StripComments(string css) + { + return CreateCommentPattern().Replace(css, string.Empty); + } + + /// + /// Split a text at a separator that is outside parentheses and quotes, trimming and dropping empty parts + /// + /// Text to split + /// Separator character + /// Collapsed parts + internal static List SplitTopLevel(string text, char separator) + { + var parts = new List(); + var current = new StringBuilder(); + var depth = 0; + var quote = '\0'; + + foreach (var character in text) + { + quote = GetQuoteAfter(quote, character); + depth += GetDepthChange(quote, character); + + if (character == separator && depth == 0 && quote == '\0') + { + AddPart(parts, current); + + continue; + } + + current.Append(character); + } + + AddPart(parts, current); + + return parts; + } + + /// + /// Get all rules of a stylesheet, those inside @media, @supports and @layer blocks included + /// + /// Stylesheet text + /// Rules in file order: collapsed selector (or @font-face), body, and the collapsed prelude of the enclosing at-rule (empty at the top level) + internal static IReadOnlyList<(string Selector, string Body, string Context)> GetRules(string css) + { + var rules = new List<(string Selector, string Body, string Context)>(); + + CollectRules(StripComments(NormalizeLineEndings(css)), string.Empty, rules); + + return rules; + } + + /// + /// Get the body of the first top-level rule whose whole selector text equals the given one (white space collapsed) + /// + /// Stylesheet text + /// Exact selector text + /// Rule body, or null when no top-level rule has that selector + internal static string? GetRuleBody(string css, string selector) + { + var wanted = CollapseWhitespace(selector); + + foreach (var rule in GetRules(css)) + { + if (rule.Context.Length == 0 && rule.Selector == wanted) + { + return rule.Body; + } + } + + return null; + } + + /// + /// Get the declarations of every top-level rule whose selector list contains the given selector, a later rule overriding an earlier one + /// + /// Stylesheet text + /// One selector of a rule's selector list + /// Property name to collapsed value, empty when no rule names the selector + internal static Dictionary GetDeclarations(string css, string selector) + { + var wanted = CollapseWhitespace(selector); + var declarations = new Dictionary(StringComparer.Ordinal); + + foreach (var rule in GetRules(css)) + { + if (rule.Context.Length == 0 && SplitTopLevel(rule.Selector, ',').Contains(wanted)) + { + MergeDeclarations(declarations, rule.Body); + } + } + + return declarations; + } + + /// + /// Get the declarations of a rule body as name and collapsed value, in file order + /// + /// Rule body + /// Declarations + internal static IReadOnlyList<(string Name, string Value)> GetDeclarationList(string body) + { + var declarations = new List<(string Name, string Value)>(); + + foreach (var part in SplitTopLevel(body, ';')) + { + var colon = part.IndexOf(':', StringComparison.Ordinal); + + if (colon > 0) + { + declarations.Add((part[..colon].Trim(), CollapseWhitespace(part[(colon + 1)..]))); + } + } + + return declarations; + } + + /// + /// Get the custom properties (--name) of a rule body + /// + /// Rule body + /// Custom property name to collapsed value + internal static Dictionary GetCustomProperties(string body) + { + var properties = new Dictionary(StringComparer.Ordinal); + + foreach (var (name, value) in GetDeclarationList(body)) + { + if (name.StartsWith("--", StringComparison.Ordinal)) + { + properties[name] = value; + } + } + + return properties; + } + + /// + /// Collect the rules of a stylesheet text, descending into grouping at-rules + /// + /// Stylesheet text without comments + /// Prelude of the enclosing at-rule, empty at the top level + /// Collected rules + private static void CollectRules(string css, string context, List<(string Selector, string Body, string Context)> rules) + { + var position = 0; + + while (position < css.Length) + { + var open = css.IndexOf('{', position); + + if (open < 0) + { + return; + } + + var close = FindClosingBrace(css, open); + var prelude = GetPrelude(css[position..open]); + var body = css[(open + 1)..close]; + + position = close + 1; + + if (IsGroupingAtRule(prelude)) + { + CollectRules(body, prelude, rules); + } + else + { + rules.Add((prelude, body, context)); + } + } + } + + /// + /// Get the prelude of a block: the text after the last statement that ended with a semicolon, collapsed + /// + /// Text between the previous block and the opening brace + /// Collapsed prelude + private static string GetPrelude(string segment) + { + var semicolon = segment.LastIndexOf(';'); + + return CollapseWhitespace(semicolon >= 0 ? segment[(semicolon + 1)..] : segment); + } + + /// + /// Tell whether a prelude opens a block that holds rules + /// + /// Collapsed prelude + /// true for @media, @supports and @layer + private static bool IsGroupingAtRule(string prelude) + { + return prelude.StartsWith("@media", StringComparison.Ordinal) + || prelude.StartsWith("@supports", StringComparison.Ordinal) + || prelude.StartsWith("@layer", StringComparison.Ordinal); + } + + /// + /// Find the brace that closes the block opened at a position + /// + /// Stylesheet text + /// Index of the opening brace + /// Index of the closing brace, or the end of the text for an unclosed block + private static int FindClosingBrace(string css, int open) + { + var depth = 0; + + for (var index = open; index < css.Length; index++) + { + depth += css[index] switch + { + '{' => 1, + '}' => -1, + _ => 0, + }; + + if (depth == 0) + { + return index; + } + } + + return css.Length; + } + + /// + /// Merge the declarations of a rule body into a declaration map + /// + /// Map to extend + /// Rule body + private static void MergeDeclarations(Dictionary declarations, string body) + { + foreach (var (name, value) in GetDeclarationList(body)) + { + declarations[name] = value; + } + } + + /// + /// Get the quote state after a character + /// + /// Open quote character, or \0 outside a string + /// Next character + /// New quote state + private static char GetQuoteAfter(char quote, char character) + { + if (quote == '\0') + { + return character is '"' or '\'' ? character : '\0'; + } + + return character == quote ? '\0' : quote; + } + + /// + /// Get the change of the parenthesis depth a character causes outside a string + /// + /// Open quote character, or \0 outside a string + /// Character + /// Change of the depth + private static int GetDepthChange(char quote, char character) + { + if (quote != '\0') + { + return 0; + } + + return character switch + { + '(' => 1, + ')' => -1, + _ => 0, + }; + } + + /// + /// Add the collected characters as a part when they are not blank, and clear the collector + /// + /// Parts + /// Collected characters + private static void AddPart(List parts, StringBuilder current) + { + var part = CollapseWhitespace(current.ToString()); + + current.Clear(); + + if (part.Length > 0) + { + parts.Add(part); + } + } + + #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 af1938d4..1ec2e37c 100644 --- a/src/Tests/DockerUpdateGuard.Tests/MainLayoutRenderTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/MainLayoutRenderTests.cs @@ -14,6 +14,7 @@ using Microsoft.Extensions.Options; using MudBlazor; +using MudBlazor.Utilities; using NSubstitute; @@ -25,6 +26,20 @@ namespace DockerUpdateGuard.Tests; [TestClass] public class MainLayoutRenderTests { + #region Fields + + /// + /// Inter stack of the theme + /// + private static readonly string[] _interStack = ["Inter", "Segoe UI", "Arial", "Helvetica", "sans-serif"]; + + /// + /// Space Grotesk stack of the theme + /// + private static readonly string[] _spaceGroteskStack = ["Space Grotesk", "Inter", "Segoe UI", "Arial", "sans-serif"]; + + #endregion // Fields + #region Methods /// @@ -199,6 +214,255 @@ public async Task MainLayoutFailedReloadOnNavigationKeepsSummaryAndLogs() } } + /// + /// Verify the theme sets Inter for text and Space Grotesk for headlines, with the sizes of the refresh + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task MainLayoutThemeUsesInterAndSpaceGroteskTypography() + { + var typography = (await RenderThemeAsync(false).ConfigureAwait(false)).Typography; + + var mismatches = FindTypographyMismatches("Default", typography.Default, _interStack, ".875rem", "1.45", "400").Concat(FindTypographyMismatches("Body1", typography.Body1, _interStack, ".875rem", "1.45", "400")) + .Concat(FindTypographyMismatches("H1", typography.H1, _spaceGroteskStack, null, null, null)) + .Concat(FindTypographyMismatches("H2", typography.H2, _spaceGroteskStack, null, null, null)) + .Concat(FindTypographyMismatches("H3", typography.H3, _spaceGroteskStack, "1.75rem", "1.2", "600")) + .Concat(FindTypographyMismatches("H4", typography.H4, _spaceGroteskStack, "1.25rem", "1.3", "600")) + .Concat(FindTypographyMismatches("H5", typography.H5, null, ".9375rem", "1.4", "600")) + .ToList(); + + if (typography.H3.LetterSpacing != "-0.02em") + { + mismatches.Add($"H3 letter spacing is '{typography.H3.LetterSpacing}'"); + } + + if (typography.H5.FontFamily is { } h5Family && h5Family.SequenceEqual(_interStack) == false) + { + mismatches.Add($"H5 family is '{string.Join(",", h5Family)}' instead of Inter"); + } + + Assert.AreEqual(string.Empty, string.Join("; ", mismatches), "The typography must follow the flat refresh"); + } + + /// + /// Verify the light theme carries the radius and the palette values of the refresh + /// + /// Task + [TestMethod] + [TestCategory("AC5")] + public async Task MainLayoutThemeCarriesLightPaletteAndRadius() + { + var theme = await RenderThemeAsync(false).ConfigureAwait(false); + var palette = theme.PaletteLight; + + var mismatches = FindPaletteMismatches([ + ("Primary", palette.Primary, "#2563EB"), + ("Secondary", palette.Secondary, "#5B6471"), + ("Info", palette.Info, "#1D4ED8"), + ("Success", palette.Success, "#067647"), + ("Warning", palette.Warning, "#B54708"), + ("Error", palette.Error, "#B42318"), + ("Background", palette.Background, "#F6F7F9"), + ("Surface", palette.Surface, "#FFFFFF"), + ("AppbarBackground", palette.AppbarBackground, "#FFFFFF"), + ("DrawerBackground", palette.DrawerBackground, "#FFFFFF"), + ("DrawerText", palette.DrawerText, "#16191D"), + ("TextPrimary", palette.TextPrimary, "#16191D"), + ("TextSecondary", palette.TextSecondary, "#5B6471"), + ("Divider", palette.Divider, "#E3E6EB"), + ("LinesDefault", palette.LinesDefault, "#E3E6EB"), + ("TableLines", palette.TableLines, "#EEF0F3"), + ("LinesInputs", palette.LinesInputs, "#C9CED6"), + ("TableHover", palette.TableHover, "#FAFBFC"), + ("PrimaryContrastText", palette.PrimaryContrastText, "#FFFFFF"), + ("InfoContrastText", palette.InfoContrastText, "#FFFFFF"), + ("ErrorContrastText", palette.ErrorContrastText, "#FFFFFF"), + ]); + + Assert.AreEqual("6px", theme.LayoutProperties.DefaultBorderRadius, "The default radius must be the control radius"); + Assert.AreEqual(string.Empty, string.Join("; ", mismatches), "The light palette must carry the refresh values"); + } + + /// + /// Verify in dark mode the theme carries the dark palette, the radius and the dark contrast texts of the status colors + /// + /// Task + [TestMethod] + [TestCategory("AC5")] + public async Task MainLayoutThemeInDarkModeCarriesDarkPaletteAndContrastTexts() + { + var theme = await RenderThemeAsync(true).ConfigureAwait(false); + var palette = theme.PaletteDark; + + var mismatches = FindPaletteMismatches([ + ("Primary", palette.Primary, "#7AA7FF"), + ("Secondary", palette.Secondary, "#9BA5B3"), + ("Info", palette.Info, "#9CC0FF"), + ("Success", palette.Success, "#5FD39A"), + ("Warning", palette.Warning, "#F2A54A"), + ("Error", palette.Error, "#FF8A80"), + ("Background", palette.Background, "#0F1216"), + ("Surface", palette.Surface, "#171B21"), + ("AppbarBackground", palette.AppbarBackground, "#171B21"), + ("DrawerBackground", palette.DrawerBackground, "#171B21"), + ("DrawerText", palette.DrawerText, "#E7EAEE"), + ("TextPrimary", palette.TextPrimary, "#E7EAEE"), + ("TextSecondary", palette.TextSecondary, "#9BA5B3"), + ("Divider", palette.Divider, "#272D36"), + ("LinesDefault", palette.LinesDefault, "#272D36"), + ("TableLines", palette.TableLines, "#20262E"), + ("LinesInputs", palette.LinesInputs, "#3A424E"), + ("TableHover", palette.TableHover, "#1B2027"), + ("PrimaryContrastText", palette.PrimaryContrastText, "#0F1216"), + ("SecondaryContrastText", palette.SecondaryContrastText, "#0F1216"), + ("InfoContrastText", palette.InfoContrastText, "#0F1216"), + ("SuccessContrastText", palette.SuccessContrastText, "#0F1216"), + ("WarningContrastText", palette.WarningContrastText, "#0F1216"), + ("ErrorContrastText", palette.ErrorContrastText, "#0F1216"), + ]); + + Assert.AreEqual("6px", theme.LayoutProperties.DefaultBorderRadius, "The default radius must be the control radius in dark mode"); + Assert.AreEqual(string.Empty, string.Join("; ", mismatches), "The dark palette must carry the refresh values and contrast texts"); + } + + /// + /// Verify each status color reaches 4.5:1 with its contrast text in both palettes + /// + /// Whether the dark palette is checked + /// Task + [TestMethod] + [TestCategory("AC6")] + [DataRow(false)] + [DataRow(true)] + public async Task MainLayoutThemeStatusColorsReachMinimumContrast(bool isDarkMode) + { + var theme = await RenderThemeAsync(isDarkMode).ConfigureAwait(false); + var pairs = isDarkMode ? GetStatusPairs(theme.PaletteDark) : GetStatusPairs(theme.PaletteLight); + + var low = pairs.Select(pair => (pair.Name, Ratio: ContrastRatio.Calculate(ToHex(pair.Text), ToHex(pair.Background)))) + .Where(pair => pair.Ratio < 4.5) + .Select(pair => $"{pair.Name} {pair.Ratio:0.00}:1") + .ToList(); + + Assert.HasCount(6, pairs, "Primary, Secondary, Info, Success, Warning and Error must be checked"); + Assert.AreEqual(string.Empty, string.Join("; ", low), "Every status color must reach 4.5:1 with its contrast text"); + } + + /// + /// Verify the theme switches off all 26 elevation shadows + /// + /// Task + [TestMethod] + [TestCategory("AC8")] + public async Task MainLayoutThemeSwitchesOffElevationShadows() + { + var elevations = (await RenderThemeAsync(false).ConfigureAwait(false)).Shadows.Elevation; + + Assert.HasCount(26, elevations, "The theme must define all 26 elevations"); + Assert.AreEqual(string.Empty, string.Join(", ", elevations.Where(elevation => elevation != "none")), "Every elevation must be none"); + } + + /// + /// Render the layout, optionally toggle dark mode, and read the theme handed to the theme provider + /// + /// Whether to click the dark-mode toggle first + /// Theme of the provider + private static async Task RenderThemeAsync(bool toggleDarkMode) + { + var testContext = CreateContext(dashboardSummary: null); + + await using (testContext) + { + var component = testContext.Render(parameters => parameters.Add(layout => layout.Body, string.Empty)); + + if (toggleDarkMode) + { + await component.Find(".app-topbar__theme-toggle").ClickAsync().ConfigureAwait(false); + } + + var provider = component.FindComponent().Instance; + + Assert.AreEqual(toggleDarkMode, component.Markup.Contains("dug-dark", StringComparison.Ordinal), "The layout must be in the requested mode"); + Assert.IsNotNull(provider.Theme, "The theme provider must receive a theme"); + + return provider.Theme; + } + } + + /// + /// Compare a typography with the expected family, size, line height and weight; null expectations are not checked + /// + /// Typography name + /// Typography + /// Expected family + /// Expected size + /// Expected line height + /// Expected weight + /// One text per difference + private static IEnumerable FindTypographyMismatches(string name, BaseTypography typography, string[]? family, string? size, string? lineHeight, string? weight) + { + if (family is not null && (typography.FontFamily?.SequenceEqual(family) ?? false) == false) + { + yield return $"{name} family is '{string.Join(",", typography.FontFamily ?? [])}'"; + } + + if (size is not null && typography.FontSize != size) + { + yield return $"{name} size is '{typography.FontSize}'"; + } + + if (lineHeight is not null && typography.LineHeight != lineHeight) + { + yield return $"{name} line height is '{typography.LineHeight}'"; + } + + if (weight is not null && typography.FontWeight != weight) + { + yield return $"{name} weight is '{typography.FontWeight}'"; + } + } + + /// + /// Compare palette colors with expected hexadecimal values + /// + /// Name, actual color and expected #RRGGBB + /// One text per difference + private static List FindPaletteMismatches((string Name, MudColor Actual, string Expected)[] colors) + { + return colors.Where(color => string.Equals(ToHex(color.Actual), color.Expected, StringComparison.OrdinalIgnoreCase) == false) + .Select(color => $"{color.Name} is {ToHex(color.Actual)}, expected {color.Expected}") + .ToList(); + } + + /// + /// Pair each status color with its contrast text + /// + /// Palette + /// Name, text and background + private static (string Name, MudColor Text, MudColor Background)[] GetStatusPairs(Palette palette) + { + return + [ + ("Primary", palette.PrimaryContrastText, palette.Primary), + ("Secondary", palette.SecondaryContrastText, palette.Secondary), + ("Info", palette.InfoContrastText, palette.Info), + ("Success", palette.SuccessContrastText, palette.Success), + ("Warning", palette.WarningContrastText, palette.Warning), + ("Error", palette.ErrorContrastText, palette.Error), + ]; + } + + /// + /// Write a color as #RRGGBB + /// + /// Color + /// Hexadecimal text + private static string ToHex(MudColor color) + { + return $"#{color.R:X2}{color.G:X2}{color.B:X2}"; + } + /// /// Create a bUnit test context wired up with the services required to render the layout /// diff --git a/src/Tests/DockerUpdateGuard.Tests/StylesheetReaderTests.cs b/src/Tests/DockerUpdateGuard.Tests/StylesheetReaderTests.cs new file mode 100644 index 00000000..cdf741e7 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/StylesheetReaderTests.cs @@ -0,0 +1,160 @@ +using DockerUpdateGuard.Tests.Helper; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for +/// +[TestClass] +public class StylesheetReaderTests +{ + #region Constants + + /// + /// Stylesheet with a comment, a grouped selector over two lines, a media block and a font face + /// + private const string SampleCss = """ + /* header { color: red; } */ + @font-face { + font-family: "Demo"; + src: url("fonts/a;b.woff2") format("woff2"); + } + + :root { + --dug-a: #AABBCC; + --dug-b: Inter, "Segoe UI", sans-serif; + color: var(--dug-a); + } + + .one, + .two:is(.x, .y) { + margin: 0; + } + + .one { + margin: 4px; + padding: 1px + } + + @media (max-width: 960px) { + .one { + margin: 9px; + } + } + """; + + #endregion // Constants + + #region Fields + + /// + /// Parts expected from splitting the sample list + /// + private static readonly string[] _expectedSplitParts = ["a:is(b, c)", "\"d,e\"", "f"]; + + #endregion // Fields + + #region Methods + + /// + /// Verify CRLF and LF text both come out with LF only + /// + [TestMethod] + public void StylesheetReaderNormalizeLineEndingsWithCrlfInputReturnsLfOnly() + { + var normalized = StylesheetReader.NormalizeLineEndings("a {\r\n b: c;\r\n}\r\n"); + + Assert.AreEqual("a {\n b: c;\n}\n", normalized, "Every CRLF must become LF"); + Assert.AreEqual("a\nb", StylesheetReader.NormalizeLineEndings("a\nb"), "LF text must stay unchanged"); + } + + /// + /// Verify the app stylesheet is read without carriage returns even when it is checked out with CRLF + /// + [TestMethod] + public void StylesheetReaderReadHostFileReturnsTextWithoutCarriageReturns() + { + var css = StylesheetReader.ReadHostFile("wwwroot/app.css"); + + Assert.DoesNotContain("\r", css, "The stylesheet text must carry no carriage return"); + Assert.Contains(":root", css, "The stylesheet text must be the content of app.css"); + } + + /// + /// Verify a rule is found by its exact selector text whatever the line breaks between its selectors, and a comment is ignored + /// + [TestMethod] + public void StylesheetReaderGetRuleBodyFindsRuleByExactSelectorText() + { + var crlfCss = StylesheetReader.NormalizeLineEndings(SampleCss).Replace("\n", "\r\n", StringComparison.Ordinal); + + var body = StylesheetReader.GetRuleBody(crlfCss, ".one, .two:is(.x, .y)"); + + Assert.IsNotNull(body, "A grouped selector list must be found by its collapsed text"); + Assert.AreEqual("margin: 0;", StylesheetReader.CollapseWhitespace(body), "The body of the first matching rule must be returned"); + Assert.IsNull(StylesheetReader.GetRuleBody(crlfCss, "header"), "A rule inside a comment must not be found"); + Assert.IsNull(StylesheetReader.GetRuleBody(crlfCss, ".two"), "A part of a selector list is not the exact selector text"); + } + + /// + /// Verify rules inside a media block carry its prelude as context and are not top-level rules + /// + [TestMethod] + public void StylesheetReaderGetRulesReportsMediaContext() + { + var rules = StylesheetReader.GetRules(SampleCss); + + var mediaRules = rules.Where(rule => rule.Context == "@media (max-width: 960px)").ToList(); + + Assert.HasCount(1, mediaRules, "The media block must hold one rule"); + Assert.AreEqual(".one", mediaRules[0].Selector, "The rule of the media block must keep its selector"); + Assert.HasCount(5, rules, "The font face, :root, the grouped rule, .one and the media rule must be found"); + Assert.AreEqual("@font-face", rules[0].Selector, "The font face must be reported with its at-rule name"); + } + + /// + /// Verify the declarations of every top-level rule that names the selector are merged, a later one overriding an earlier one + /// + [TestMethod] + public void StylesheetReaderGetDeclarationsMergesTopLevelRulesNamingTheSelector() + { + var declarations = StylesheetReader.GetDeclarations(SampleCss, ".one"); + + Assert.AreEqual("4px", declarations["margin"], "The later top-level rule must override the earlier one and the media rule must not count"); + Assert.AreEqual("1px", declarations["padding"], "A last declaration without a semicolon must be read"); + Assert.HasCount(2, declarations, "Only margin and padding must be declared"); + } + + /// + /// Verify custom properties are read with collapsed values and semicolons inside strings or parentheses do not split a declaration + /// + [TestMethod] + public void StylesheetReaderGetCustomPropertiesReturnsOnlyCustomProperties() + { + var body = StylesheetReader.GetRuleBody(SampleCss, ":root"); + + var properties = StylesheetReader.GetCustomProperties(body!); + + Assert.HasCount(2, properties, "The plain color declaration must not be a custom property"); + Assert.AreEqual("#AABBCC", properties["--dug-a"], "A value must be read as written"); + Assert.AreEqual("Inter, \"Segoe UI\", sans-serif", properties["--dug-b"], "White space inside a value must collapse"); + + var fontFace = StylesheetReader.GetRules(SampleCss)[0]; + var declarations = StylesheetReader.GetDeclarationList(fontFace.Body); + + Assert.AreEqual("url(\"fonts/a;b.woff2\") format(\"woff2\")", declarations[1].Value, "A semicolon inside parentheses must not split the declaration"); + } + + /// + /// Verify splitting honors parentheses and quotes + /// + [TestMethod] + public void StylesheetReaderSplitTopLevelKeepsNestedAndQuotedSeparators() + { + var parts = StylesheetReader.SplitTopLevel("a:is(b, c), \"d,e\" ,, f", ','); + + Assert.AreSequenceEqual(_expectedSplitParts, parts, "Only separators outside parentheses and quotes may split"); + } + + #endregion // Methods +} \ No newline at end of file