Admin: themawissel met Auto en themagebonden Checkbox/Radio #19

Merged
Sluijsens merged 2 commits from feature/admin-form-controls into master 2026-11-17 12:57:39 +01:00
11 changed files with 579 additions and 136 deletions
@@ -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)');
});
});
+58 -12
View File
@@ -1,20 +1,66 @@
import { Sun, Moon } from 'lucide-react';
import { Monitor, Moon, Sun } from 'lucide-react';
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() {
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 (
<button
type="button"
onClick={toggleTheme}
aria-label={isDark ? t('theme.switchToLight') : t('theme.switchToDark')}
data-testid="theme-toggle"
className="flex items-center justify-center rounded-md p-2 text-muted-foreground hover:bg-accent hover:text-accent-foreground"
>
{isDark ? <Sun className="size-4" /> : <Moon className="size-4" />}
</button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
aria-label={label}
title={label}
data-testid="theme-toggle"
data-mode={mode}
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>
);
}
@@ -0,0 +1,105 @@
import { describe, expect, it } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { useForm } from 'react-hook-form';
import { Checkbox, CheckboxField } from './checkbox';
import { Radio, RadioField, RadioGroup } from './radio';
describe('Checkbox', () => {
it('is a real checkbox: Space toggles it and the label is clickable', async () => {
render(<CheckboxField label="Uitgelicht" data-testid="box" />);
const box = screen.getByRole('checkbox', { name: 'Uitgelicht' });
box.focus();
await userEvent.keyboard(' ');
expect(box).toBeChecked();
await userEvent.click(screen.getByText('Uitgelicht'));
expect(box).not.toBeChecked();
});
it('shows the in-between state and does not change its value', () => {
render(<Checkbox aria-label="alles" indeterminate />);
const box = screen.getByRole('checkbox', { name: 'alles' }) as HTMLInputElement;
expect(box.indeterminate).toBe(true);
expect(box).not.toBeChecked();
});
it('can be disabled and marked invalid', async () => {
render(<Checkbox aria-label="x" disabled invalid />);
const box = screen.getByRole('checkbox', { name: 'x' });
expect(box).toBeDisabled();
expect(box).toHaveAttribute('aria-invalid', 'true');
await userEvent.click(box);
expect(box).not.toBeChecked();
});
it('draws with the colours of the theme (accent when checked, a visible border, a focus ring)', () => {
render(<Checkbox aria-label="x" />);
const cls = screen.getByRole('checkbox').className;
expect(cls).toContain('checked:bg-primary');
expect(cls).toContain('border-muted-foreground');
expect(cls).toContain('focus-visible:ring-ring');
expect(cls).toContain('forced-colors:checked:bg-[Highlight]');
});
it('works with react-hook-form register, like the native input it replaces', async () => {
function Form({ onSubmit }: { onSubmit: (v: { on: boolean }) => void }) {
const { register, handleSubmit } = useForm<{ on: boolean }>({ defaultValues: { on: false } });
return (
<form onSubmit={handleSubmit(onSubmit)}>
<CheckboxField label="Aan" {...register('on')} />
<button type="submit">go</button>
</form>
);
}
let saved: { on: boolean } | null = null;
render(
<Form
onSubmit={(v) => {
saved = v;
}}
/>,
);
await userEvent.click(screen.getByLabelText('Aan'));
await userEvent.click(screen.getByText('go'));
await screen.findByText('go');
expect(saved).toEqual({ on: true });
});
});
describe('Radio', () => {
it('is a real radio group: the arrow keys move and select, with a name for the group', async () => {
render(
<RadioGroup label="Weergave">
<RadioField name="d" value="single" label="Enkel" defaultChecked />
<RadioField name="d" value="slideshow" label="Diavoorstelling" />
</RadioGroup>,
);
expect(screen.getByRole('radiogroup', { name: 'Weergave' })).toBeInTheDocument();
const first = screen.getByRole('radio', { name: 'Enkel' });
const second = screen.getByRole('radio', { name: 'Diavoorstelling' });
first.focus();
await userEvent.keyboard('{ArrowDown}');
expect(second).toBeChecked();
expect(first).not.toBeChecked();
expect(second).toHaveFocus();
});
it('can be disabled and marked invalid, and uses theme colours', () => {
render(<Radio aria-label="r" name="g" value="a" disabled invalid />);
const radio = screen.getByRole('radio');
expect(radio).toBeDisabled();
expect(radio).toHaveAttribute('aria-invalid', 'true');
expect(radio.className).toContain('checked:border-primary');
expect(radio.className).toContain('forced-colors:checked:border-[Highlight]');
});
});
+77
View File
@@ -0,0 +1,77 @@
import * as React from 'react';
import { Check, Minus } from 'lucide-react';
import { cn } from '@/lib/utils';
export interface CheckboxProps extends Omit<React.ComponentProps<'input'>, 'type' | 'size'> {
/** The "some of them" state of a parent checkbox. It is shown with a minus; the value of the box itself does not change. */
indeterminate?: boolean;
/** The field has an error: a red border (and aria-invalid for screen readers). */
invalid?: boolean;
}
/**
* A real checkbox (a native input: Space toggles it, it works with a label, with react-hook-form's register and in forms),
* drawn in the colours of the theme: a clear border, the accent colour with a check mark when checked, a minus for the
* in-between state, hover, a focus ring, disabled and error states. The check mark is an icon over the input in the
* "primary foreground" colour; in forced-colors (high contrast) mode the system colours take over.
*/
export const Checkbox = React.forwardRef<HTMLInputElement, CheckboxProps>(
({ className, indeterminate = false, invalid = false, ...props }, forwardedRef) => {
const inner = React.useRef<HTMLInputElement | null>(null);
const setRef = (element: HTMLInputElement | null) => {
inner.current = element;
if (typeof forwardedRef === 'function') forwardedRef(element);
else if (forwardedRef) forwardedRef.current = element;
};
React.useEffect(() => {
if (inner.current) inner.current.indeterminate = indeterminate;
}, [indeterminate]);
return (
<span className="relative inline-flex size-5 shrink-0 items-center justify-center">
<input
ref={setRef}
type="checkbox"
aria-invalid={invalid || undefined}
className={cn(
'peer size-5 shrink-0 cursor-pointer appearance-none rounded border-2 border-muted-foreground bg-background transition-colors',
'hover:border-primary checked:border-primary checked:bg-primary indeterminate:border-primary indeterminate:bg-primary',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ring-offset-background',
'disabled:cursor-not-allowed disabled:opacity-50 aria-[invalid=true]:border-destructive',
'forced-colors:checked:bg-[Highlight] forced-colors:checked:border-[Highlight]',
className,
)}
{...props}
/>
<Check
className="pointer-events-none absolute size-3.5 text-primary-foreground opacity-0 peer-checked:opacity-100 peer-indeterminate:opacity-0 peer-disabled:opacity-50 forced-colors:text-[HighlightText]"
strokeWidth={3}
aria-hidden="true"
/>
<Minus
className="pointer-events-none absolute size-3.5 text-primary-foreground opacity-0 peer-indeterminate:opacity-100 peer-disabled:opacity-50 forced-colors:text-[HighlightText]"
strokeWidth={3}
aria-hidden="true"
/>
</span>
);
},
);
Checkbox.displayName = 'Checkbox';
interface CheckboxFieldProps extends CheckboxProps {
label: React.ReactNode;
}
/** A checkbox with its label: the whole line is clickable and at least 24 px high. */
export const CheckboxField = React.forwardRef<HTMLInputElement, CheckboxFieldProps>(({ label, id, disabled, ...props }, ref) => {
const generated = React.useId();
const inputId = id ?? generated;
return (
<label htmlFor={inputId} className={cn('inline-flex min-h-6 cursor-pointer items-center gap-2 py-0.5 text-sm', disabled && 'cursor-not-allowed opacity-70')}>
<Checkbox ref={ref} id={inputId} disabled={disabled} {...props} />
<span>{label}</span>
</label>
);
});
CheckboxField.displayName = 'CheckboxField';
+61
View File
@@ -0,0 +1,61 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
export interface RadioProps extends Omit<React.ComponentProps<'input'>, 'type' | 'size'> {
invalid?: boolean;
}
/**
* A real radio button (a native input: with the same name the arrow keys move and select inside the group, Space selects),
* drawn in the colours of the theme: a clear round border, the accent colour with a dot when selected, hover, a focus
* ring, disabled and error states, and system colours in forced-colors (high contrast) mode.
*/
export const Radio = React.forwardRef<HTMLInputElement, RadioProps>(({ className, invalid = false, ...props }, ref) => (
<span className="relative inline-flex size-5 shrink-0 items-center justify-center">
<input
ref={ref}
type="radio"
aria-invalid={invalid || undefined}
className={cn(
'peer size-5 shrink-0 cursor-pointer appearance-none rounded-full border-2 border-muted-foreground bg-background transition-colors',
'hover:border-primary checked:border-primary',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ring-offset-background',
'disabled:cursor-not-allowed disabled:opacity-50 aria-[invalid=true]:border-destructive',
'forced-colors:checked:border-[Highlight]',
className,
)}
{...props}
/>
<span
className="pointer-events-none absolute size-2.5 rounded-full bg-primary opacity-0 peer-checked:opacity-100 peer-disabled:opacity-50 forced-colors:bg-[Highlight]"
aria-hidden="true"
/>
</span>
));
Radio.displayName = 'Radio';
interface RadioFieldProps extends RadioProps {
label: React.ReactNode;
}
/** A radio button with its label: the whole line is clickable and at least 24 px high. */
export const RadioField = React.forwardRef<HTMLInputElement, RadioFieldProps>(({ label, id, disabled, ...props }, ref) => {
const generated = React.useId();
const inputId = id ?? generated;
return (
<label htmlFor={inputId} className={cn('inline-flex min-h-6 cursor-pointer items-center gap-2 py-0.5 text-sm', disabled && 'cursor-not-allowed opacity-70')}>
<Radio ref={ref} id={inputId} disabled={disabled} {...props} />
<span>{label}</span>
</label>
);
});
RadioField.displayName = 'RadioField';
/** The group around related radio buttons: role radiogroup with a name, so a screen reader announces what is chosen. */
export function RadioGroup({ label, className, children, ...props }: { label: string } & Omit<React.ComponentProps<'div'>, 'aria-label'>) {
return (
<div role="radiogroup" aria-label={label} className={cn('flex flex-wrap gap-x-6 gap-y-1', className)} {...props}>
{children}
</div>
);
}
@@ -5,6 +5,7 @@ import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { CheckboxField } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { FieldError } from '@/components/ui/FieldError';
import { FormErrorBanner } from '@/components/ui/FormErrorBanner';
@@ -211,16 +212,12 @@ function OfferingBannerForm({
</div>
<p className="text-xs text-muted-foreground">{t('offerings.banners.scheduleHint')}</p>
<div className="flex items-center gap-2">
<input
id="banner-active"
type="checkbox"
data-testid="banner-active"
className="size-4 rounded border-input"
{...register('isActive')}
/>
<Label htmlFor="banner-active">{t('offerings.banners.activeLabel')}</Label>
</div>
<CheckboxField
id="banner-active"
data-testid="banner-active"
label={t('offerings.banners.activeLabel')}
{...register('isActive')}
/>
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" onClick={onClose} data-testid="banner-cancel">
@@ -5,6 +5,7 @@ import { useTranslation } from 'react-i18next';
import { Check, Pencil, Plus, Trash2, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { CheckboxField } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { FieldError } from '@/components/ui/FieldError';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
@@ -293,28 +294,20 @@ export function OfferingForm({ initialValues, onSubmit, onCancel, isSubmitting }
{errors.ctaLabel && <FieldError message={errors.ctaLabel.message} testId="offering-cta-label-error" />}
</div>
<div className="flex items-center gap-2">
<input
id="offering-featured"
type="checkbox"
data-testid="offering-featured"
className="size-4 rounded border-input"
{...register('featured')}
/>
<Label htmlFor="offering-featured">{t('offerings.form.featuredLabel')}</Label>
</div>
<CheckboxField
id="offering-featured"
data-testid="offering-featured"
label={t('offerings.form.featuredLabel')}
{...register('featured')}
/>
<div className="space-y-3 rounded-md border p-3" data-testid="offering-schedule">
<div className="flex items-center gap-2">
<input
id="offering-active"
type="checkbox"
data-testid="offering-active"
className="size-4 rounded border-input"
{...register('isActive')}
/>
<Label htmlFor="offering-active">{t('offerings.form.activeLabel')}</Label>
</div>
<CheckboxField
id="offering-active"
data-testid="offering-active"
label={t('offerings.form.activeLabel')}
{...register('isActive')}
/>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="offering-starts">{t('offerings.form.startsLabel')}</Label>
+105 -62
View File
@@ -2,6 +2,33 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
import { renderHook, act } from '@testing-library/react';
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(() => {
localStorage.clear();
document.documentElement.className = '';
@@ -9,96 +36,112 @@ beforeEach(() => {
});
describe('useTheme', () => {
it('defaults to light when no preference is stored and OS prefers light', () => {
vi.spyOn(window, 'matchMedia').mockReturnValue({ matches: false } as MediaQueryList);
it('is automatic when nothing is stored, and follows the system', () => {
system(true);
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', () => {
vi.spyOn(window, 'matchMedia').mockReturnValue({ matches: true } as MediaQueryList);
const { result } = renderHook(() => useTheme());
expect(result.current.mode).toBe('auto');
expect(result.current.theme).toBe('dark');
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([
['light', 'dark'],
['dark', 'light'],
])('flips the shown theme straight away when the OS prefers %s and nothing is stored or applied', (os, expected) => {
media(os === 'dark');
['light', true, 'light'],
['dark', false, 'dark'],
])('a stored %s wins over the system (dark=%s)', (stored, osDark, expected) => {
localStorage.setItem('cms-theme', stored);
system(osDark);
const { result } = renderHook(() => useTheme());
expect(shown()).toBe(os);
act(() => { result.current.toggleTheme(); });
expect(shown()).toBe(expected);
expect(result.current.mode).toBe(stored);
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');
media(true);
document.documentElement.className = 'system';
system(true);
const { result } = renderHook(() => useTheme());
expect(result.current.mode).toBe('auto');
expect(shown()).toBe('dark');
act(() => { result.current.toggleTheme(); });
expect(shown()).toBe('light');
});
it('follows the shown theme when it differs from the stored one', () => {
localStorage.setItem('cms-theme', 'light');
it.each([
['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';
const { result } = renderHook(() => useTheme());
expect(result.current.theme).toBe('dark');
act(() => { result.current.toggleTheme(); });
act(() => result.current.setMode('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');
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 b = renderHook(() => useTheme());
act(() => { a.result.current.toggleTheme(); });
expect(b.result.current.theme).toBe('dark');
act(() => a.result.current.setMode('dark'));
expect(b.result.current.mode).toBe('dark');
expect(os.listenerCount()).toBeGreaterThan(0);
act(() => { b.result.current.toggleTheme(); });
expect(shown()).toBe('light');
expect(a.result.current.theme).toBe('light');
a.unmount();
b.unmount();
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');
});
});
+55 -28
View File
@@ -1,63 +1,90 @@
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 DARK_QUERY = '(prefers-color-scheme: dark)';
const listeners = new Set<() => void>();
function isTheme(value: string | null): value is Theme {
return value === 'light' || value === 'dark';
/** Only used when storage cannot be written (private mode): the choice then lasts for this page view. */
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 {
const stored = localStorage.getItem(STORAGE_KEY);
if (isTheme(stored)) return stored;
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
function systemTheme(): Theme {
return window.matchMedia(DARK_QUERY).matches ? 'dark' : 'light';
}
function apply(theme: Theme) {
document.documentElement.classList.remove('light', 'dark');
document.documentElement.classList.add(theme);
const classes = document.documentElement.classList;
if (!classes.contains(theme) || classes.contains(theme === 'dark' ? 'light' : 'dark')) {
classes.remove('light', 'dark');
classes.add(theme);
}
}
/**
* The theme that is actually shown, which is what the <html> class says: the stylesheet only
* knows that class. The stored value and the OS preference are only the way to pick a theme when
* 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();
/** The shown theme for a mode; it is put on <html> right away, so what we report is what the user sees. */
function resolve(mode: ThemeMode): Theme {
const theme = mode === 'auto' ? systemTheme() : mode;
apply(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) {
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 () => {
listeners.delete(listener);
media?.removeEventListener?.('change', listener);
window.removeEventListener('storage', onStorage);
};
}
export function useTheme() {
// 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 next: Theme = currentTheme() === 'dark' ? 'light' : 'dark';
const setMode = useCallback((next: ThemeMode) => {
try {
localStorage.setItem(STORAGE_KEY, next);
memoryMode = null;
} 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);
listeners.forEach((notify) => notify());
resolve(next);
notifyAll();
}, []);
return { theme, isDark: theme === 'dark', toggleTheme };
return { mode, theme, isDark: theme === 'dark', setMode };
}
@@ -18,8 +18,14 @@
"closeMenu": "Close navigation"
},
"theme": {
"switchToLight": "Switch to light theme",
"switchToDark": "Switch to dark theme"
"title": "Theme",
"label": "Theme: {{mode}}",
"labelAuto": "Theme: automatic (now {{now}})",
"mode": {
"light": "Light",
"dark": "Dark",
"auto": "Automatic"
}
},
"session": {
"unreachable": {
@@ -18,8 +18,14 @@
"closeMenu": "Navigatie sluiten"
},
"theme": {
"switchToLight": "Overschakelen naar licht thema",
"switchToDark": "Overschakelen naar donker thema"
"title": "Thema",
"label": "Thema: {{mode}}",
"labelAuto": "Thema: automatisch (nu {{now}})",
"mode": {
"light": "Licht",
"dark": "Donker",
"auto": "Automatisch"
}
},
"session": {
"unreachable": {