CMS: één bannerlijst met Locatie, SLP-thema, thema-schakelaar, documentatie

- Banner-admin: één lijst met Locatie-badge (Boven/Onder), Locatie-keuzeveld in het formulier, "Live" en "Wordt niet getoond" per locatie, aan/uit per rij
- Thema slpsoftware: Archivo, bordeaux #7A1414 (WCAG AA licht en donker), <SLP/>-logo, favicon, mail-logo; VITE_THEME in de SLP-builds (test en productie-config)
- Thema-schakelaar: eerste klik wisselt altijd het getoonde thema (klasse op <html> als bron van waarheid, gedeelde status, startscript valideert opslag) + tests
- Docs: README, docs/cms-themas.md, docs/deploy-en-testomgevingen.md, docs/privacy-gegevens-contactformulier.md, aidlc-docs (offering-banners, bug theme-toggle-first-click)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 00:14:10 +01:00
co-authored by Claude Sonnet 5.5
parent 4b09089ffb
commit 321234dfa6
28 changed files with 1081 additions and 242 deletions
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useEffect, useState } from 'react';
import { useForm, useWatch } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useTranslation } from 'react-i18next';
@@ -21,9 +21,9 @@ import { useSaveOfferingBanner } from '../services/useSaveOfferingBanner';
import type { BannerPosition, OfferingBannerDto } from '../services/types';
interface OfferingBannerDialogProps {
/** Open for editing this banner (its own position applies); null with `creatingPosition` = a new one there. */
/** Open for editing this banner; null with `creating` = a new one. */
banner: OfferingBannerDto | null;
creatingPosition: BannerPosition | null;
creating: boolean;
onClose: () => void;
}
@@ -52,21 +52,20 @@ function toForm(banner: OfferingBannerDto | null, position: BannerPosition): Off
};
}
export function OfferingBannerDialog({ banner, creatingPosition, onClose }: OfferingBannerDialogProps) {
export function OfferingBannerDialog({ banner, creating, onClose }: OfferingBannerDialogProps) {
const { t } = useTranslation();
const open = creatingPosition !== null || banner !== null;
const position: BannerPosition = banner?.position ?? creatingPosition ?? 'bottom';
const open = creating || banner !== null;
return (
<Dialog open={open} onOpenChange={(next) => { if (!next) onClose(); }}>
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-lg">
<DialogHeader>
<DialogTitle data-testid="banner-dialog-title">
{banner ? t(`offerings.banners.editTitle_${position}`) : t(`offerings.banners.createTitle_${position}`)}
{banner ? t('offerings.banners.editTitle') : t('offerings.banners.createTitle')}
</DialogTitle>
</DialogHeader>
{/* Content is unmounted while closed, so every opening starts from fresh form state. */}
<OfferingBannerForm banner={banner} position={position} onClose={onClose} />
<OfferingBannerForm banner={banner} onClose={onClose} />
</DialogContent>
</Dialog>
);
@@ -74,11 +73,9 @@ export function OfferingBannerDialog({ banner, creatingPosition, onClose }: Offe
function OfferingBannerForm({
banner,
position,
onClose,
}: {
banner: OfferingBannerDto | null;
position: BannerPosition;
onClose: () => void;
}) {
const { t } = useTranslation();
@@ -89,14 +86,22 @@ function OfferingBannerForm({
register,
handleSubmit,
control,
formState: { errors },
trigger,
formState: { errors, isSubmitted },
} = useForm<OfferingBannerFormData>({
resolver: zodResolver(offeringBannerFormSchema),
mode: 'onTouched',
defaultValues: toForm(banner, position),
defaultValues: toForm(banner, 'bottom'),
});
const position: BannerPosition = useWatch({ control, name: 'position' }) ?? 'bottom';
const textMax = bannerTextMaxLength(position);
const textLength = (useWatch({ control, name: 'text' }) ?? '').length;
const textTooLong = textLength > textMax;
// After a failed submit, switching location re-validates so stale title/text errors follow the new rules.
useEffect(() => {
if (isSubmitted) void trigger(['title', 'text']);
}, [position, isSubmitted, trigger]);
const onSubmit = async (values: OfferingBannerFormData) => {
setServerError(null);
@@ -129,6 +134,19 @@ function OfferingBannerForm({
/>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate data-testid="banner-form">
<div className="space-y-2">
<Label htmlFor="banner-position">{t('offerings.banners.position.label')}</Label>
<select
id="banner-position"
data-testid="banner-position"
className="h-10 w-full rounded-md border border-input bg-background px-3 text-sm"
{...register('position')}
>
<option value="top">{t('offerings.banners.position.top')}</option>
<option value="bottom">{t('offerings.banners.position.bottom')}</option>
</select>
</div>
<div className="space-y-2">
<Label htmlFor="banner-title">{t(position === 'top' ? 'offerings.banners.titleLabelOptional' : 'offerings.banners.titleLabel')}</Label>
<Input id="banner-title" data-testid="banner-title" maxLength={100} {...register('title')} />
@@ -152,6 +170,11 @@ function OfferingBannerForm({
{textLength}/{textMax}
{position === 'top' && ` · ${t('offerings.banners.textHintTop')}`}
</p>
{textTooLong && !errors.text && (
<p className="text-sm text-destructive" role="alert" data-testid="banner-text-toolong">
{t('offerings.banners.textTooLong', { length: textLength, max: textMax })}
</p>
)}
<FieldError message={errors.text?.message} testId="banner-text-error" />
</div>
@@ -10,30 +10,34 @@ import { useDeleteOfferingBanner } from '../services/useDeleteOfferingBanner';
import { useSaveOfferingBanner } from '../services/useSaveOfferingBanner';
import { bannerStatus } from '../schemas/offeringBanner';
import { OfferingBannerDialog } from './OfferingBannerDialog';
import type { BannerPosition, OfferingBannerDto } from '../services/types';
import type { OfferingBannerDto } from '../services/types';
const fmt = (iso: string | null) =>
iso ? new Date(iso).toLocaleString('nl-NL', { dateStyle: 'short', timeStyle: 'short' }) : null;
const POSITIONS: BannerPosition[] = ['top', 'bottom'];
const statusVariant = { live: 'default', scheduled: 'secondary', expired: 'outline', off: 'outline' } as const;
/** The banner shown now for one position: among the live ones, the most recently changed wins. */
function liveBannerOf(banners: OfferingBannerDto[], now = new Date()): OfferingBannerDto | null {
const live = banners.filter((b) => bannerStatus(b, now) === 'live');
if (live.length === 0) return null;
return live.reduce((a, b) => (new Date(b.updatedAt) > new Date(a.updatedAt) ? b : a));
/** Ids of the banners actually shown now: per position, among the live ones the most recently changed wins. */
function shownBannerIds(banners: OfferingBannerDto[], now = new Date()): Set<string> {
const winners = new Map<string, OfferingBannerDto>();
for (const b of banners) {
if (bannerStatus(b, now) !== 'live') continue;
const current = winners.get(b.position);
if (!current || new Date(b.updatedAt) > new Date(current.updatedAt)) winners.set(b.position, b);
}
return new Set([...winners.values()].map((b) => b.id));
}
export function OfferingBannersTab() {
const { t } = useTranslation();
const { data: banners, isPending, isError } = useOfferingBanners();
const [editing, setEditing] = useState<OfferingBannerDto | null>(null);
const [creating, setCreating] = useState<BannerPosition | null>(null);
const [creating, setCreating] = useState(false);
const [pendingDelete, setPendingDelete] = useState<OfferingBannerDto | null>(null);
const remove = useDeleteOfferingBanner();
const save = useSaveOfferingBanner();
const items = banners ?? [];
const shownIds = shownBannerIds(items);
const toggleActive = (b: OfferingBannerDto) =>
save.mutate(
@@ -63,120 +67,119 @@ export function OfferingBannersTab() {
{isPending && <p className="text-sm text-muted-foreground">{t('common.loading')}</p>}
{isError && <p className="text-sm text-destructive">{t('errors.generic')}</p>}
{!isPending &&
!isError &&
POSITIONS.map((position) => {
const items = (banners ?? []).filter((b) => b.position === position);
const live = liveBannerOf(items);
return (
<section key={position} className="space-y-3" data-testid={`banners-section-${position}`}>
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="space-y-1">
<h2 className="text-base font-semibold">{t(`offerings.banners.section.${position}.title`)}</h2>
<p className="text-sm text-muted-foreground">
{t(`offerings.banners.section.${position}.description`)}
</p>
<p className="text-xs text-muted-foreground" data-testid={`banner-live-hint-${position}`}>
{live
? t('offerings.banners.liveNow', { title: live.title || live.text })
: t('offerings.banners.nothingActive')}
</p>
</div>
<Button type="button" onClick={() => setCreating(position)} data-testid={`banner-add-${position}`}>
<Plus className="mr-1 size-4" aria-hidden="true" />
{t(`offerings.banners.section.${position}.addButton`)}
</Button>
</div>
{!isPending && !isError && (
<>
<div className="flex justify-end">
<Button type="button" onClick={() => setCreating(true)} data-testid="banner-add">
<Plus className="mr-1 size-4" aria-hidden="true" />
{t('offerings.banners.addButton')}
</Button>
</div>
{items.length === 0 ? (
<div
className="flex flex-col items-center space-y-2 py-8 text-center"
data-testid={`banners-empty-${position}`}
>
<Megaphone className="size-8 text-muted-foreground" aria-hidden="true" />
<p className="text-muted-foreground">{t('offerings.banners.empty')}</p>
</div>
) : (
<ul className="space-y-2" data-testid={`banners-list-${position}`}>
{items.map((b) => {
const status = bannerStatus(b);
const toggleLabel = t(
b.isActive ? 'offerings.banners.turnOffButton' : 'offerings.banners.turnOnButton',
);
return (
<li
key={b.id}
className="flex flex-col gap-2 rounded-md border p-3 sm:flex-row sm:items-center sm:justify-between"
data-testid={`banner-row-${b.id}`}
{items.length === 0 ? (
<div className="flex flex-col items-center space-y-2 py-8 text-center" data-testid="banners-empty">
<Megaphone className="size-8 text-muted-foreground" aria-hidden="true" />
<p className="text-muted-foreground">{t('offerings.banners.empty')}</p>
</div>
) : (
<ul className="space-y-2" data-testid="banners-list">
{items.map((b) => {
const status = bannerStatus(b);
const shown = shownIds.has(b.id);
const hidden = status === 'live' && !shown;
const toggleLabel = t(
b.isActive ? 'offerings.banners.turnOffButton' : 'offerings.banners.turnOnButton',
);
return (
<li
key={b.id}
className="flex flex-col gap-2 rounded-md border p-3 sm:flex-row sm:items-center sm:justify-between"
data-testid={`banner-row-${b.id}`}
>
<div className="min-w-0 space-y-1">
<div className="flex flex-wrap items-center gap-2">
{b.title && <span className="font-medium">{b.title}</span>}
<Badge variant="outline" data-testid={`banner-position-${b.id}`}>
{t(`offerings.banners.position.${b.position}`)}
</Badge>
<Badge variant={statusVariant[status]} data-testid={`banner-status-${b.id}`}>
{t(`offerings.banners.status.${status}`)}
</Badge>
{shown && (
<Badge data-testid={`banner-shown-${b.id}`}>{t('offerings.banners.shownBadge')}</Badge>
)}
{hidden && (
<Badge variant="destructive" data-testid={`banner-not-shown-${b.id}`}>
{t('offerings.banners.notShownBadge')}
</Badge>
)}
</div>
<p className="truncate text-sm text-muted-foreground">{b.text}</p>
{hidden && (
<p className="text-xs text-destructive" data-testid={`banner-not-shown-hint-${b.id}`}>
{t('offerings.banners.notShownHint')}
</p>
)}
{(b.startsAt || b.endsAt) && (
<p className="text-xs text-muted-foreground">
{fmt(b.startsAt) ?? '…'} – {fmt(b.endsAt) ?? '…'}
</p>
)}
</div>
<div className="flex shrink-0 gap-2">
<Button
type="button"
variant="outline"
size="icon"
className="size-11"
aria-label={toggleLabel}
title={toggleLabel}
disabled={save.isPending}
data-testid={`banner-toggle-${b.id}`}
onClick={() => toggleActive(b)}
>
<div className="min-w-0 space-y-1">
<div className="flex flex-wrap items-center gap-2">
{b.title && <span className="font-medium">{b.title}</span>}
<Badge variant={statusVariant[status]} data-testid={`banner-status-${b.id}`}>
{t(`offerings.banners.status.${status}`)}
</Badge>
</div>
<p className="truncate text-sm text-muted-foreground">{b.text}</p>
{(b.startsAt || b.endsAt) && (
<p className="text-xs text-muted-foreground">
{fmt(b.startsAt) ?? '…'} – {fmt(b.endsAt) ?? '…'}
</p>
)}
</div>
<div className="flex shrink-0 gap-2">
<Button
type="button"
variant="outline"
size="icon"
className="size-11"
aria-label={toggleLabel}
title={toggleLabel}
disabled={save.isPending}
data-testid={`banner-toggle-${b.id}`}
onClick={() => toggleActive(b)}
>
<Power className="size-4" aria-hidden="true" />
</Button>
<Button
type="button"
variant="outline"
size="icon"
className="size-11"
aria-label={t('offerings.banners.editButton')}
title={t('offerings.banners.editButton')}
data-testid={`banner-edit-${b.id}`}
onClick={() => setEditing(b)}
>
<Pencil className="size-4" aria-hidden="true" />
</Button>
<Button
type="button"
variant="outline"
size="icon"
className="size-11"
aria-label={t('offerings.banners.deleteButton')}
title={t('offerings.banners.deleteButton')}
data-testid={`banner-delete-${b.id}`}
onClick={() => setPendingDelete(b)}
>
<Trash2 className="size-4" aria-hidden="true" />
</Button>
</div>
</li>
);
})}
</ul>
)}
</section>
);
})}
<Power className="size-4" aria-hidden="true" />
</Button>
<Button
type="button"
variant="outline"
size="icon"
className="size-11"
aria-label={t('offerings.banners.editButton')}
title={t('offerings.banners.editButton')}
data-testid={`banner-edit-${b.id}`}
onClick={() => setEditing(b)}
>
<Pencil className="size-4" aria-hidden="true" />
</Button>
<Button
type="button"
variant="outline"
size="icon"
className="size-11"
aria-label={t('offerings.banners.deleteButton')}
title={t('offerings.banners.deleteButton')}
data-testid={`banner-delete-${b.id}`}
onClick={() => setPendingDelete(b)}
>
<Trash2 className="size-4" aria-hidden="true" />
</Button>
</div>
</li>
);
})}
</ul>
)}
</>
)}
<OfferingBannerDialog
banner={editing}
creatingPosition={creating}
creating={creating}
onClose={() => {
setEditing(null);
setCreating(null);
setCreating(false);
}}
/>
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { screen, waitFor, within } from '@testing-library/react';
import { fireEvent, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { renderApp, mockAuthenticated } from '@/test/utils';
import { getMockBanners, resetMockOfferings, setMockBanners } from '@/features/offerings/mocks/handlers';
@@ -55,24 +55,19 @@ describe('Banner tab', () => {
expect(await screen.findByTestId('offerings-add-button')).toBeInTheDocument();
});
it('shows two sections (top and bottom), each with its own empty state and "nothing active" hint', async () => {
it('shows one list with an empty state and a single add button', async () => {
await openBannerTab();
const top = await screen.findByTestId('banners-section-top', {}, T);
const bottom = screen.getByTestId('banners-section-bottom');
expect(within(top).getByTestId('banners-empty-top')).toBeInTheDocument();
expect(within(bottom).getByTestId('banners-empty-bottom')).toBeInTheDocument();
expect(within(top).getByTestId('banner-add-top')).toBeInTheDocument();
expect(within(bottom).getByTestId('banner-add-bottom')).toBeInTheDocument();
expect(screen.getByTestId('banner-live-hint-top')).toHaveTextContent(/niets actief|Nothing is active/);
expect(screen.getByTestId('banner-live-hint-bottom')).toHaveTextContent(/niets actief|Nothing is active/);
expect(await screen.findByTestId('banners-empty', {}, T)).toBeInTheDocument();
expect(screen.getByTestId('banner-add')).toBeInTheDocument();
expect(screen.queryByTestId('banners-section-top')).not.toBeInTheDocument();
expect(screen.queryByTestId('banner-add-top')).not.toBeInTheDocument();
});
it('creates a bottom banner with a link and a schedule, sending position bottom', async () => {
it('creates a banner defaulting to location bottom, with a link and a schedule', async () => {
await openBannerTab();
expect(await screen.findByTestId('banners-empty-bottom', {}, T)).toBeInTheDocument();
await userEvent.click(screen.getByTestId('banner-add-bottom'));
await userEvent.type(await screen.findByTestId('banner-title'), 'Zomeractie');
await userEvent.click(await screen.findByTestId('banner-add', {}, T));
expect(await screen.findByTestId('banner-position')).toHaveValue('bottom');
await userEvent.type(screen.getByTestId('banner-title'), 'Zomeractie');
await userEvent.type(screen.getByTestId('banner-text'), '10% korting in juli');
await userEvent.type(screen.getByTestId('banner-link-label'), 'Bekijk');
await userEvent.type(screen.getByTestId('banner-link-url'), '/privacy');
@@ -91,41 +86,67 @@ describe('Banner tab', () => {
});
expect(saved.startsAt).toBe(fromLocalInput('2030-07-01T09:00'));
expect(await screen.findByText('Zomeractie')).toBeInTheDocument();
expect(within(screen.getByTestId('banners-section-bottom')).getByTestId(`banner-status-${saved.id}`)).toHaveTextContent(
/Gepland|Scheduled/,
);
expect(screen.getByTestId('banners-empty-top')).toBeInTheDocument();
expect(screen.getByTestId(`banner-position-${saved.id}`)).toHaveTextContent(/Onder|Bottom/);
expect(screen.getByTestId(`banner-status-${saved.id}`)).toHaveTextContent(/Gepland|Scheduled/);
});
it('requires a title for a bottom banner', async () => {
it('requires a title at location bottom', async () => {
await openBannerTab();
await userEvent.click(await screen.findByTestId('banner-add-bottom', {}, T));
await userEvent.click(await screen.findByTestId('banner-add', {}, T));
await userEvent.type(await screen.findByTestId('banner-text'), 'Alleen tekst');
await userEvent.click(screen.getByTestId('banner-submit'));
expect(await screen.findByTestId('banner-title-error')).toBeInTheDocument();
expect(getMockBanners()).toHaveLength(0);
});
it('creates a top banner without a title, limited to 120 characters with a counter', async () => {
it('creates a top banner without a title; the text limit follows the chosen location live', async () => {
await openBannerTab();
await userEvent.click(await screen.findByTestId('banner-add-top', {}, T));
expect(await screen.findByTestId('banner-text')).toHaveAttribute('maxlength', '120');
await userEvent.click(await screen.findByTestId('banner-add', {}, T));
const text = await screen.findByTestId('banner-text');
expect(text).toHaveAttribute('maxlength', '300');
expect(screen.getByTestId('banner-text-counter')).toHaveTextContent('0/300');
await userEvent.selectOptions(screen.getByTestId('banner-position'), 'top');
expect(text).toHaveAttribute('maxlength', '120');
expect(screen.getByTestId('banner-text-counter')).toHaveTextContent('0/120');
await userEvent.type(screen.getByTestId('banner-text'), 'Gratis verzending deze week');
await userEvent.type(text, 'Gratis verzending deze week');
expect(screen.getByTestId('banner-text-counter')).toHaveTextContent('27/120');
await userEvent.click(screen.getByTestId('banner-submit'));
await waitFor(() => expect(getMockBanners()).toHaveLength(1));
expect(getMockBanners()[0]).toMatchObject({ position: 'top', title: '', text: 'Gratis verzending deze week' });
const top = screen.getByTestId('banners-section-top');
expect(await within(top).findByText('Gratis verzending deze week')).toBeInTheDocument();
expect(screen.getByTestId('banners-empty-bottom')).toBeInTheDocument();
const saved = getMockBanners()[0];
expect(saved).toMatchObject({ position: 'top', title: '', text: 'Gratis verzending deze week' });
expect(await screen.findByTestId(`banner-position-${saved.id}`)).toHaveTextContent(/Boven|Top/);
});
it('does not silently truncate: switching to top with too long text shows a visible error and blocks saving', async () => {
await openBannerTab();
await userEvent.click(await screen.findByTestId('banner-add', {}, T));
await userEvent.type(await screen.findByTestId('banner-title'), 'Titel');
fireEvent.change(screen.getByTestId('banner-text'), { target: { value: 'x'.repeat(200) } });
expect(screen.getByTestId('banner-text-counter')).toHaveTextContent('200/300');
expect(screen.queryByTestId('banner-text-toolong')).not.toBeInTheDocument();
await userEvent.selectOptions(screen.getByTestId('banner-position'), 'top');
expect(screen.getByTestId('banner-text')).toHaveValue('x'.repeat(200));
expect(screen.getByTestId('banner-text-counter')).toHaveTextContent('200/120');
expect(await screen.findByTestId('banner-text-toolong')).toBeInTheDocument();
await userEvent.click(screen.getByTestId('banner-submit'));
expect(await screen.findByTestId('banner-text-error')).toBeInTheDocument();
expect(getMockBanners()).toHaveLength(0);
await userEvent.selectOptions(screen.getByTestId('banner-position'), 'bottom');
await waitFor(() => expect(screen.queryByTestId('banner-text-error')).not.toBeInTheDocument());
expect(screen.queryByTestId('banner-text-toolong')).not.toBeInTheDocument();
await userEvent.click(screen.getByTestId('banner-submit'));
await waitFor(() => expect(getMockBanners()).toHaveLength(1));
});
it('rejects an unsafe link and a link without button text, and an end before the start', async () => {
await openBannerTab();
await userEvent.click(await screen.findByTestId('banner-add-bottom', {}, T));
await userEvent.click(await screen.findByTestId('banner-add', {}, T));
await userEvent.type(await screen.findByTestId('banner-title'), 'X');
await userEvent.type(screen.getByTestId('banner-text'), 'Y');
@@ -148,41 +169,58 @@ describe('Banner tab', () => {
expect(getMockBanners()).toHaveLength(0);
});
it('lists banners under their own position and shows which one is live (most recently changed wins)', async () => {
it('lists all banners in one list in API order with a location badge per row', async () => {
setMockBanners([
banner({ id: 'b-old', title: 'Oud', updatedAt: '2026-01-01T00:00:00Z' }),
banner({ id: 'b-new', title: 'Nieuw', updatedAt: '2026-02-01T00:00:00Z' }),
banner({ id: 't1', position: 'top', title: '', text: 'Balktekst' }),
]);
await openBannerTab();
const top = await screen.findByTestId('banners-section-top', {}, T);
const bottom = screen.getByTestId('banners-section-bottom');
expect(within(top).getByTestId('banner-row-t1')).toBeInTheDocument();
expect(within(top).queryByTestId('banner-row-b-new')).not.toBeInTheDocument();
expect(within(bottom).getByTestId('banner-row-b-old')).toBeInTheDocument();
expect(within(bottom).getByTestId('banner-row-b-new')).toBeInTheDocument();
expect(screen.getByTestId('banner-live-hint-bottom')).toHaveTextContent(/Nu live: Nieuw|Live now: Nieuw/);
expect(screen.getByTestId('banner-live-hint-top')).toHaveTextContent(/Balktekst/);
const list = await screen.findByTestId('banners-list', {}, T);
const rows = within(list).getAllByTestId(/^banner-row-/);
expect(rows.map((r) => r.getAttribute('data-testid'))).toEqual(['banner-row-b-new', 'banner-row-t1']);
expect(screen.getByTestId('banner-position-b-new')).toHaveTextContent(/Onder|Bottom/);
expect(screen.getByTestId('banner-position-t1')).toHaveTextContent(/Boven|Top/);
});
it('turns a banner off and on from its section', async () => {
setMockBanners([banner({ id: 't1', position: 'top', title: '', text: 'Balktekst' })]);
it('marks the shown banner per location and flags older live banners on the same location as not shown', async () => {
setMockBanners([
banner({ id: 'b-old', title: 'Oud', updatedAt: '2026-01-01T00:00:00Z' }),
banner({ id: 'b-new', title: 'Nieuw', updatedAt: '2026-02-01T00:00:00Z' }),
banner({ id: 't1', position: 'top', title: '', text: 'Balktekst' }),
banner({ id: 'b-off', title: 'Uit', isActive: false, updatedAt: '2026-03-01T00:00:00Z' }),
]);
await openBannerTab();
expect(await screen.findByTestId('banner-status-t1', {}, T)).toHaveTextContent(/Actief|Active/);
await userEvent.click(screen.getByTestId('banner-toggle-t1'));
await waitFor(() => expect(getMockBanners()[0].isActive).toBe(false));
expect(getMockBanners()[0].position).toBe('top');
expect(await screen.findByTestId('banner-status-t1')).toHaveTextContent(/Uit|Off/);
expect(screen.getByTestId('banner-live-hint-top')).toHaveTextContent(/niets actief|Nothing is active/);
await userEvent.click(screen.getByTestId('banner-toggle-t1'));
await waitFor(() => expect(getMockBanners()[0].isActive).toBe(true));
expect(await screen.findByTestId('banner-shown-b-new', {}, T)).toBeInTheDocument();
expect(screen.getByTestId('banner-shown-t1')).toBeInTheDocument();
expect(screen.getByTestId('banner-not-shown-b-old')).toBeInTheDocument();
expect(screen.getByTestId('banner-not-shown-hint-b-old')).toHaveTextContent(/niet getoond|Not shown/);
expect(screen.queryByTestId('banner-shown-b-old')).not.toBeInTheDocument();
expect(screen.queryByTestId('banner-not-shown-b-new')).not.toBeInTheDocument();
// An inactive banner is neither shown nor flagged.
expect(screen.queryByTestId('banner-shown-b-off')).not.toBeInTheDocument();
expect(screen.queryByTestId('banner-not-shown-b-off')).not.toBeInTheDocument();
});
it('edits and deletes an existing banner, keeping its position', async () => {
it('turns a banner off and on, moving the shown mark to the next live banner', async () => {
setMockBanners([
banner({ id: 'b-old', title: 'Oud', updatedAt: '2026-01-01T00:00:00Z' }),
banner({ id: 'b-new', title: 'Nieuw', updatedAt: '2026-02-01T00:00:00Z' }),
]);
await openBannerTab();
expect(await screen.findByTestId('banner-status-b-new', {}, T)).toHaveTextContent(/Actief|Active/);
await userEvent.click(screen.getByTestId('banner-toggle-b-new'));
await waitFor(() => expect(getMockBanners().find((b) => b.id === 'b-new')?.isActive).toBe(false));
expect(getMockBanners().find((b) => b.id === 'b-new')?.position).toBe('bottom');
expect(await screen.findByTestId('banner-status-b-new')).toHaveTextContent(/Uit|Off/);
expect(await screen.findByTestId('banner-shown-b-old')).toBeInTheDocument();
expect(screen.queryByTestId('banner-not-shown-b-old')).not.toBeInTheDocument();
await userEvent.click(screen.getByTestId('banner-toggle-b-new'));
await waitFor(() => expect(getMockBanners().find((b) => b.id === 'b-new')?.isActive).toBe(true));
});
it('edits a banner including its location (top keeps title optional), then deletes it', async () => {
setMockBanners([banner({ id: 'b1', title: 'Oud' })]);
await openBannerTab();
expect(await screen.findByTestId('banner-status-b1', {}, T)).toHaveTextContent(/Actief|Active/);
@@ -190,18 +228,21 @@ describe('Banner tab', () => {
await userEvent.click(screen.getByTestId('banner-edit-b1'));
const title = await screen.findByTestId('banner-title');
expect(title).toHaveValue('Oud');
expect(screen.getByTestId('banner-position')).toHaveValue('bottom');
await userEvent.clear(title);
await userEvent.type(title, 'Nieuw');
await userEvent.selectOptions(screen.getByTestId('banner-position'), 'top');
expect(screen.getByTestId('banner-text')).toHaveAttribute('maxlength', '120');
await userEvent.click(screen.getByTestId('banner-active'));
await userEvent.click(screen.getByTestId('banner-submit'));
await waitFor(() => expect(getMockBanners()[0]).toMatchObject({ title: 'Nieuw', isActive: false, position: 'bottom' }));
await waitFor(() => expect(getMockBanners()[0]).toMatchObject({ title: '', isActive: false, position: 'top' }));
expect(await screen.findByTestId('banner-status-b1')).toHaveTextContent(/Uit|Off/);
expect(screen.getByTestId('banner-position-b1')).toHaveTextContent(/Boven|Top/);
await userEvent.click(screen.getByTestId('banner-delete-b1'));
expect(await screen.findByTestId('banner-delete-message')).toHaveTextContent('Nieuw');
expect(await screen.findByTestId('banner-delete-message')).toHaveTextContent('Tekst');
await userEvent.click(screen.getByTestId('banner-delete-confirm'));
await waitFor(() => expect(getMockBanners()).toHaveLength(0));
expect(await screen.findByTestId('banners-empty-bottom')).toBeInTheDocument();
expect(await screen.findByTestId('banners-empty')).toBeInTheDocument();
});
});
+54
View File
@@ -48,3 +48,57 @@ describe('useTheme', () => {
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');
const { result } = renderHook(() => useTheme());
expect(shown()).toBe(os);
act(() => { result.current.toggleTheme(); });
expect(shown()).toBe(expected);
expect(result.current.theme).toBe(expected);
});
it('flips from what is shown even when the stored value is unusable', () => {
localStorage.setItem('cms-theme', 'system');
media(true);
document.documentElement.className = 'system';
const { result } = renderHook(() => useTheme());
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');
document.documentElement.className = 'dark';
const { result } = renderHook(() => useTheme());
expect(result.current.theme).toBe('dark');
act(() => { result.current.toggleTheme(); });
expect(shown()).toBe('light');
expect(localStorage.getItem('cms-theme')).toBe('light');
});
it('keeps two toggles on the page in step', () => {
localStorage.setItem('cms-theme', 'light');
const a = renderHook(() => useTheme());
const b = renderHook(() => useTheme());
act(() => { a.result.current.toggleTheme(); });
expect(b.result.current.theme).toBe('dark');
act(() => { b.result.current.toggleTheme(); });
expect(shown()).toBe('light');
expect(a.result.current.theme).toBe('light');
});
});
+46 -10
View File
@@ -1,26 +1,62 @@
import { useState, useCallback } from 'react';
import { useCallback, useSyncExternalStore } from 'react';
type Theme = 'light' | 'dark';
const STORAGE_KEY = 'cms-theme';
function getInitialTheme(): Theme {
const listeners = new Set<() => void>();
function isTheme(value: string | null): value is Theme {
return value === 'light' || value === 'dark';
}
function preferredTheme(): Theme {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored === 'light' || stored === 'dark') return stored;
if (isTheme(stored)) return stored;
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
function apply(theme: Theme) {
document.documentElement.classList.remove('light', 'dark');
document.documentElement.classList.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();
apply(theme);
return theme;
}
function subscribe(listener: () => void) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
export function useTheme() {
const [theme, setTheme] = useState<Theme>(getInitialTheme);
// One source of truth shared by every toggle on the page (desktop sidebar, mobile overlay).
const theme = useSyncExternalStore(subscribe, currentTheme, () => 'light' as Theme);
const toggleTheme = useCallback(() => {
setTheme((current) => {
const next: Theme = current === 'dark' ? 'light' : 'dark';
const next: Theme = currentTheme() === 'dark' ? 'light' : 'dark';
try {
localStorage.setItem(STORAGE_KEY, next);
document.documentElement.classList.remove('light', 'dark');
document.documentElement.classList.add(next);
return next;
});
} catch {
// Storage can be unavailable (private mode); the switch itself still works.
}
apply(next);
listeners.forEach((notify) => notify());
}, []);
return { theme, isDark: theme === 'dark', toggleTheme };
+9 -18
View File
@@ -325,28 +325,19 @@
"title": "Offerings",
"addButton": "Add Offering",
"banners": {
"intro": "A banner is a wide announcement or promotion on the website. Plan ahead with a start and end time. At most one banner is shown per spot (top and bottom) at any time: the most recently changed active one.",
"section": {
"top": {
"title": "Top",
"description": "Narrow bar at the top of the website, one line of text.",
"addButton": "Add top banner"
},
"bottom": {
"title": "Bottom",
"description": "Large banner at the bottom of the page with title, text and button.",
"addButton": "Add bottom banner"
}
"intro": "A banner is a wide announcement or promotion on the website. Plan ahead with a start and end time. At most one banner is shown per location (top and bottom) at any time: the most recently changed active one.",
"position": {
"label": "Location",
"top": "Top",
"bottom": "Bottom"
},
"liveNow": "Live now: {{title}}",
"nothingActive": "Nothing is active in this spot right now.",
"shownBadge": "Live",
"notShownBadge": "Not shown",
"notShownHint": "Not shown: a newer banner at this location",
"turnOffButton": "Turn banner off",
"turnOnButton": "Turn banner on",
"createTitle_top": "New banner (top)",
"createTitle_bottom": "New banner (bottom)",
"editTitle_top": "Edit banner (top)",
"editTitle_bottom": "Edit banner (bottom)",
"titleLabelOptional": "Title (optional)",
"textTooLong": "The text is {{length}} characters; this location allows at most {{max}}. Shorten the text or pick another location.",
"textHintTop": "One short line, up to 120 characters.",
"addButton": "Add banner",
"empty": "No banners yet.",
+9 -18
View File
@@ -325,28 +325,19 @@
"title": "Aanbiedingen",
"addButton": "Aanbieding toevoegen",
"banners": {
"intro": "Een banner is een brede mededeling of actie op de website. Plan vooruit met een begin- en eindtijd. Per plek (boven en onder) wordt altijd maximaal één banner getoond: de laatst gewijzigde actieve.",
"section": {
"top": {
"title": "Boven",
"description": "Smalle balk bovenaan de website, één regel tekst.",
"addButton": "Banner boven toevoegen"
},
"bottom": {
"title": "Onder",
"description": "Grote banner onderaan de pagina met titel, tekst en knop.",
"addButton": "Banner onder toevoegen"
}
"intro": "Een banner is een brede mededeling of actie op de website. Plan vooruit met een begin- en eindtijd. Per locatie (boven en onder) wordt maximaal één banner getoond: de laatst gewijzigde actieve.",
"position": {
"label": "Locatie",
"top": "Boven",
"bottom": "Onder"
},
"liveNow": "Nu live: {{title}}",
"nothingActive": "Er is nu niets actief op deze plek.",
"shownBadge": "Live",
"notShownBadge": "Wordt niet getoond",
"notShownHint": "Wordt niet getoond: nieuwere banner op deze locatie",
"turnOffButton": "Banner uitzetten",
"turnOnButton": "Banner aanzetten",
"createTitle_top": "Nieuwe banner (boven)",
"createTitle_bottom": "Nieuwe banner (onder)",
"editTitle_top": "Banner bewerken (boven)",
"editTitle_bottom": "Banner bewerken (onder)",
"titleLabelOptional": "Titel (optioneel)",
"textTooLong": "De tekst is {{length}} tekens; voor deze locatie zijn maximaal {{max}} tekens toegestaan. Kort de tekst in of kies een andere locatie.",
"textHintTop": "Eén korte regel, maximaal 120 tekens.",
"addButton": "Banner toevoegen",
"empty": "Nog geen banners.",