From 18148430d96557544080a9a8f39bebfe36de8fb6 Mon Sep 17 00:00:00 2001 From: Edi Wang Date: Tue, 8 Oct 2024 20:06:54 +0800 Subject: [PATCH] Add PrefersColorSchemeMiddleware and config setting - Added `PrefersColorSchemeMiddleware` to handle color scheme headers. - Updated `Program.cs` to conditionally use the new middleware based on `Experimental:UsePrefersColorSchemeHeader` setting. - Modified `appsettings.json` to include `Experimental` section with `UsePrefersColorSchemeHeader` setting. --- .../Middleware/PrefersColorSchemeMiddleware.cs | 17 +++++++++++++++++ src/Moonglade.Web/Program.cs | 5 +++++ src/Moonglade.Web/appsettings.json | 3 +++ 3 files changed, 25 insertions(+) create mode 100644 src/Moonglade.Web/Middleware/PrefersColorSchemeMiddleware.cs diff --git a/src/Moonglade.Web/Middleware/PrefersColorSchemeMiddleware.cs b/src/Moonglade.Web/Middleware/PrefersColorSchemeMiddleware.cs new file mode 100644 index 000000000..593eafd29 --- /dev/null +++ b/src/Moonglade.Web/Middleware/PrefersColorSchemeMiddleware.cs @@ -0,0 +1,17 @@ +namespace Moonglade.Web.Middleware; + +public class PrefersColorSchemeMiddleware(RequestDelegate next) +{ + public async Task InvokeAsync(HttpContext context) + { + context.Response.OnStarting(() => + { + context.Response.Headers["Accept-CH"] = "Sec-CH-Prefers-Color-Scheme"; + context.Response.Headers["Vary"] = "Sec-CH-Prefers-Color-Scheme"; + context.Response.Headers["Critical-CH"] = "Sec-CH-Prefers-Color-Scheme"; + return Task.CompletedTask; + }); + + await next(context); + } +} \ No newline at end of file diff --git a/src/Moonglade.Web/Program.cs b/src/Moonglade.Web/Program.cs index 2139e1891..ffb85f579 100644 --- a/src/Moonglade.Web/Program.cs +++ b/src/Moonglade.Web/Program.cs @@ -267,6 +267,11 @@ private static void ConfigureMiddleware(WebApplication app, List cu options.IconFilePath = "/favicon-16x16.png"; }); + // In v14.11.0, just send the header to the client in order to observe browser behaviour + // We will read client's preference in future versions + bool usePrefersColorSchemeHeader = app.Configuration.GetSection("Experimental:UsePrefersColorSchemeHeader").Get(); + if (usePrefersColorSchemeHeader) app.UseMiddleware(); + app.UseMiddleware(); app.UseMiddleware(); diff --git a/src/Moonglade.Web/appsettings.json b/src/Moonglade.Web/appsettings.json index f8015b5ca..8ae2501be 100644 --- a/src/Moonglade.Web/appsettings.json +++ b/src/Moonglade.Web/appsettings.json @@ -73,6 +73,9 @@ "SetLastModifiedHeader": true, "CacheMinutes": 20 }, + "Experimental": { + "UsePrefersColorSchemeHeader": true + }, "Logging": { "LogLevel": { "Default": "Warning",