Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions e2e/accessibility.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
2 changes: 1 addition & 1 deletion e2e/header-overflow.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
159 changes: 123 additions & 36 deletions e2e/theme-toggle.spec.ts
Original file line number Diff line number Diff line change
@@ -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);

Expand All @@ -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/);
Expand All @@ -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/);
});
});
24 changes: 18 additions & 6 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@
<meta name="title" content="HackerTok - Your daily dose of Hacker News" />
<meta name="description" content="An open-source, blazingly fast, progressive Hacker News client. Swipe or scroll through stories, read comments, and install as an app." />

<!-- Theme Colors (with dark mode support) -->
<meta name="theme-color" content="#fffdfb" media="(prefers-color-scheme: light)" />
<meta name="theme-color" content="#241e1a" media="(prefers-color-scheme: dark)" />
<!-- Status-bar / browser-chrome color. Single JS-controlled tag (no media
query) so it tracks the *app* theme, not just the OS scheme. The
bootstrap script below sets the correct value before first paint and
ThemeProvider keeps it in sync on toggle / OS change. Keep these hex
values in sync with THEME_COLORS in src/context/ThemeContext.tsx. -->
<meta name="theme-color" content="#fffdfb" />

<!-- Favicons -->
<link rel="icon" type="image/svg+xml" href="/icons/icon.svg" />
Expand Down Expand Up @@ -58,12 +61,21 @@
})();
</script>
<script>
// Prevent flash of wrong theme
// Prevent flash of wrong theme, and set the initial status-bar color
// before first paint so the Android PWA chrome matches the resolved theme.
// Mirrors ThemeProvider: 'light'/'dark' are explicit pins; 'system' (and
// any missing value) follows the OS color scheme.
(function() {
const theme = localStorage.getItem('setting:theme');
if (theme === 'dark' || (!theme && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
var mode = localStorage.getItem('setting:theme');
var prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
var isDark = mode === 'dark' || (mode !== 'light' && prefersDark);
if (isDark) {
document.documentElement.classList.add('dark');
}
var meta = document.querySelector('meta[name="theme-color"]');
if (meta) {
meta.setAttribute('content', isDark ? '#241e1a' : '#fffdfb');
}
})();
</script>
</head>
Expand Down
60 changes: 60 additions & 0 deletions src/components/ThemeToggle.test.tsx
Original file line number Diff line number Diff line change
@@ -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<typeof LucideReact>();
const makeIcon = (testid: string) => {
const Icon = (props: Record<string, unknown>) => <svg data-testid={testid} {...props} />;
Icon.displayName = testid;
return Icon;
};
return {
...actual,
Sun: makeIcon('icon-sun'),
Moon: makeIcon('icon-moon'),
SunMoon: makeIcon('icon-sunmoon'),
};
});

function renderToggle() {
return render(
<ThemeProvider>
<ThemeToggle />
</ThemeProvider>,
);
}

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.');
});
});
33 changes: 23 additions & 10 deletions src/components/ThemeToggle.tsx
Original file line number Diff line number Diff line change
@@ -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<ThemeMode, string> = {
system: 'System',
light: 'Light',
dark: 'Dark',
};

const MODE_ICON: Record<ThemeMode, typeof SunMoon> = {
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 (
<Button
variant="ghost"
size="icon"
onClick={toggleTheme}
onClick={cycleMode}
aria-label={label}
title={label}
data-testid="theme-toggle"
className="rounded-full text-muted-foreground dark:hover:bg-muted"
>
{theme === 'dark' ? (
<Sun aria-hidden className="size-5" />
) : (
<Moon aria-hidden className="size-5" />
)}
<Icon aria-hidden className="size-5" />
</Button>
);
}
Loading