Admin: themaknop met drie standen (licht, donker, automatisch), toont de huidige stand, volgt de systeemvoorkeur live
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,82 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { render, screen } from '@testing-library/react';
|
||||||
|
import userEvent from '@testing-library/user-event';
|
||||||
|
import i18n from '@/i18n/config';
|
||||||
|
import { ThemeToggle } from './ThemeToggle';
|
||||||
|
|
||||||
|
const media = (dark: boolean) =>
|
||||||
|
vi.spyOn(window, 'matchMedia').mockImplementation(
|
||||||
|
() => ({ matches: dark, addEventListener: () => undefined, removeEventListener: () => undefined }) as unknown as MediaQueryList,
|
||||||
|
);
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
localStorage.clear();
|
||||||
|
document.documentElement.className = '';
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
await i18n.changeLanguage('nl');
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ThemeToggle', () => {
|
||||||
|
it.each([
|
||||||
|
['light', 'Thema: licht'],
|
||||||
|
['dark', 'Thema: donker'],
|
||||||
|
])('shows the CURRENT %s theme in its name (not the action)', (mode, name) => {
|
||||||
|
localStorage.setItem('cms-theme', mode);
|
||||||
|
media(false);
|
||||||
|
|
||||||
|
render(<ThemeToggle />);
|
||||||
|
|
||||||
|
const button = screen.getByTestId('theme-toggle');
|
||||||
|
expect(button).toHaveAccessibleName(name);
|
||||||
|
expect(button).toHaveAttribute('data-mode', mode);
|
||||||
|
expect(button).toHaveAttribute('title', name);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('says in words what automatic currently is', () => {
|
||||||
|
media(true);
|
||||||
|
|
||||||
|
render(<ThemeToggle />);
|
||||||
|
|
||||||
|
expect(screen.getByTestId('theme-toggle')).toHaveAccessibleName('Thema: automatisch (nu donker)');
|
||||||
|
expect(screen.getByTestId('theme-toggle')).toHaveAttribute('data-mode', 'auto');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('opens a menu with three options, the current one marked, and chooses with the keyboard', async () => {
|
||||||
|
media(false);
|
||||||
|
localStorage.setItem('cms-theme', 'light');
|
||||||
|
render(<ThemeToggle />);
|
||||||
|
|
||||||
|
screen.getByTestId('theme-toggle').focus();
|
||||||
|
await userEvent.keyboard('{Enter}');
|
||||||
|
|
||||||
|
expect(await screen.findByTestId('theme-option-light')).toHaveAttribute('aria-current', 'true');
|
||||||
|
expect(screen.getByTestId('theme-option-dark')).not.toHaveAttribute('aria-current');
|
||||||
|
expect(screen.getByTestId('theme-option-auto')).toHaveTextContent('Automatisch');
|
||||||
|
|
||||||
|
await userEvent.click(screen.getByTestId('theme-option-dark'));
|
||||||
|
|
||||||
|
expect(localStorage.getItem('cms-theme')).toBe('dark');
|
||||||
|
expect(document.documentElement.classList.contains('dark')).toBe(true);
|
||||||
|
expect(screen.getByTestId('theme-toggle')).toHaveAccessibleName('Thema: donker');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('works on the first click: automatic to dark flips what is shown at once', async () => {
|
||||||
|
media(false);
|
||||||
|
render(<ThemeToggle />);
|
||||||
|
|
||||||
|
await userEvent.click(screen.getByTestId('theme-toggle'));
|
||||||
|
await userEvent.click(await screen.findByTestId('theme-option-dark'));
|
||||||
|
|
||||||
|
expect(document.documentElement.classList.contains('dark')).toBe(true);
|
||||||
|
expect(document.documentElement.classList.contains('light')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('has English texts too', async () => {
|
||||||
|
await i18n.changeLanguage('en');
|
||||||
|
media(true);
|
||||||
|
|
||||||
|
render(<ThemeToggle />);
|
||||||
|
|
||||||
|
expect(screen.getByTestId('theme-toggle')).toHaveAccessibleName('Theme: automatic (now dark)');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,20 +1,66 @@
|
|||||||
import { Sun, Moon } from 'lucide-react';
|
import { Monitor, Moon, Sun } from 'lucide-react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { useTheme } from '@/hooks/useTheme';
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuCheck,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuLabel,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from '@/components/ui/dropdown-menu';
|
||||||
|
import { useTheme, type ThemeMode } from '@/hooks/useTheme';
|
||||||
|
|
||||||
|
const MODES: { mode: ThemeMode; icon: typeof Sun }[] = [
|
||||||
|
{ mode: 'light', icon: Sun },
|
||||||
|
{ mode: 'dark', icon: Moon },
|
||||||
|
{ mode: 'auto', icon: Monitor },
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Three states: light, dark, automatic (follow the system). The button shows the CURRENT choice (sun = light, moon =
|
||||||
|
* dark, monitor = automatic), its name says it in words ("Theme: automatic (now dark)"), and a small menu with the three
|
||||||
|
* options (the current one marked) changes it.
|
||||||
|
*/
|
||||||
export function ThemeToggle() {
|
export function ThemeToggle() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { isDark, toggleTheme } = useTheme();
|
const { mode, theme, setMode } = useTheme();
|
||||||
|
const Icon = MODES.find((m) => m.mode === mode)!.icon;
|
||||||
|
const label =
|
||||||
|
mode === 'auto'
|
||||||
|
? t('theme.labelAuto', { now: t(`theme.mode.${theme}`).toLowerCase() })
|
||||||
|
: t('theme.label', { mode: t(`theme.mode.${mode}`).toLowerCase() });
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<DropdownMenu>
|
||||||
type="button"
|
<DropdownMenuTrigger asChild>
|
||||||
onClick={toggleTheme}
|
<button
|
||||||
aria-label={isDark ? t('theme.switchToLight') : t('theme.switchToDark')}
|
type="button"
|
||||||
data-testid="theme-toggle"
|
aria-label={label}
|
||||||
className="flex items-center justify-center rounded-md p-2 text-muted-foreground hover:bg-accent hover:text-accent-foreground"
|
title={label}
|
||||||
>
|
data-testid="theme-toggle"
|
||||||
{isDark ? <Sun className="size-4" /> : <Moon className="size-4" />}
|
data-mode={mode}
|
||||||
</button>
|
className="flex items-center justify-center rounded-md p-2 text-muted-foreground hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
>
|
||||||
|
<Icon className="size-4" />
|
||||||
|
</button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="start">
|
||||||
|
<DropdownMenuLabel>{t('theme.title')}</DropdownMenuLabel>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
{MODES.map(({ mode: option, icon: OptionIcon }) => (
|
||||||
|
<DropdownMenuItem
|
||||||
|
key={option}
|
||||||
|
onSelect={() => setMode(option)}
|
||||||
|
aria-current={mode === option ? 'true' : undefined}
|
||||||
|
data-testid={`theme-option-${option}`}
|
||||||
|
>
|
||||||
|
<OptionIcon className="size-4" />
|
||||||
|
{t(`theme.mode.${option}`)}
|
||||||
|
<DropdownMenuCheck checked={mode === option} />
|
||||||
|
</DropdownMenuItem>
|
||||||
|
))}
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,33 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
|
|||||||
import { renderHook, act } from '@testing-library/react';
|
import { renderHook, act } from '@testing-library/react';
|
||||||
import { useTheme } from './useTheme';
|
import { useTheme } from './useTheme';
|
||||||
|
|
||||||
|
type Listener = () => void;
|
||||||
|
|
||||||
|
/** A matchMedia that can change its answer and tell its listeners, like the system preference does. */
|
||||||
|
function system(initialDark: boolean) {
|
||||||
|
let dark = initialDark;
|
||||||
|
const listeners = new Set<Listener>();
|
||||||
|
vi.spyOn(window, 'matchMedia').mockImplementation(
|
||||||
|
() =>
|
||||||
|
({
|
||||||
|
get matches() {
|
||||||
|
return dark;
|
||||||
|
},
|
||||||
|
addEventListener: (_: string, l: Listener) => listeners.add(l),
|
||||||
|
removeEventListener: (_: string, l: Listener) => listeners.delete(l),
|
||||||
|
}) as unknown as MediaQueryList,
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
change(next: boolean) {
|
||||||
|
dark = next;
|
||||||
|
listeners.forEach((l) => l());
|
||||||
|
},
|
||||||
|
listenerCount: () => listeners.size,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const shown = () => (document.documentElement.classList.contains('dark') ? 'dark' : 'light');
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
localStorage.clear();
|
localStorage.clear();
|
||||||
document.documentElement.className = '';
|
document.documentElement.className = '';
|
||||||
@@ -9,96 +36,112 @@ beforeEach(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('useTheme', () => {
|
describe('useTheme', () => {
|
||||||
it('defaults to light when no preference is stored and OS prefers light', () => {
|
it('is automatic when nothing is stored, and follows the system', () => {
|
||||||
vi.spyOn(window, 'matchMedia').mockReturnValue({ matches: false } as MediaQueryList);
|
system(true);
|
||||||
const { result } = renderHook(() => useTheme());
|
const { result } = renderHook(() => useTheme());
|
||||||
expect(result.current.theme).toBe('light');
|
|
||||||
expect(result.current.isDark).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('defaults to dark when OS prefers dark and nothing is stored', () => {
|
expect(result.current.mode).toBe('auto');
|
||||||
vi.spyOn(window, 'matchMedia').mockReturnValue({ matches: true } as MediaQueryList);
|
|
||||||
const { result } = renderHook(() => useTheme());
|
|
||||||
expect(result.current.theme).toBe('dark');
|
expect(result.current.theme).toBe('dark');
|
||||||
expect(result.current.isDark).toBe(true);
|
expect(result.current.isDark).toBe(true);
|
||||||
|
expect(shown()).toBe('dark');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('uses stored localStorage value over OS preference', () => {
|
|
||||||
localStorage.setItem('cms-theme', 'dark');
|
|
||||||
vi.spyOn(window, 'matchMedia').mockReturnValue({ matches: false } as MediaQueryList);
|
|
||||||
const { result } = renderHook(() => useTheme());
|
|
||||||
expect(result.current.theme).toBe('dark');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('toggleTheme switches from light to dark', () => {
|
|
||||||
localStorage.setItem('cms-theme', 'light');
|
|
||||||
const { result } = renderHook(() => useTheme());
|
|
||||||
act(() => { result.current.toggleTheme(); });
|
|
||||||
expect(result.current.theme).toBe('dark');
|
|
||||||
expect(localStorage.getItem('cms-theme')).toBe('dark');
|
|
||||||
expect(document.documentElement.classList.contains('dark')).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('toggleTheme switches from dark to light', () => {
|
|
||||||
localStorage.setItem('cms-theme', 'dark');
|
|
||||||
const { result } = renderHook(() => useTheme());
|
|
||||||
act(() => { result.current.toggleTheme(); });
|
|
||||||
expect(result.current.theme).toBe('light');
|
|
||||||
expect(localStorage.getItem('cms-theme')).toBe('light');
|
|
||||||
expect(document.documentElement.classList.contains('light')).toBe(true);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('first click', () => {
|
|
||||||
const media = (dark: boolean) => vi.spyOn(window, 'matchMedia').mockReturnValue({ matches: dark } as MediaQueryList);
|
|
||||||
const shown = () => (document.documentElement.classList.contains('dark') ? 'dark' : 'light');
|
|
||||||
|
|
||||||
it.each([
|
it.each([
|
||||||
['light', 'dark'],
|
['light', true, 'light'],
|
||||||
['dark', 'light'],
|
['dark', false, 'dark'],
|
||||||
])('flips the shown theme straight away when the OS prefers %s and nothing is stored or applied', (os, expected) => {
|
])('a stored %s wins over the system (dark=%s)', (stored, osDark, expected) => {
|
||||||
media(os === 'dark');
|
localStorage.setItem('cms-theme', stored);
|
||||||
|
system(osDark);
|
||||||
|
|
||||||
const { result } = renderHook(() => useTheme());
|
const { result } = renderHook(() => useTheme());
|
||||||
|
|
||||||
expect(shown()).toBe(os);
|
expect(result.current.mode).toBe(stored);
|
||||||
act(() => { result.current.toggleTheme(); });
|
|
||||||
|
|
||||||
expect(shown()).toBe(expected);
|
|
||||||
expect(result.current.theme).toBe(expected);
|
expect(result.current.theme).toBe(expected);
|
||||||
|
expect(shown()).toBe(expected);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('flips from what is shown even when the stored value is unusable', () => {
|
it('treats an unusable stored value as automatic', () => {
|
||||||
localStorage.setItem('cms-theme', 'system');
|
localStorage.setItem('cms-theme', 'system');
|
||||||
media(true);
|
system(true);
|
||||||
document.documentElement.className = 'system';
|
|
||||||
const { result } = renderHook(() => useTheme());
|
const { result } = renderHook(() => useTheme());
|
||||||
|
|
||||||
|
expect(result.current.mode).toBe('auto');
|
||||||
expect(shown()).toBe('dark');
|
expect(shown()).toBe('dark');
|
||||||
act(() => { result.current.toggleTheme(); });
|
|
||||||
expect(shown()).toBe('light');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('follows the shown theme when it differs from the stored one', () => {
|
it.each([
|
||||||
localStorage.setItem('cms-theme', 'light');
|
['light', false],
|
||||||
|
['dark', false],
|
||||||
|
['auto', true],
|
||||||
|
] as const)('setMode(%s) applies it at the very first call and stores it', (mode, osDark) => {
|
||||||
|
system(osDark);
|
||||||
|
const { result } = renderHook(() => useTheme());
|
||||||
|
|
||||||
|
act(() => result.current.setMode(mode));
|
||||||
|
|
||||||
|
expect(localStorage.getItem('cms-theme')).toBe(mode);
|
||||||
|
expect(result.current.mode).toBe(mode);
|
||||||
|
expect(shown()).toBe(mode === 'auto' ? (osDark ? 'dark' : 'light') : mode);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('the first choice works at once, whatever the page carried before', () => {
|
||||||
|
system(true);
|
||||||
document.documentElement.className = 'dark';
|
document.documentElement.className = 'dark';
|
||||||
const { result } = renderHook(() => useTheme());
|
const { result } = renderHook(() => useTheme());
|
||||||
|
|
||||||
expect(result.current.theme).toBe('dark');
|
act(() => result.current.setMode('light'));
|
||||||
act(() => { result.current.toggleTheme(); });
|
|
||||||
expect(shown()).toBe('light');
|
expect(shown()).toBe('light');
|
||||||
expect(localStorage.getItem('cms-theme')).toBe('light');
|
expect(result.current.theme).toBe('light');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('keeps two toggles on the page in step', () => {
|
it('in automatic mode it follows a change of the system preference live, without reload', () => {
|
||||||
|
const os = system(false);
|
||||||
|
const { result } = renderHook(() => useTheme());
|
||||||
|
expect(shown()).toBe('light');
|
||||||
|
|
||||||
|
act(() => os.change(true));
|
||||||
|
|
||||||
|
expect(result.current.theme).toBe('dark');
|
||||||
|
expect(shown()).toBe('dark');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('with a fixed theme a change of the system preference changes nothing', () => {
|
||||||
localStorage.setItem('cms-theme', 'light');
|
localStorage.setItem('cms-theme', 'light');
|
||||||
|
const os = system(false);
|
||||||
|
const { result } = renderHook(() => useTheme());
|
||||||
|
|
||||||
|
act(() => os.change(true));
|
||||||
|
|
||||||
|
expect(result.current.theme).toBe('light');
|
||||||
|
expect(shown()).toBe('light');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps two toggles on the page in step, and stops listening when they are gone', () => {
|
||||||
|
const os = system(false);
|
||||||
const a = renderHook(() => useTheme());
|
const a = renderHook(() => useTheme());
|
||||||
const b = renderHook(() => useTheme());
|
const b = renderHook(() => useTheme());
|
||||||
|
|
||||||
act(() => { a.result.current.toggleTheme(); });
|
act(() => a.result.current.setMode('dark'));
|
||||||
expect(b.result.current.theme).toBe('dark');
|
expect(b.result.current.mode).toBe('dark');
|
||||||
|
expect(os.listenerCount()).toBeGreaterThan(0);
|
||||||
|
|
||||||
act(() => { b.result.current.toggleTheme(); });
|
a.unmount();
|
||||||
expect(shown()).toBe('light');
|
b.unmount();
|
||||||
expect(a.result.current.theme).toBe('light');
|
expect(os.listenerCount()).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('still works for this page view when the storage cannot be written', () => {
|
||||||
|
system(false);
|
||||||
|
vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
|
||||||
|
throw new Error('private mode');
|
||||||
|
});
|
||||||
|
const { result } = renderHook(() => useTheme());
|
||||||
|
|
||||||
|
act(() => result.current.setMode('dark'));
|
||||||
|
|
||||||
|
expect(result.current.mode).toBe('dark');
|
||||||
|
expect(shown()).toBe('dark');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,63 +1,90 @@
|
|||||||
import { useCallback, useSyncExternalStore } from 'react';
|
import { useCallback, useSyncExternalStore } from 'react';
|
||||||
|
|
||||||
type Theme = 'light' | 'dark';
|
/** What the user chose: a fixed theme, or follow the system (also the default when nothing is stored). */
|
||||||
|
export type ThemeMode = 'light' | 'dark' | 'auto';
|
||||||
|
/** The theme that is actually shown. */
|
||||||
|
export type Theme = 'light' | 'dark';
|
||||||
|
|
||||||
const STORAGE_KEY = 'cms-theme';
|
const STORAGE_KEY = 'cms-theme';
|
||||||
|
const DARK_QUERY = '(prefers-color-scheme: dark)';
|
||||||
|
|
||||||
const listeners = new Set<() => void>();
|
const listeners = new Set<() => void>();
|
||||||
|
|
||||||
function isTheme(value: string | null): value is Theme {
|
/** Only used when storage cannot be written (private mode): the choice then lasts for this page view. */
|
||||||
return value === 'light' || value === 'dark';
|
let memoryMode: ThemeMode | null = null;
|
||||||
|
|
||||||
|
function storedMode(): ThemeMode {
|
||||||
|
if (memoryMode) return memoryMode;
|
||||||
|
try {
|
||||||
|
const stored = localStorage.getItem(STORAGE_KEY);
|
||||||
|
return stored === 'light' || stored === 'dark' ? stored : 'auto';
|
||||||
|
} catch {
|
||||||
|
return memoryMode ?? 'auto';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function preferredTheme(): Theme {
|
function systemTheme(): Theme {
|
||||||
const stored = localStorage.getItem(STORAGE_KEY);
|
return window.matchMedia(DARK_QUERY).matches ? 'dark' : 'light';
|
||||||
if (isTheme(stored)) return stored;
|
|
||||||
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function apply(theme: Theme) {
|
function apply(theme: Theme) {
|
||||||
document.documentElement.classList.remove('light', 'dark');
|
const classes = document.documentElement.classList;
|
||||||
document.documentElement.classList.add(theme);
|
if (!classes.contains(theme) || classes.contains(theme === 'dark' ? 'light' : 'dark')) {
|
||||||
|
classes.remove('light', 'dark');
|
||||||
|
classes.add(theme);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** The shown theme for a mode; it is put on <html> right away, so what we report is what the user sees. */
|
||||||
* The theme that is actually shown, which is what the <html> class says: the stylesheet only
|
function resolve(mode: ThemeMode): Theme {
|
||||||
* knows that class. The stored value and the OS preference are only the way to pick a theme when
|
const theme = mode === 'auto' ? systemTheme() : mode;
|
||||||
* the page carries none (or an unusable one); in that case it is applied right away, so the state
|
|
||||||
* we report and what the user sees can never differ. A first click then always flips what is shown.
|
|
||||||
*/
|
|
||||||
function currentTheme(): Theme {
|
|
||||||
const classes = document.documentElement.classList;
|
|
||||||
if (classes.contains('dark')) return 'dark';
|
|
||||||
if (classes.contains('light')) return 'light';
|
|
||||||
|
|
||||||
const theme = preferredTheme();
|
|
||||||
apply(theme);
|
apply(theme);
|
||||||
return theme;
|
return theme;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** One primitive per state, so useSyncExternalStore sees no change while nothing changed. */
|
||||||
|
function snapshot(): string {
|
||||||
|
const mode = storedMode();
|
||||||
|
return `${mode}:${resolve(mode)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function notifyAll() {
|
||||||
|
listeners.forEach((notify) => notify());
|
||||||
|
}
|
||||||
|
|
||||||
function subscribe(listener: () => void) {
|
function subscribe(listener: () => void) {
|
||||||
listeners.add(listener);
|
listeners.add(listener);
|
||||||
|
// In automatic mode the page follows a change of the system preference live, without a reload; another tab that
|
||||||
|
// changes the choice is followed as well.
|
||||||
|
const media = typeof window.matchMedia === 'function' ? window.matchMedia(DARK_QUERY) : null;
|
||||||
|
media?.addEventListener?.('change', listener);
|
||||||
|
const onStorage = (event: StorageEvent) => {
|
||||||
|
if (event.key === STORAGE_KEY || event.key === null) listener();
|
||||||
|
};
|
||||||
|
window.addEventListener('storage', onStorage);
|
||||||
return () => {
|
return () => {
|
||||||
listeners.delete(listener);
|
listeners.delete(listener);
|
||||||
|
media?.removeEventListener?.('change', listener);
|
||||||
|
window.removeEventListener('storage', onStorage);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useTheme() {
|
export function useTheme() {
|
||||||
// One source of truth shared by every toggle on the page (desktop sidebar, mobile overlay).
|
// One source of truth shared by every toggle on the page (desktop sidebar, mobile overlay).
|
||||||
const theme = useSyncExternalStore(subscribe, currentTheme, () => 'light' as Theme);
|
const state = useSyncExternalStore(subscribe, snapshot, () => 'auto:light');
|
||||||
|
const [mode, theme] = state.split(':') as [ThemeMode, Theme];
|
||||||
|
|
||||||
const toggleTheme = useCallback(() => {
|
const setMode = useCallback((next: ThemeMode) => {
|
||||||
const next: Theme = currentTheme() === 'dark' ? 'light' : 'dark';
|
|
||||||
try {
|
try {
|
||||||
localStorage.setItem(STORAGE_KEY, next);
|
localStorage.setItem(STORAGE_KEY, next);
|
||||||
|
memoryMode = null;
|
||||||
} catch {
|
} catch {
|
||||||
// Storage can be unavailable (private mode); the switch itself still works.
|
// Storage can be unavailable (private mode); the switch itself still works for this page view.
|
||||||
|
memoryMode = next;
|
||||||
}
|
}
|
||||||
apply(next);
|
resolve(next);
|
||||||
listeners.forEach((notify) => notify());
|
notifyAll();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return { theme, isDark: theme === 'dark', toggleTheme };
|
return { mode, theme, isDark: theme === 'dark', setMode };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,8 +18,14 @@
|
|||||||
"closeMenu": "Close navigation"
|
"closeMenu": "Close navigation"
|
||||||
},
|
},
|
||||||
"theme": {
|
"theme": {
|
||||||
"switchToLight": "Switch to light theme",
|
"title": "Theme",
|
||||||
"switchToDark": "Switch to dark theme"
|
"label": "Theme: {{mode}}",
|
||||||
|
"labelAuto": "Theme: automatic (now {{now}})",
|
||||||
|
"mode": {
|
||||||
|
"light": "Light",
|
||||||
|
"dark": "Dark",
|
||||||
|
"auto": "Automatic"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"session": {
|
"session": {
|
||||||
"unreachable": {
|
"unreachable": {
|
||||||
|
|||||||
@@ -18,8 +18,14 @@
|
|||||||
"closeMenu": "Navigatie sluiten"
|
"closeMenu": "Navigatie sluiten"
|
||||||
},
|
},
|
||||||
"theme": {
|
"theme": {
|
||||||
"switchToLight": "Overschakelen naar licht thema",
|
"title": "Thema",
|
||||||
"switchToDark": "Overschakelen naar donker thema"
|
"label": "Thema: {{mode}}",
|
||||||
|
"labelAuto": "Thema: automatisch (nu {{now}})",
|
||||||
|
"mode": {
|
||||||
|
"light": "Licht",
|
||||||
|
"dark": "Donker",
|
||||||
|
"auto": "Automatisch"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"session": {
|
"session": {
|
||||||
"unreachable": {
|
"unreachable": {
|
||||||
|
|||||||
Reference in New Issue
Block a user