Admin Berichten: toggle-switch, statusicoon, archiveren/terugzetten (CMS-U10)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 23:20:05 +01:00
co-authored by Claude Sonnet 5.5
parent 5378c21799
commit 787131002f
10 changed files with 245 additions and 78 deletions
@@ -0,0 +1,9 @@
# CMS-U10 — Berichten UX (summary)
Frontend only, `frontend/src/features/contact` + nl/en texts (`contact.switch.on|off`, `contact.detail.archive|restore`).
- **Form switch**: new `ToggleSwitch` (native button, `role="switch"`, `aria-checked`, label as accessible name, state as visible text "Aan"/"Uit", `min-h-11 min-w-11` target, Space/Enter, disabled while saving). Existing error handling, toast and first-time hint unchanged.
- **Status**: new `StatusIcon` (envelope = new, open envelope = read, archive box = archived, shield = spam) with the name as visible text and `title`; the same component in the list and the detail dialog. The status select is gone.
- **Detail actions**: opening an unread message still marks it read automatically (no button). Buttons: Archiveren (new/read), Terugzetten (archived -> read), Geen spam (spam), Verwijderen, Opnieuw mailen.
- **Subject**: shown literally as the site sent it (no transformation); mock data now uses capitalised labels ('Website', 'Onderhoudspakket', 'Overig'). The local dev database was re-seeded with such labels (not part of the repo).
- Tests: switch (role, name, state text, 44px classes, Space/Enter, disabled while saving), no select, status icon with text in list and detail, archive/restore flow, literal subject. Lint and `tsc -b` clean, vitest 59 files / 470 tests.
@@ -1,9 +1,9 @@
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card'; import { Card, CardContent } from '@/components/ui/card';
import { useContactSettings, useUpdateContactSettings } from '../services/useContactSettings'; import { useContactSettings, useUpdateContactSettings } from '../services/useContactSettings';
import { contactErrorMessage } from '../errors'; import { contactErrorMessage } from '../errors';
import { ToggleSwitch } from './ToggleSwitch';
/** The form switch: whether the contact form on the website is open. The state shown is the server's. */ /** The form switch: whether the contact form on the website is open. The state shown is the server's. */
export function FormSwitchCard() { export function FormSwitchCard() {
@@ -14,8 +14,8 @@ export function FormSwitchCard() {
if (!settings) return null; if (!settings) return null;
const open = settings.enabled; const open = settings.enabled;
const toggle = () => const toggle = (next: boolean) =>
update.mutate(!open, { update.mutate(next, {
onSuccess: (saved) => onSuccess: (saved) =>
toast.success( toast.success(
saved.enabled ? t('contact.switch.nowOn') : t('contact.switch.nowOff'), saved.enabled ? t('contact.switch.nowOn') : t('contact.switch.nowOff'),
@@ -33,18 +33,14 @@ export function FormSwitchCard() {
</p> </p>
</div> </div>
{settings.hostEnabled ? ( {settings.hostEnabled ? (
<Button <ToggleSwitch
type="button" checked={open}
role="switch" onCheckedChange={toggle}
aria-checked={open} label={t('contact.switch.title')}
aria-label={t('contact.switch.title')} stateText={open ? t('contact.switch.on') : t('contact.switch.off')}
variant={open ? 'default' : 'outline'}
disabled={update.isPending} disabled={update.isPending}
onClick={toggle}
data-testid="contact-switch-toggle" data-testid="contact-switch-toggle"
> />
{open ? t('contact.switch.turnOff') : t('contact.switch.turnOn')}
</Button>
) : ( ) : (
<p <p
className="text-sm text-muted-foreground" className="text-sm text-muted-foreground"
@@ -14,7 +14,7 @@ import {
useResendContactMessage, useResendContactMessage,
useUpdateContactMessageStatus, useUpdateContactMessageStatus,
} from '../services/useContactMessages'; } from '../services/useContactMessages';
import type { SettableStatus } from '../services/types'; import { StatusIcon } from './StatusIcon';
import { contactErrorMessage, mailErrorLabel } from '../errors'; import { contactErrorMessage, mailErrorLabel } from '../errors';
import { MailStatusIcon } from './MessagesTable'; import { MailStatusIcon } from './MessagesTable';
@@ -24,8 +24,6 @@ interface Props {
onDeleteRequested: (id: string) => void; onDeleteRequested: (id: string) => void;
} }
const SETTABLE: SettableStatus[] = ['new', 'read', 'archived'];
export function MessageDialog({ id, onClose, onDeleteRequested }: Props) { export function MessageDialog({ id, onClose, onDeleteRequested }: Props) {
const { t, i18n } = useTranslation(); const { t, i18n } = useTranslation();
const { data: message, isPending, isError } = useContactMessage(id); const { data: message, isPending, isError } = useContactMessage(id);
@@ -118,52 +116,55 @@ export function MessageDialog({ id, onClose, onDeleteRequested }: Props) {
{message.message} {message.message}
</p> </p>
<div className="flex items-center gap-2 text-sm"> <div className="flex flex-wrap items-center gap-2 text-sm">
<label <span className="text-muted-foreground">
htmlFor="contact-status-select"
className="text-muted-foreground"
>
{t('contact.table.status')} {t('contact.table.status')}
</label> </span>
{isSpam ? ( <StatusIcon status={message.status} />
<> {isSpam && (
<span>{t('contact.status.spam')}</span> <Button
<Button type="button"
type="button" size="sm"
size="sm" variant="outline"
variant="outline"
disabled={setStatus.isPending}
onClick={() =>
setStatus.mutate(
{ id: message.id, status: 'read' },
{ onSuccess: onClose },
)
}
data-testid="contact-not-spam"
>
{t('contact.detail.notSpam')}
</Button>
</>
) : (
<select
id="contact-status-select"
value={message.status}
disabled={setStatus.isPending} disabled={setStatus.isPending}
onChange={(e) => onClick={() =>
setStatus.mutate({ setStatus.mutate(
id: message.id, { id: message.id, status: 'read' },
status: e.target.value as SettableStatus, { onSuccess: onClose },
}) )
} }
className="h-9 rounded-md border border-input bg-background px-2" data-testid="contact-not-spam"
data-testid="contact-status-select"
> >
{SETTABLE.map((s) => ( {t('contact.detail.notSpam')}
<option key={s} value={s}> </Button>
{t(`contact.status.${s}`)} )}
</option> {(message.status === 'new' || message.status === 'read') && (
))} <Button
</select> type="button"
size="sm"
variant="outline"
disabled={setStatus.isPending}
onClick={() =>
setStatus.mutate({ id: message.id, status: 'archived' })
}
data-testid="contact-archive-button"
>
{t('contact.detail.archive')}
</Button>
)}
{message.status === 'archived' && (
<Button
type="button"
size="sm"
variant="outline"
disabled={setStatus.isPending}
onClick={() =>
setStatus.mutate({ id: message.id, status: 'read' })
}
data-testid="contact-restore-button"
>
{t('contact.detail.restore')}
</Button>
)} )}
</div> </div>
{setStatus.isError && ( {setStatus.isError && (
@@ -1,6 +1,6 @@
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { CheckCircle2, Clock, MinusCircle, XCircle } from 'lucide-react'; import { CheckCircle2, Clock, MinusCircle, XCircle } from 'lucide-react';
import { Badge } from '@/components/ui/badge'; import { StatusIcon } from './StatusIcon';
import type { ContactMailStatus, ContactMessageListItem } from '../services/types'; import type { ContactMailStatus, ContactMessageListItem } from '../services/types';
export function MailStatusIcon({ status }: { status: ContactMailStatus }) { export function MailStatusIcon({ status }: { status: ContactMailStatus }) {
@@ -76,17 +76,7 @@ export function MessagesTable({ items, onOpen }: Props) {
<td className="p-2">{m.email}</td> <td className="p-2">{m.email}</td>
<td className="p-2">{m.subject}</td> <td className="p-2">{m.subject}</td>
<td className="p-2"> <td className="p-2">
<Badge <StatusIcon status={m.status} />
variant={
m.status === 'spam'
? 'destructive'
: m.status === 'new'
? 'default'
: 'secondary'
}
>
{t(`contact.status.${m.status}`)}
</Badge>
</td> </td>
<td className="p-2"> <td className="p-2">
<MailStatusIcon status={m.mailStatus} /> <MailStatusIcon status={m.mailStatus} />
@@ -0,0 +1,34 @@
import { useTranslation } from 'react-i18next';
import { Archive, Mail, MailOpen, ShieldAlert, type LucideIcon } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import type { ContactStatus } from '../services/types';
const ICONS: Record<ContactStatus, LucideIcon> = {
new: Mail,
read: MailOpen,
archived: Archive,
spam: ShieldAlert,
// Not produced by the management screen (kept for completeness of the API's status set).
converted: MailOpen,
};
/**
* The status of a message as an icon plus its name as visible text (never colour alone): closed envelope = new,
* open envelope = read, archive box = archived, shield = spam. The same component is used in the list and the detail.
*/
export function StatusIcon({ status }: { status: ContactStatus }) {
const { t } = useTranslation();
const Icon = ICONS[status];
const label = t(`contact.status.${status}`);
return (
<Badge
variant={status === 'spam' ? 'destructive' : status === 'new' ? 'default' : 'secondary'}
className="gap-1.5"
title={label}
data-testid={`status-icon-${status}`}
>
<Icon className="size-3.5" aria-hidden="true" />
<span>{label}</span>
</Badge>
);
}
@@ -0,0 +1,56 @@
import { cn } from '@/lib/utils';
interface ToggleSwitchProps {
checked: boolean;
onCheckedChange: (checked: boolean) => void;
/** The visible label; it is also the accessible name of the switch. */
label: string;
/** The state as text ("On"/"Off"), so the state is never conveyed by colour or position alone. */
stateText: string;
disabled?: boolean;
'data-testid'?: string;
}
/**
* A toggle switch: a native button with role="switch" (Space and Enter work out of the box), a 44px touch target,
* the label and the state as visible text.
*/
export function ToggleSwitch({
checked,
onCheckedChange,
label,
stateText,
disabled = false,
'data-testid': testId,
}: ToggleSwitchProps) {
return (
<button
type="button"
role="switch"
aria-checked={checked}
aria-label={label}
disabled={disabled}
onClick={() => onCheckedChange(!checked)}
data-testid={testId}
className="inline-flex min-h-11 min-w-11 items-center gap-3 rounded-md px-1 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-60"
>
<span
aria-hidden="true"
className={cn(
'relative inline-flex h-7 w-12 shrink-0 items-center rounded-full border transition-colors',
checked ? 'border-primary bg-primary' : 'border-input bg-muted',
)}
>
<span
className={cn(
'inline-block size-5 rounded-full bg-background shadow transition-transform',
checked ? 'translate-x-6' : 'translate-x-1',
)}
/>
</span>
<span className="text-sm font-medium" data-testid="toggle-switch-state">
{stateText}
</span>
</button>
);
}
@@ -27,7 +27,7 @@ function seed(): ContactMessageDetail[] {
receivedAt: '2026-11-09T10:00:00Z', receivedAt: '2026-11-09T10:00:00Z',
name: 'Jan Jansen', name: 'Jan Jansen',
email: 'jan@example.nl', email: 'jan@example.nl',
subject: 'website', subject: 'Website',
message: 'Eerste regel\nTweede regel', message: 'Eerste regel\nTweede regel',
status: 'new', status: 'new',
mailStatus: 'sent', mailStatus: 'sent',
@@ -38,7 +38,7 @@ function seed(): ContactMessageDetail[] {
receivedAt: '2026-11-08T10:00:00Z', receivedAt: '2026-11-08T10:00:00Z',
name: 'Marieke', name: 'Marieke',
email: 'marieke@example.nl', email: 'marieke@example.nl',
subject: 'onderhoud', subject: 'Onderhoudspakket',
message: 'Hallo', message: 'Hallo',
status: 'read', status: 'read',
mailStatus: 'failed', mailStatus: 'failed',
@@ -52,7 +52,7 @@ function seed(): ContactMessageDetail[] {
receivedAt: '2026-11-07T10:00:00Z', receivedAt: '2026-11-07T10:00:00Z',
name: 'Bot', name: 'Bot',
email: 'bot@example.nl', email: 'bot@example.nl',
subject: 'website', subject: 'Overig',
message: 'buy', message: 'buy',
status: 'spam', status: 'spam',
mailStatus: 'notApplicable', mailStatus: 'notApplicable',
@@ -113,6 +113,39 @@ describe('Form switch', () => {
); );
}); });
it('is a real switch: named, stateful, 44px, with the state as text, usable by keyboard', async () => {
await openPage();
const toggle = await screen.findByRole('switch', { name: 'Contact form on the website' });
expect(toggle).toHaveAttribute('aria-checked', 'false');
expect(toggle).toHaveTextContent('Off');
expect(toggle.className).toContain('min-h-11');
expect(toggle.className).toContain('min-w-11');
toggle.focus();
await userEvent.keyboard(' ');
await waitFor(() => expect(toggle).toHaveAttribute('aria-checked', 'true'));
expect(toggle).toHaveTextContent('On');
await userEvent.keyboard('{Enter}');
await waitFor(() => expect(toggle).toHaveAttribute('aria-checked', 'false'));
});
it('is disabled while saving', async () => {
await openPage();
server.use(
http.put(`${API_BASE}/api/v1/contact-settings`, async () => {
await new Promise((r) => setTimeout(r, 300));
return HttpResponse.json({ enabled: true, hostEnabled: true });
}),
);
const toggle = await screen.findByTestId('contact-switch-toggle');
await userEvent.click(toggle);
expect(toggle).toBeDisabled();
await waitFor(() => expect(toggle).not.toBeDisabled());
});
it('shows a translated error and keeps the state when the switch fails', async () => { it('shows a translated error and keeps the state when the switch fails', async () => {
await openPage(); await openPage();
server.use( server.use(
@@ -304,19 +337,59 @@ describe('Message detail', () => {
expect(getMockContactMessages().find((m) => m.id === MSG_READ)?.status).toBe('read'); expect(getMockContactMessages().find((m) => m.id === MSG_READ)?.status).toBe('read');
}); });
it('changes the status through the select', async () => { it('has no status select; the status is an icon with its name as text', async () => {
await openPage(); await openPage();
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_READ}`)); await userEvent.click(await screen.findByTestId(`contact-open-${MSG_READ}`));
await userEvent.selectOptions(
await screen.findByTestId('contact-status-select'),
'archived',
);
const dialog = await screen.findByTestId('contact-message-dialog');
expect(within(dialog).queryByTestId('contact-status-select')).not.toBeInTheDocument();
expect(within(dialog).queryByRole('combobox')).not.toBeInTheDocument();
const icon = within(dialog).getByTestId('status-icon-read');
expect(icon).toHaveTextContent('Read');
expect(icon).toHaveAttribute('title', 'Read');
expect(icon.querySelector('svg')).toHaveAttribute('aria-hidden', 'true');
});
it('archives a message and restores it to read', async () => {
await openPage();
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_READ}`));
await userEvent.click(await screen.findByTestId('contact-archive-button'));
await waitFor(() => await waitFor(() =>
expect(getMockContactMessages().find((m) => m.id === MSG_READ)?.status).toBe( expect(getMockContactMessages().find((m) => m.id === MSG_READ)?.status).toBe(
'archived', 'archived',
), ),
); );
expect(
await within(screen.getByTestId('contact-message-dialog')).findByTestId(
'status-icon-archived',
),
).toHaveTextContent('Archived');
expect(screen.queryByTestId('contact-archive-button')).not.toBeInTheDocument();
await userEvent.click(await screen.findByTestId('contact-restore-button'));
await waitFor(() =>
expect(getMockContactMessages().find((m) => m.id === MSG_READ)?.status).toBe('read'),
);
expect(await screen.findByTestId('contact-archive-button')).toBeInTheDocument();
});
it('shows the same status icon and name in the list', async () => {
await openPage();
const readRow = await screen.findByTestId(`contact-row-${MSG_READ}`);
const newRow = screen.getByTestId(`contact-row-${MSG_NEW}`);
expect(within(readRow).getByTestId('status-icon-read')).toHaveTextContent('Read');
expect(within(newRow).getByTestId('status-icon-new')).toHaveTextContent('New');
await userEvent.click(screen.getByTestId('contact-filter-spam'));
expect(await screen.findByTestId('status-icon-spam')).toHaveTextContent('Spam');
});
it('shows the subject exactly as the site sent it, capitals included', async () => {
await openPage();
const row = await screen.findByTestId(`contact-row-${MSG_NEW}`);
expect(row).toHaveTextContent('Website');
expect(row).not.toHaveTextContent('website'); // case-sensitive: no lower-case slug
}); });
it('shows the translated mail error and the next attempt, never the raw code', async () => { it('shows the translated mail error and the next attempt, never the raw code', async () => {
@@ -423,6 +423,8 @@
"title": "Contact form on the website", "title": "Contact form on the website",
"stateOn": "The form is on: visitors can send you a message.", "stateOn": "The form is on: visitors can send you a message.",
"stateOff": "The form is off: visitors only see your e-mail address.", "stateOff": "The form is off: visitors only see your e-mail address.",
"on": "On",
"off": "Off",
"turnOn": "Turn on", "turnOn": "Turn on",
"turnOff": "Turn off", "turnOff": "Turn off",
"nowOn": "The contact form is now on.", "nowOn": "The contact form is now on.",
@@ -479,6 +481,8 @@
"nextAttempt": "Next attempt: {{time}}", "nextAttempt": "Next attempt: {{time}}",
"delete": "Delete", "delete": "Delete",
"resend": "Send mail again", "resend": "Send mail again",
"archive": "Archive",
"restore": "Restore",
"notSpam": "Not spam" "notSpam": "Not spam"
}, },
"resend": { "resend": {
@@ -423,6 +423,8 @@
"title": "Contactformulier op de website", "title": "Contactformulier op de website",
"stateOn": "Het formulier staat aan: bezoekers kunnen je een bericht sturen.", "stateOn": "Het formulier staat aan: bezoekers kunnen je een bericht sturen.",
"stateOff": "Het formulier staat uit: bezoekers zien alleen je e-mailadres.", "stateOff": "Het formulier staat uit: bezoekers zien alleen je e-mailadres.",
"on": "Aan",
"off": "Uit",
"turnOn": "Aanzetten", "turnOn": "Aanzetten",
"turnOff": "Uitzetten", "turnOff": "Uitzetten",
"nowOn": "Het contactformulier staat nu aan.", "nowOn": "Het contactformulier staat nu aan.",
@@ -479,6 +481,8 @@
"nextAttempt": "Volgende poging: {{time}}", "nextAttempt": "Volgende poging: {{time}}",
"delete": "Verwijderen", "delete": "Verwijderen",
"resend": "Opnieuw mailen", "resend": "Opnieuw mailen",
"archive": "Archiveren",
"restore": "Terugzetten",
"notSpam": "Geen spam" "notSpam": "Geen spam"
}, },
"resend": { "resend": {