From f86ab2a8de8db638bac21046fe959c8d06e66d5e Mon Sep 17 00:00:00 2001
From: therealsama <263038098+therealsama@users.noreply.github.com>
Date: Mon, 8 Jun 2026 23:43:48 +0200
Subject: [PATCH] fix: sync PWA status bar with theme and follow system color
scheme
The theme-color meta was keyed to prefers-color-scheme, so the in-app
toggle never recolored the Android PWA status bar, and the app never
reacted to the OS theme changing at runtime.
- Drive a single JS-controlled theme-color meta from the resolved theme
(seeded before first paint, updated on every change) so the status bar
tracks the app theme.
- Add a tri-state preference (system/light/dark, default system) that
follows the OS color scheme live; explicit light/dark pins persist
across OS changes.
- Replace the binary toggle with a System -> Light -> Dark cycle button.
---
e2e/accessibility.spec.ts | 3 +
e2e/header-overflow.spec.ts | 2 +-
e2e/theme-toggle.spec.ts | 159 +++++++++++++++++------
index.html | 24 +++-
src/components/ThemeToggle.test.tsx | 60 +++++++++
src/components/ThemeToggle.tsx | 33 +++--
src/context/ThemeContext.tsx | 87 ++++++++++---
src/context/themeColors.test.ts | 40 ++++++
src/context/themeConfig.ts | 22 ++++
src/hooks/useTheme.test.tsx | 193 +++++++++++++++++++++++-----
src/types.ts | 11 +-
11 files changed, 526 insertions(+), 108 deletions(-)
create mode 100644 src/components/ThemeToggle.test.tsx
create mode 100644 src/context/themeColors.test.ts
create mode 100644 src/context/themeConfig.ts
diff --git a/e2e/accessibility.spec.ts b/e2e/accessibility.spec.ts
index f3028b9..45276a4 100644
--- a/e2e/accessibility.spec.ts
+++ b/e2e/accessibility.spec.ts
@@ -105,6 +105,9 @@ test.describe('Accessibility', () => {
await expect(themeToggle).toBeFocused();
+ // Cycle system → light → dark from the keyboard. Two presses always lands
+ // on the dark pin regardless of the OS scheme.
+ await page.keyboard.press('Enter');
await page.keyboard.press('Enter');
const html = page.locator('html');
diff --git a/e2e/header-overflow.spec.ts b/e2e/header-overflow.spec.ts
index 18d5163..3b77df7 100644
--- a/e2e/header-overflow.spec.ts
+++ b/e2e/header-overflow.spec.ts
@@ -141,6 +141,6 @@ test.describe('Theme toggle — accessible label', () => {
).toBeVisible();
const toggle = page.getByTestId('theme-toggle');
- await expect(toggle).toHaveAccessibleName(/switch to (dark|light) mode/i);
+ await expect(toggle).toHaveAccessibleName(/switch to (system|light|dark)/i);
});
});
diff --git a/e2e/theme-toggle.spec.ts b/e2e/theme-toggle.spec.ts
index 0f7b1cc..a559545 100644
--- a/e2e/theme-toggle.spec.ts
+++ b/e2e/theme-toggle.spec.ts
@@ -1,39 +1,50 @@
-import { test, expect } from '@playwright/test';
+import { test, expect, type Page } from '@playwright/test';
import { setupApiMocks } from './fixtures/api-mocks';
-test.describe('Theme Toggle', () => {
+const storedMode = (page: Page) =>
+ page.evaluate(() => localStorage.getItem('setting:theme'));
+
+test.describe('Theme cycle button', () => {
test.beforeEach(async ({ page }) => {
await setupApiMocks(page);
- await page.addInitScript(() => {
- localStorage.clear();
- });
+ await page.emulateMedia({ colorScheme: 'light' });
+ await page.addInitScript(() => localStorage.clear());
});
- test('can toggle to dark mode', async ({ page }) => {
+ test('cycles system → light → dark → system', async ({ page }) => {
await page.goto('/#/');
- await expect(page.getByRole('button', { name: /theme|dark|light|mode/i }).first()).toBeVisible();
-
+ const html = page.locator('html');
const toggle = page.getByTestId('theme-toggle');
+ await expect(toggle).toBeVisible();
+
+ // Default is system (no stored choice); OS is light here → resolves light.
+ await expect(html).toHaveClass(/light/);
+ expect(await storedMode(page)).toBeNull();
+
+ // system → light
await toggle.click();
+ await expect.poll(() => storedMode(page)).toBe('light');
+ await expect(html).toHaveClass(/light/);
- const html = page.locator('html');
+ // light → dark
+ await toggle.click();
+ await expect.poll(() => storedMode(page)).toBe('dark');
await expect(html).toHaveClass(/dark/);
await expect(html).not.toHaveClass(/light/);
- await expect.poll(async () => {
- return await page.evaluate(() => localStorage.getItem('setting:theme'));
- }, { timeout: 5000 }).toBeTruthy();
- const theme = await page.evaluate(() => localStorage.getItem('setting:theme'));
- expect(['dark', 'light']).toContain(theme);
+ // dark → system (OS is light → resolves light again)
+ await toggle.click();
+ await expect.poll(() => storedMode(page)).toBe('system');
+ await expect(html).toHaveClass(/light/);
});
- test('theme persists after reload', async ({ browser, baseURL }) => {
+ test('pinned theme persists after reload', async ({ browser, baseURL }) => {
// Multiple page loads + a fresh context push past the default test timeout.
test.setTimeout(60000);
// Fresh context so addInitScript doesn't wipe localStorage on reload.
- const context = await browser.newContext({ baseURL });
+ const context = await browser.newContext({ baseURL, colorScheme: 'light' });
const page = await context.newPage();
await setupApiMocks(page);
@@ -42,18 +53,15 @@ test.describe('Theme Toggle', () => {
const toggle = page.getByTestId('theme-toggle');
await expect(toggle).toBeVisible();
+ // system → light → dark
await toggle.click();
-
- await expect.poll(async () => {
- return await page.evaluate(() => localStorage.getItem('setting:theme'));
- }, { timeout: 5000 }).toBe('dark');
+ await toggle.click();
+ await expect.poll(() => storedMode(page)).toBe('dark');
await page.reload();
await expect(page.getByTestId('theme-toggle')).toBeVisible();
-
- const afterReloadTheme = await page.evaluate(() => localStorage.getItem('setting:theme'));
- expect(afterReloadTheme).toBe('dark');
+ expect(await storedMode(page)).toBe('dark');
const html = page.locator('html');
await expect(html).toHaveClass(/dark/);
@@ -62,37 +70,116 @@ test.describe('Theme Toggle', () => {
// Don't call context.close() — Playwright's automatic teardown races with
// explicit close and produces flaky teardown errors on CI.
});
-
});
-test.describe('Theme - System Preference', () => {
- test('respects system dark mode preference', async ({ page }) => {
+test.describe('Theme - System mode', () => {
+ test('system mode (default) resolves to the OS dark preference', async ({ page }) => {
await page.emulateMedia({ colorScheme: 'dark' });
-
await setupApiMocks(page);
- // Clear stored theme so the app falls through to system preference.
- await page.addInitScript(() => {
- localStorage.clear();
- });
+ await page.addInitScript(() => localStorage.clear());
await page.goto('/#/');
- // ThemeContext reads matchMedia('(prefers-color-scheme: dark)') on init.
const html = page.locator('html');
await expect(html).toHaveClass(/dark/);
await expect(html).not.toHaveClass(/light/);
});
- test('respects system light mode preference', async ({ page }) => {
+ test('system mode (default) resolves to the OS light preference', async ({ page }) => {
+ await page.emulateMedia({ colorScheme: 'light' });
+ await setupApiMocks(page);
+ await page.addInitScript(() => localStorage.clear());
+ await page.goto('/#/');
+
+ const html = page.locator('html');
+ await expect(html).toHaveClass(/light/);
+ await expect(html).not.toHaveClass(/dark/);
+ });
+
+ // Issue 2: while following the system, flipping the OS theme flips the app.
+ test('system mode follows the OS theme when it changes after load', async ({ page }) => {
+ await page.emulateMedia({ colorScheme: 'light' });
+ await setupApiMocks(page);
+ await page.addInitScript(() => localStorage.clear());
+ await page.goto('/#/');
+
+ const html = page.locator('html');
+ await expect(html).toHaveClass(/light/);
+
+ await page.emulateMedia({ colorScheme: 'dark' });
+ await expect(html).toHaveClass(/dark/);
+ await expect(html).not.toHaveClass(/light/);
+
await page.emulateMedia({ colorScheme: 'light' });
+ await expect(html).toHaveClass(/light/);
+ await expect(html).not.toHaveClass(/dark/);
+ });
+ // The regression the tri-state model fixes: a pin must survive OS changes.
+ test('a pinned theme is not overridden by an OS theme change', async ({ page }) => {
+ await page.emulateMedia({ colorScheme: 'light' });
await setupApiMocks(page);
- await page.addInitScript(() => {
- localStorage.clear();
- });
+ await page.addInitScript(() => localStorage.clear());
await page.goto('/#/');
+ const toggle = page.getByTestId('theme-toggle');
const html = page.locator('html');
+
+ // system → light (explicit pin)
+ await toggle.click();
+ await expect.poll(() => storedMode(page)).toBe('light');
+ await expect(html).toHaveClass(/light/);
+
+ // OS flips to dark; the pinned light theme must hold.
+ await page.emulateMedia({ colorScheme: 'dark' });
await expect(html).toHaveClass(/light/);
await expect(html).not.toHaveClass(/dark/);
});
});
+
+test.describe('Theme - Status bar color', () => {
+ const themeColor = (page: Page) =>
+ page.locator('meta[name="theme-color"]').getAttribute('content');
+
+ test.beforeEach(async ({ page }) => {
+ await setupApiMocks(page);
+ await page.addInitScript(() => localStorage.clear());
+ });
+
+ // Issue 1: exactly one app-controlled theme-color tag, recolored on change.
+ test('theme-color meta updates when pinning a dark theme', async ({ page }) => {
+ await page.emulateMedia({ colorScheme: 'light' });
+ await page.goto('/#/');
+
+ await expect(page.locator('meta[name="theme-color"]')).toHaveCount(1);
+ expect(await themeColor(page)).toBe('#fffdfb');
+
+ // system → light → dark
+ await page.getByTestId('theme-toggle').click();
+ await page.getByTestId('theme-toggle').click();
+
+ await expect.poll(() => themeColor(page)).toBe('#241e1a');
+ await expect(page.locator('html')).toHaveClass(/dark/);
+ });
+
+ test('theme-color meta follows the OS theme at runtime in system mode', async ({ page }) => {
+ await page.emulateMedia({ colorScheme: 'light' });
+ await page.goto('/#/');
+
+ expect(await themeColor(page)).toBe('#fffdfb');
+
+ await page.emulateMedia({ colorScheme: 'dark' });
+
+ await expect.poll(() => themeColor(page)).toBe('#241e1a');
+ });
+
+ // A cold load under a dark OS must paint the dark status bar from the start
+ // (bootstrap pre-paint, then ThemeProvider) — not only after a runtime flip.
+ test('theme-color meta is dark on a cold load under a dark OS', async ({ page }) => {
+ await page.emulateMedia({ colorScheme: 'dark' });
+ await page.goto('/#/');
+
+ await expect(page.locator('meta[name="theme-color"]')).toHaveCount(1);
+ await expect.poll(() => themeColor(page)).toBe('#241e1a');
+ await expect(page.locator('html')).toHaveClass(/dark/);
+ });
+});
diff --git a/index.html b/index.html
index 22803a0..a45e984 100644
--- a/index.html
+++ b/index.html
@@ -9,9 +9,12 @@
-
-
-
+
+
@@ -58,12 +61,21 @@
})();
diff --git a/src/components/ThemeToggle.test.tsx b/src/components/ThemeToggle.test.tsx
new file mode 100644
index 0000000..571f86e
--- /dev/null
+++ b/src/components/ThemeToggle.test.tsx
@@ -0,0 +1,60 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, fireEvent } from '@testing-library/react';
+import type * as LucideReact from 'lucide-react';
+import { ThemeProvider } from '../context/ThemeContext';
+import { ThemeToggle } from './ThemeToggle';
+
+// Stub only the three icons the toggle maps over so we can assert the mapping
+// without coupling to lucide's internal SVG markup. Every other icon stays real
+// so unrelated components keep rendering.
+vi.mock('lucide-react', async (importOriginal) => {
+ const actual = await importOriginal();
+ const makeIcon = (testid: string) => {
+ const Icon = (props: Record) => ;
+ Icon.displayName = testid;
+ return Icon;
+ };
+ return {
+ ...actual,
+ Sun: makeIcon('icon-sun'),
+ Moon: makeIcon('icon-moon'),
+ SunMoon: makeIcon('icon-sunmoon'),
+ };
+});
+
+function renderToggle() {
+ return render(
+
+
+ ,
+ );
+}
+
+describe('ThemeToggle', () => {
+ it('shows the System icon and the "switch to Light" label by default', () => {
+ renderToggle();
+
+ expect(screen.getByTestId('icon-sunmoon')).toBeInTheDocument();
+ expect(screen.getByTestId('theme-toggle')).toHaveAttribute(
+ 'aria-label',
+ 'Theme: System. Switch to Light.',
+ );
+ });
+
+ it('cycles icon + label on click: system → light → dark → system', () => {
+ renderToggle();
+ const button = screen.getByTestId('theme-toggle');
+
+ fireEvent.click(button);
+ expect(screen.getByTestId('icon-sun')).toBeInTheDocument();
+ expect(button).toHaveAttribute('aria-label', 'Theme: Light. Switch to Dark.');
+
+ fireEvent.click(button);
+ expect(screen.getByTestId('icon-moon')).toBeInTheDocument();
+ expect(button).toHaveAttribute('aria-label', 'Theme: Dark. Switch to System.');
+
+ fireEvent.click(button);
+ expect(screen.getByTestId('icon-sunmoon')).toBeInTheDocument();
+ expect(button).toHaveAttribute('aria-label', 'Theme: System. Switch to Light.');
+ });
+});
diff --git a/src/components/ThemeToggle.tsx b/src/components/ThemeToggle.tsx
index b78dfbf..ca79ad4 100644
--- a/src/components/ThemeToggle.tsx
+++ b/src/components/ThemeToggle.tsx
@@ -1,26 +1,39 @@
-import { Moon, Sun } from 'lucide-react';
+import { Moon, Sun, SunMoon } from 'lucide-react';
import { useTheme } from '../hooks/useTheme';
+import { nextMode } from '../context/themeConfig';
import { Button } from './ui';
+import type { ThemeMode } from '../types';
+
+const MODE_LABEL: Record = {
+ system: 'System',
+ light: 'Light',
+ dark: 'Dark',
+};
+
+const MODE_ICON: Record = {
+ system: SunMoon,
+ light: Sun,
+ dark: Moon,
+};
export function ThemeToggle() {
- const { theme, toggleTheme } = useTheme();
- const target = theme === 'dark' ? 'light' : 'dark';
- const label = `Switch to ${target} mode`;
+ const { mode, cycleMode } = useTheme();
+ // The icon reflects the current preference (including System) so the active
+ // mode is visible; the label announces what tapping will switch to next.
+ const Icon = MODE_ICON[mode];
+ const label = `Theme: ${MODE_LABEL[mode]}. Switch to ${MODE_LABEL[nextMode(mode)]}.`;
return (
);
}
diff --git a/src/context/ThemeContext.tsx b/src/context/ThemeContext.tsx
index 91db840..a72f98e 100644
--- a/src/context/ThemeContext.tsx
+++ b/src/context/ThemeContext.tsx
@@ -1,34 +1,79 @@
import { useEffect, useState, type ReactNode } from 'react';
import { ThemeContext } from './themeContextDef';
-import type { Theme } from '../types';
+import { THEME_COLORS, nextMode } from './themeConfig';
+import type { Theme, ThemeMode } from '../types';
-const THEME_KEY = 'setting:theme';
+// Persisted user preference ('light' | 'dark' | 'system'). An absent or
+// invalid value falls back to 'system' (follow the device).
+const MODE_KEY = 'setting:theme';
+
+const DARK_QUERY = '(prefers-color-scheme: dark)';
+
+function getSystemTheme(): Theme {
+ return window.matchMedia(DARK_QUERY).matches ? 'dark' : 'light';
+}
+
+function readStoredMode(): ThemeMode {
+ const stored = localStorage.getItem(MODE_KEY);
+ if (stored === 'light' || stored === 'dark' || stored === 'system') {
+ return stored;
+ }
+ return 'system';
+}
+
+function resolveTheme(mode: ThemeMode): Theme {
+ return mode === 'system' ? getSystemTheme() : mode;
+}
+
+// Apply the resolved theme to the document: toggle the `.dark` class (drives
+// the CSS tokens) AND update the theme-color meta so the PWA status bar follows.
+function applyTheme(theme: Theme) {
+ const root = window.document.documentElement;
+ root.classList.remove('light', 'dark');
+ root.classList.add(theme);
+
+ const meta = document.querySelector('meta[name="theme-color"]');
+ if (meta) {
+ meta.setAttribute('content', THEME_COLORS[theme]);
+ }
+}
export function ThemeProvider({ children }: { children: ReactNode }) {
- const [theme, setTheme] = useState(() => {
- const stored = localStorage.getItem(THEME_KEY);
- if (stored === 'dark' || stored === 'light') {
- return stored;
- }
- if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
- return 'dark';
- }
- return 'light';
- });
+ const [mode, setModeState] = useState(readStoredMode);
+ const [theme, setTheme] = useState(() => resolveTheme(mode));
+ // Resolve + apply the theme for the current preference, and — only in 'system'
+ // mode — keep following the OS scheme live (e.g. Android flipping light↔dark,
+ // including scheduled/auto switching) so the app and the PWA status bar stay in
+ // sync. A pin ('light'/'dark') resolves once and skips the subscription, so an
+ // explicit choice is never clobbered by the system.
useEffect(() => {
- const root = window.document.documentElement;
- root.classList.remove('light', 'dark');
- root.classList.add(theme);
- localStorage.setItem(THEME_KEY, theme);
- }, [theme]);
-
- const toggleTheme = () => {
- setTheme(prev => prev === 'dark' ? 'light' : 'dark');
+ const update = (next: Theme) => {
+ setTheme(next);
+ applyTheme(next);
+ };
+
+ update(resolveTheme(mode));
+ if (mode !== 'system') return;
+
+ const mq = window.matchMedia(DARK_QUERY);
+ const handleChange = (event: MediaQueryListEvent) =>
+ update(event.matches ? 'dark' : 'light');
+ mq.addEventListener('change', handleChange);
+ return () => mq.removeEventListener('change', handleChange);
+ }, [mode]);
+
+ // Persist only on an explicit choice. Mounting never writes, so a fresh user
+ // stays "follow the device" until they opt out.
+ const setMode = (next: ThemeMode) => {
+ localStorage.setItem(MODE_KEY, next);
+ setModeState(next);
};
+ const cycleMode = () => setMode(nextMode(mode));
+
return (
-
+
{children}
);
diff --git a/src/context/themeColors.test.ts b/src/context/themeColors.test.ts
new file mode 100644
index 0000000..7889f53
--- /dev/null
+++ b/src/context/themeColors.test.ts
@@ -0,0 +1,40 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { describe, it, expect } from 'vitest';
+import { THEME_COLORS } from './themeConfig';
+
+// THEME_COLORS is the runtime source of truth for the PWA status-bar color, but
+// the same hexes are necessarily hardcoded where JS can't reach them: the
+// index.html bootstrap (pre-React, anti-FOUC) and the static
+// default, plus the web app manifest (read by the OS
+// for the install / splash chrome). ThemeProvider overwrites the meta tag on
+// mount, so a drifted bootstrap or manifest hex can NOT be caught by a
+// rendered-DOM test — only by cross-checking the literals, which is what this does.
+const root = process.cwd();
+const indexHtml = readFileSync(resolve(root, 'index.html'), 'utf8');
+const manifest = JSON.parse(
+ readFileSync(resolve(root, 'public/manifest.webmanifest'), 'utf8'),
+) as { theme_color: string };
+
+const BOOTSTRAP_RE = /isDark \? '(#[0-9a-fA-F]{6})' : '(#[0-9a-fA-F]{6})'/;
+const STATIC_META_RE = /name="theme-color" content="(#[0-9a-fA-F]{6})"/;
+
+describe('theme-color hexes stay in sync across THEME_COLORS / index.html / manifest', () => {
+ it('the index.html bootstrap ternary matches THEME_COLORS', () => {
+ const match = BOOTSTRAP_RE.exec(indexHtml);
+ if (!match) throw new Error('bootstrap theme-color ternary not found in index.html');
+ const [, dark, light] = match;
+ expect(dark.toLowerCase()).toBe(THEME_COLORS.dark);
+ expect(light.toLowerCase()).toBe(THEME_COLORS.light);
+ });
+
+ it('the static default matches the light token', () => {
+ const match = STATIC_META_RE.exec(indexHtml);
+ if (!match) throw new Error('static theme-color meta not found in index.html');
+ expect(match[1].toLowerCase()).toBe(THEME_COLORS.light);
+ });
+
+ it('the manifest theme_color matches the dark token (the PWA chrome is dark)', () => {
+ expect(manifest.theme_color.toLowerCase()).toBe(THEME_COLORS.dark);
+ });
+});
diff --git a/src/context/themeConfig.ts b/src/context/themeConfig.ts
new file mode 100644
index 0000000..085f24d
--- /dev/null
+++ b/src/context/themeConfig.ts
@@ -0,0 +1,22 @@
+import type { Theme, ThemeMode } from '../types';
+
+// Status-bar / browser-chrome colors per resolved theme. These drive the
+// tag that Android (Chrome) uses to tint the PWA
+// status bar. The status bar sits directly above the pinned header (bg-card),
+// so these are the sRGB of the --card tokens in index.css — NOT --background —
+// so the bar matches the header with no seam. The index.html bootstrap and the
+// web manifest hardcode the same hexes (JS can't reach them pre-paint / from the
+// OS); themeColors.test.ts asserts all the copies stay in sync.
+export const THEME_COLORS: Record = {
+ light: '#fffdfb',
+ dark: '#241e1a',
+};
+
+// Single source of truth for the header cycle button's tap order. `nextMode` is
+// used by both the provider's cycleMode and the toggle's label, so the label
+// announces exactly what the next tap resolves to — they can't drift apart.
+const MODE_CYCLE: ThemeMode[] = ['system', 'light', 'dark'];
+
+export function nextMode(mode: ThemeMode): ThemeMode {
+ return MODE_CYCLE[(MODE_CYCLE.indexOf(mode) + 1) % MODE_CYCLE.length];
+}
diff --git a/src/hooks/useTheme.test.tsx b/src/hooks/useTheme.test.tsx
index 6b356cc..6da0b6d 100644
--- a/src/hooks/useTheme.test.tsx
+++ b/src/hooks/useTheme.test.tsx
@@ -1,14 +1,14 @@
-import { describe, it, expect, vi } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import type { ReactNode } from 'react';
import { useTheme } from './useTheme';
import { ThemeProvider } from '../context/ThemeContext';
-describe('useTheme', () => {
- const wrapper = ({ children }: { children: ReactNode }) => (
- {children}
- );
+const wrapper = ({ children }: { children: ReactNode }) => (
+ {children}
+);
+describe('useTheme', () => {
it('throws error when used outside ThemeProvider', () => {
// React logs the throw via console.error; silence to keep test output clean.
const spy = vi.spyOn(console, 'error').mockImplementation(() => { /* noop */ });
@@ -20,45 +20,172 @@ describe('useTheme', () => {
spy.mockRestore();
});
- it('returns theme and toggleTheme from context', () => {
+ it('exposes mode, theme, setMode and cycleMode', () => {
const { result } = renderHook(() => useTheme(), { wrapper });
-
+
+ expect(result.current.mode).toBeDefined();
expect(result.current.theme).toBeDefined();
- expect(typeof result.current.toggleTheme).toBe('function');
+ expect(typeof result.current.setMode).toBe('function');
+ expect(typeof result.current.cycleMode).toBe('function');
});
- it('theme defaults to light when no preference set', () => {
+ it('defaults to system mode, resolving to light when the OS is not dark', () => {
const { result } = renderHook(() => useTheme(), { wrapper });
-
+
+ expect(result.current.mode).toBe('system');
expect(result.current.theme).toBe('light');
});
- it('toggleTheme switches between light and dark', () => {
+ it('cycleMode advances system → light → dark → system', () => {
+ const { result } = renderHook(() => useTheme(), { wrapper });
+
+ expect(result.current.mode).toBe('system');
+
+ act(() => result.current.cycleMode());
+ expect(result.current.mode).toBe('light');
+
+ act(() => result.current.cycleMode());
+ expect(result.current.mode).toBe('dark');
+
+ act(() => result.current.cycleMode());
+ expect(result.current.mode).toBe('system');
+ });
+
+ it('persists the selected mode to localStorage', () => {
const { result } = renderHook(() => useTheme(), { wrapper });
-
- const initialTheme = result.current.theme;
-
- act(() => {
- result.current.toggleTheme();
- });
-
- expect(result.current.theme).toBe(initialTheme === 'dark' ? 'light' : 'dark');
-
- act(() => {
- result.current.toggleTheme();
- });
-
- expect(result.current.theme).toBe(initialTheme);
+
+ act(() => result.current.setMode('dark'));
+
+ expect(result.current.mode).toBe('dark');
+ expect(result.current.theme).toBe('dark');
+ expect(localStorage.getItem('setting:theme')).toBe('dark');
});
- it('persists theme to localStorage', () => {
+ it('rehydrates an explicit pin from localStorage on mount', () => {
+ // OS is light (global matchMedia stub); the stored 'dark' pin must win so a
+ // returning user keeps their choice rather than snapping back to the device.
+ localStorage.setItem('setting:theme', 'dark');
+
const { result } = renderHook(() => useTheme(), { wrapper });
-
- act(() => {
- result.current.toggleTheme();
- });
-
- const stored = localStorage.getItem('setting:theme');
- expect(stored).toBe(result.current.theme);
+
+ expect(result.current.mode).toBe('dark');
+ expect(result.current.theme).toBe('dark');
+ });
+
+ it('falls back to system for an invalid stored value', () => {
+ localStorage.setItem('setting:theme', 'banana');
+
+ const { result } = renderHook(() => useTheme(), { wrapper });
+
+ expect(result.current.mode).toBe('system');
+ expect(result.current.theme).toBe('light');
+ });
+});
+
+// Controllable matchMedia so we can simulate the OS flipping color schemes at
+// runtime (Android light↔dark). The global jsdom mock in test/setup.ts is a
+// fixed `matches: false` stub, so we override it locally and restore after.
+function installMatchMediaMock(initialDark: boolean) {
+ let matches = initialDark;
+ const listeners = new Set<(event: MediaQueryListEvent) => void>();
+
+ const mql = {
+ get matches() { return matches; },
+ media: '(prefers-color-scheme: dark)',
+ onchange: null,
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ addEventListener: vi.fn((_type: string, cb: (event: MediaQueryListEvent) => void) => {
+ listeners.add(cb);
+ }),
+ removeEventListener: vi.fn((_type: string, cb: (event: MediaQueryListEvent) => void) => {
+ listeners.delete(cb);
+ }),
+ dispatchEvent: vi.fn(),
+ };
+
+ window.matchMedia = vi.fn(() => mql) as unknown as typeof window.matchMedia;
+
+ return {
+ setDark(next: boolean) {
+ matches = next;
+ const event = { matches: next, media: mql.media } as MediaQueryListEvent;
+ listeners.forEach(cb => cb(event));
+ },
+ get listenerCount() { return listeners.size; },
+ };
+}
+
+describe('useTheme — system color-scheme + status bar', () => {
+ const originalMatchMedia = window.matchMedia;
+ let metaThemeColor: HTMLMetaElement;
+
+ beforeEach(() => {
+ // Stand-in for the tag from index.html.
+ metaThemeColor = document.createElement('meta');
+ metaThemeColor.setAttribute('name', 'theme-color');
+ document.head.appendChild(metaThemeColor);
+ });
+
+ afterEach(() => {
+ window.matchMedia = originalMatchMedia;
+ metaThemeColor.remove();
+ });
+
+ it('initializes from the OS scheme when in system mode', () => {
+ installMatchMediaMock(true);
+
+ const { result } = renderHook(() => useTheme(), { wrapper });
+
+ expect(result.current.mode).toBe('system');
+ expect(result.current.theme).toBe('dark');
+ });
+
+ it('follows the OS scheme live while in system mode', () => {
+ const mq = installMatchMediaMock(false);
+
+ const { result } = renderHook(() => useTheme(), { wrapper });
+ expect(result.current.theme).toBe('light');
+
+ act(() => mq.setDark(true));
+ expect(result.current.theme).toBe('dark');
+
+ act(() => mq.setDark(false));
+ expect(result.current.theme).toBe('light');
+ });
+
+ it('does NOT let an OS change override an explicit pin', () => {
+ const mq = installMatchMediaMock(false);
+
+ const { result } = renderHook(() => useTheme(), { wrapper });
+
+ act(() => result.current.setMode('light'));
+ expect(result.current.theme).toBe('light');
+ // Subscription torn down once pinned.
+ expect(mq.listenerCount).toBe(0);
+
+ act(() => mq.setDark(true));
+ expect(result.current.theme).toBe('light');
+ expect(result.current.mode).toBe('light');
+ });
+
+ it('updates the theme-color meta tag when the mode changes (PWA status bar)', () => {
+ installMatchMediaMock(false);
+
+ const { result } = renderHook(() => useTheme(), { wrapper });
+ expect(metaThemeColor.getAttribute('content')).toBe('#fffdfb');
+
+ act(() => result.current.setMode('dark'));
+ expect(metaThemeColor.getAttribute('content')).toBe('#241e1a');
+ });
+
+ it('updates the theme-color meta tag when the OS scheme changes in system mode', () => {
+ const mq = installMatchMediaMock(false);
+
+ renderHook(() => useTheme(), { wrapper });
+ expect(metaThemeColor.getAttribute('content')).toBe('#fffdfb');
+
+ act(() => mq.setDark(true));
+ expect(metaThemeColor.getAttribute('content')).toBe('#241e1a');
});
});
diff --git a/src/types.ts b/src/types.ts
index 3f22b60..040fed6 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -141,11 +141,20 @@ export interface PrefetchResult {
comments: Comment[];
}
+// `Theme` is the *resolved* appearance actually applied to the document.
+// `ThemeMode` is the user's *preference*: an explicit pin ('light'/'dark') or
+// 'system', which tracks the OS color scheme live.
export type Theme = 'light' | 'dark';
+export type ThemeMode = 'light' | 'dark' | 'system';
export interface ThemeContextValue {
+ /** User preference. 'system' follows the OS scheme. */
+ mode: ThemeMode;
+ /** Resolved appearance currently applied ('light' | 'dark'). */
theme: Theme;
- toggleTheme: () => void;
+ setMode: (mode: ThemeMode) => void;
+ /** Advance the preference: system → light → dark → system. */
+ cycleMode: () => void;
}
export interface ScrollContainerContextValue {