progmaweb
The site and account service of Progmasoft: a Next.js frontend and an ASP.NET Core API.
Clonegit clone https://git.progmasoft.com/progmaweb
Share the theme and the language across every Progmasoft host
- Commit
6d78305900851f98e00cc1b688d1237b5e33f857- Author
- Leitwolf11 ·
- Parents
477625cd75db
Changes
apps/web/app/layout.tsx | 17 +---- apps/web/components/PreferenceControls.tsx | 40 ++++++++-- apps/web/e2e/preferences.spec.ts | 94 +++++++++++++++++++++++ apps/web/lib/shared-cookies.ts | 28 +++++++ apps/web/lib/theme.ts | 75 ++++++++++++++++++ apps/web/proxy.ts | 17 ++++- apps/web/tests/theme.test.mjs | 118 +++++++++++++++++++++++++++++ 7 files changed, 366 insertions(+), 23 deletions(-) diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx index a18ab39..60ee919 100644 --- a/apps/web/app/layout.tsx +++ b/apps/web/app/layout.tsx @@ -7,22 +7,10 @@ import type { ReactNode } from "react"; import { nonceHeader } from "@/lib/content-security-policy"; import { getLocale } from "@/lib/locale.server"; import { textDirection } from "@/lib/localization"; +import { themeBootstrap } from "@/lib/theme"; import "./globals.css"; import "./viget.css"; -// Apply the stored theme before the body is painted. PreferenceControls keeps -// this value synchronized after hydration, while this small bootstrap prevents -// a light flash on every route—including dashboard loading and error states. -const themeBootstrap = ` - (() => { - try { - const theme = localStorage.getItem("progmasoft_theme") === "dark" ? "dark" : "light"; - document.documentElement.dataset.theme = theme; - document.documentElement.style.colorScheme = theme; - } catch {} - })(); -`; - export const metadata: Metadata = { // The apex host is the only public organization canonical. The www host is a // transport-level redirect and account pages opt out of indexing below. @@ -50,7 +38,8 @@ export default async function RootLayout({ <html lang={locale} data-text-direction={textDirection(locale)} - // data-theme belongs to the bootstrap script and the theme control only. + // data-theme belongs to the bootstrap script (lib/theme.ts) and the theme + // control only. // Rendered here, React would set it back to light whenever the server // re-renders the layout (a language switch), and the page would flash. suppressHydrationWarning diff --git a/apps/web/components/PreferenceControls.tsx b/apps/web/components/PreferenceControls.tsx index cfb92fb..ab4df6c 100644 --- a/apps/web/components/PreferenceControls.tsx +++ b/apps/web/components/PreferenceControls.tsx @@ -11,6 +11,12 @@ import { supportedLocales, type Locale, } from "@/lib/localization"; +import { + themeCookie, + themeCookieName, + themeFromCookies, + type Theme, +} from "@/lib/theme"; interface PreferenceControlsProps { locale: Locale; @@ -22,14 +28,10 @@ interface PreferenceControlsProps { }; } -type Theme = "light" | "dark"; - const themeEvent = "progmasoft-theme-change"; function readTheme(): Theme { - return window.localStorage.getItem("progmasoft_theme") === "dark" - ? "dark" - : "light"; + return themeFromCookies(document.cookie) ?? "light"; } /** @@ -51,12 +53,24 @@ function applyTheme(theme: Theme) { ); } +/** + * The theme can change while the page stays open: in this tab, or on another + * host of Progmasoft, which shares the cookie. The page reads it again when it + * is shown or comes back into view. + */ function subscribeTheme(onStoreChange: () => void) { - window.addEventListener("storage", onStoreChange); + const onVisible = () => { + if (document.visibilityState === "visible") onStoreChange(); + }; window.addEventListener(themeEvent, onStoreChange); + window.addEventListener("pageshow", onStoreChange); + window.addEventListener("focus", onStoreChange); + document.addEventListener("visibilitychange", onVisible); return () => { - window.removeEventListener("storage", onStoreChange); window.removeEventListener(themeEvent, onStoreChange); + window.removeEventListener("pageshow", onStoreChange); + window.removeEventListener("focus", onStoreChange); + document.removeEventListener("visibilitychange", onVisible); }; } @@ -81,7 +95,17 @@ export function PreferenceControls({ function toggleTheme() { const selected: Theme = theme === "light" ? "dark" : "light"; applyTheme(selected); - window.localStorage.setItem("progmasoft_theme", selected); + document.cookie = themeCookie( + selected, + window.location.hostname, + window.location.protocol === "https:", + ); + // The choice lives in the cookie; an old per-host copy would only mislead. + try { + window.localStorage.removeItem(themeCookieName); + } catch { + // Storage may be unavailable; the cookie holds the choice. + } window.dispatchEvent(new Event(themeEvent)); } diff --git a/apps/web/e2e/preferences.spec.ts b/apps/web/e2e/preferences.spec.ts new file mode 100644 index 0000000..18a3326 --- /dev/null +++ b/apps/web/e2e/preferences.spec.ts @@ -0,0 +1,94 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later + +import { expect, test, type Page } from "@playwright/test"; + +/** + * The theme and the language a visitor chooses on one host of Progmasoft + * hold on the others: both are cookies of the registrable domain. + */ + +async function open(page: Page, target: string) { + const response = await page.goto(`http://${target}`); + expect(response?.status(), `status of ${target}`).toBeLessThan(400); +} + +const theme = (page: Page) => + page.evaluate(() => document.documentElement.dataset.theme); + +test.beforeEach(({ page }) => { + // The header shows its controls without a menu on a wide screen. + test.skip( + (page.viewportSize()?.width ?? 0) <= 980, + "the controls are in the menu below 980px; one width is enough here", + ); +}); + +test("a theme chosen on progmasoft.com holds on the other hosts", async ({ + page, +}) => { + await open(page, "progmasoft.com/"); + expect(await theme(page)).toBe("light"); + await page.locator(".preference-controls button").click(); + expect(await theme(page)).toBe("dark"); + for (const host of [ + "viget.progmasoft.com/", + "account.progmasoft.com/", + "product.progmasoft.com/", + ]) { + await open(page, host); + expect(await theme(page), host).toBe("dark"); + } + await page.locator(".preference-controls button").click(); + await open(page, "progmasoft.com/"); + expect(await theme(page)).toBe("light"); +}); + +test("a language chosen on progmasoft.com holds on the other hosts", async ({ + page, +}) => { + await open(page, "progmasoft.com/"); + await page.locator(".preference-controls select").selectOption("de-DE"); + await expect(page.locator("html")).toHaveAttribute("lang", "de-DE"); + for (const host of ["viget.progmasoft.com/", "product.progmasoft.com/"]) { + await open(page, host); + await expect(page.locator("html"), host).toHaveAttribute("lang", "de-DE"); + } +}); + +test("a theme of an earlier version in localStorage moves into the shared cookie", async ({ + page, +}) => { + await open(page, "account.progmasoft.com/"); + await page.evaluate(() => localStorage.setItem("progmasoft_theme", "dark")); + await open(page, "account.progmasoft.com/"); + expect(await theme(page)).toBe("dark"); + await open(page, "viget.progmasoft.com/"); + expect(await theme(page)).toBe("dark"); +}); + +test("a cookie of one host does not shadow the shared language", async ({ + page, + context, +}) => { + await context.addCookies([ + { + name: "progmasoft_locale", + value: "ru-RU", + url: "http://viget.progmasoft.com/", + }, + { + name: "progmasoft_locale", + value: "de-DE", + domain: ".progmasoft.com", + path: "/", + }, + ]); + await open(page, "viget.progmasoft.com/"); + await open(page, "viget.progmasoft.com/"); + await expect(page.locator("html")).toHaveAttribute("lang", "de-DE"); + const left = (await context.cookies("http://viget.progmasoft.com/")).filter( + (cookie) => cookie.name === "progmasoft_locale", + ); + expect(left.map((cookie) => cookie.domain)).toEqual([".progmasoft.com"]); +}); diff --git a/apps/web/lib/shared-cookies.ts b/apps/web/lib/shared-cookies.ts new file mode 100644 index 0000000..3b088b6 --- /dev/null +++ b/apps/web/lib/shared-cookies.ts @@ -0,0 +1,28 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later + +import { localeCookieName } from "./localization.ts"; +import { themeCookieName } from "./theme.ts"; + +/** The cookies every host of Progmasoft shares through the registrable domain. */ +const sharedCookies = [localeCookieName, themeCookieName]; + +/** + * Expires the cookies of this host alone that bear the name of a shared + * cookie. A request with two cookies of one name has a host cookie left over + * from before the cookie was shared; without it the shared one holds. + */ +export function expireShadowingCookies( + cookieHeader: string, + secure: boolean, +): string[] { + const names = cookieHeader + .split(";") + .map((part) => part.trim().split("=", 1)[0] ?? ""); + return sharedCookies + .filter((name) => names.filter((found) => found === name).length > 1) + .map( + (name) => + `${name}=; Path=/; Max-Age=0; SameSite=Lax${secure ? "; Secure" : ""}`, + ); +} diff --git a/apps/web/lib/theme.ts b/apps/web/lib/theme.ts new file mode 100644 index 0000000..c819ac8 --- /dev/null +++ b/apps/web/lib/theme.ts @@ -0,0 +1,75 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later + +/** + * The theme a visitor chose, shared by every host of Progmasoft. + * + * It is a cookie of the registrable domain, as the language is, so a choice + * made on progmasoft.com holds on account., viget., product. and console. as + * well. Scripts of the page read and write it, so it is not HttpOnly; it + * carries nothing but "light" or "dark". A choice stored by earlier versions + * of the site in localStorage, which each host kept for itself, moves into + * the cookie the first time a page sees it. + */ + +export type Theme = "light" | "dark"; + +export const themeCookieName = "progmasoft_theme"; + +/** The value of the theme cookie in a Cookie header, if it holds a theme. */ +export function themeFromCookies(cookieHeader: string): Theme | undefined { + for (const part of cookieHeader.split(";")) { + const [name, value] = part.trim().split("=", 2); + if (name === themeCookieName && (value === "light" || value === "dark")) { + return value; + } + } + return undefined; +} + +/** + * The Set-Cookie text of a theme for `document.cookie`: a year long, for the + * registrable domain on a Progmasoft host and for the host itself elsewhere + * (a local development name), and Secure over HTTPS. + */ +export function themeCookie( + theme: Theme, + host: string, + secure: boolean, +): string { + const shared = host === "progmasoft.com" || host.endsWith(".progmasoft.com"); + return [ + `${themeCookieName}=${theme}`, + "Path=/", + `Max-Age=${60 * 60 * 24 * 365}`, + "SameSite=Lax", + ...(shared ? ["Domain=.progmasoft.com"] : []), + ...(secure ? ["Secure"] : []), + ].join("; "); +} + +/** + * The script that sets the theme before the body is painted, so no page + * flashes the other theme: the cookie, else a choice in localStorage (which it + * moves into the cookie), else light. It runs as an inline script with the + * nonce of the page, so it is plain text; tests run it against the functions + * above. + */ +export const themeBootstrap = `(() => { + try { + const host = location.hostname; + const shared = host === "progmasoft.com" || host.endsWith(".progmasoft.com"); + let theme = (/(?:^|;\\s*)progmasoft_theme=(light|dark)(?:;|$)/.exec(document.cookie) || [])[1]; + if (!theme) { + const stored = localStorage.getItem("progmasoft_theme"); + if (stored === "light" || stored === "dark") { + theme = stored; + document.cookie = "progmasoft_theme=" + theme + "; Path=/; Max-Age=31536000; SameSite=Lax" + + (shared ? "; Domain=.progmasoft.com" : "") + (location.protocol === "https:" ? "; Secure" : ""); + } + } + theme = theme || "light"; + document.documentElement.dataset.theme = theme; + document.documentElement.style.colorScheme = theme; + } catch {} +})();`; diff --git a/apps/web/proxy.ts b/apps/web/proxy.ts index 4bf1163..822bad6 100644 --- a/apps/web/proxy.ts +++ b/apps/web/proxy.ts @@ -3,6 +3,7 @@ import type { NextRequest } from "next/server"; import { NextResponse } from "next/server"; +import { expireShadowingCookies } from "@/lib/shared-cookies"; import { isLocale, localeCookieName, @@ -67,7 +68,7 @@ const ownSites: OwnSite[] = [ }, ]; -export function proxy(request: NextRequest) { +function handle(request: NextRequest) { // Every page gets its own nonce. Next reads the policy from the request to // mark its scripts, and the layout reads the nonce for the theme bootstrap. const nonce = createNonce(); @@ -274,3 +275,17 @@ export const config = { "/((?!_next/static|_next/image|favicon.ico|icon.svg|apple-icon.png|robots.txt|sitemap.xml).*)", ], }; + +export function proxy(request: NextRequest) { + const response = handle(request); + const secure = + request.headers.get("x-forwarded-proto") === "https" || + request.nextUrl.protocol === "https:"; + for (const cookie of expireShadowingCookies( + request.headers.get("cookie") ?? "", + secure, + )) { + response.headers.append("set-cookie", cookie); + } + return response; +} diff --git a/apps/web/tests/theme.test.mjs b/apps/web/tests/theme.test.mjs new file mode 100644 index 0000000..d530657 --- /dev/null +++ b/apps/web/tests/theme.test.mjs @@ -0,0 +1,118 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later + +import assert from "node:assert/strict"; +import { test } from "node:test"; +import vm from "node:vm"; +import { expireShadowingCookies } from "../lib/shared-cookies.ts"; +import { themeBootstrap, themeCookie, themeFromCookies } from "../lib/theme.ts"; + +test("the theme comes from its cookie and nothing else", () => { + assert.equal(themeFromCookies("progmasoft_theme=dark"), "dark"); + assert.equal(themeFromCookies("a=1; progmasoft_theme=light; b=2"), "light"); + assert.equal(themeFromCookies("progmasoft_theme=blue"), undefined); + assert.equal(themeFromCookies("my_progmasoft_theme=dark"), undefined); + assert.equal(themeFromCookies(""), undefined); +}); + +test("the theme cookie is shared by the Progmasoft hosts and secure over HTTPS", () => { + assert.equal( + themeCookie("dark", "viget.progmasoft.com", true), + "progmasoft_theme=dark; Path=/; Max-Age=31536000; SameSite=Lax; Domain=.progmasoft.com; Secure", + ); + assert.equal( + themeCookie("light", "progmasoft.com", false), + "progmasoft_theme=light; Path=/; Max-Age=31536000; SameSite=Lax; Domain=.progmasoft.com", + ); + assert.equal( + themeCookie("light", "localhost", false), + "progmasoft_theme=light; Path=/; Max-Age=31536000; SameSite=Lax", + ); + assert.equal( + themeCookie("dark", "notprogmasoft.com", true), + "progmasoft_theme=dark; Path=/; Max-Age=31536000; SameSite=Lax; Secure", + ); +}); + +/** Runs the bootstrap in a page with the given cookie, localStorage and address. */ +function boot({ + cookie = "", + stored = null, + host = "account.progmasoft.com", + protocol = "https:", +}) { + const written = []; + const root = { dataset: {}, style: {} }; + const document = { + documentElement: root, + get cookie() { + return cookie; + }, + set cookie(value) { + written.push(value); + }, + }; + const localStorage = { + getItem: (name) => (name === "progmasoft_theme" ? stored : null), + }; + vm.runInNewContext(themeBootstrap, { + document, + localStorage, + location: { hostname: host, protocol }, + }); + return { theme: root.dataset.theme, scheme: root.style.colorScheme, written }; +} + +test("the page starts in the theme of the cookie", () => { + assert.deepEqual(boot({ cookie: "x=1; progmasoft_theme=dark" }), { + theme: "dark", + scheme: "dark", + written: [], + }); +}); + +test("a choice of an earlier version moves from localStorage into the shared cookie", () => { + const result = boot({ stored: "dark" }); + assert.equal(result.theme, "dark"); + assert.deepEqual(result.written, [ + themeCookie("dark", "account.progmasoft.com", true), + ]); + assert.deepEqual( + boot({ stored: "light", host: "localhost", protocol: "http:" }).written, + [themeCookie("light", "localhost", false)], + ); +}); + +test("the cookie wins over localStorage, and light is the default", () => { + assert.equal( + boot({ cookie: "progmasoft_theme=light", stored: "dark" }).theme, + "light", + ); + assert.equal(boot({}).theme, "light"); + assert.equal(boot({ stored: "blue" }).theme, "light"); +}); + +test("a host cookie that shadows a shared one is expired", () => { + assert.deepEqual( + expireShadowingCookies( + "progmasoft_locale=en-US; progmasoft_locale=de-DE", + true, + ), + ["progmasoft_locale=; Path=/; Max-Age=0; SameSite=Lax; Secure"], + ); + assert.deepEqual( + expireShadowingCookies( + "progmasoft_theme=light; a=1; progmasoft_theme=dark", + false, + ), + ["progmasoft_theme=; Path=/; Max-Age=0; SameSite=Lax"], + ); + assert.deepEqual( + expireShadowingCookies( + "progmasoft_locale=de-DE; progmasoft_theme=dark", + true, + ), + [], + ); + assert.deepEqual(expireShadowingCookies("", true), []); +});