Media: eis ML-17 (kiezen of uploaden) in requirements, ontwerp en aannamelijst; pure ImagePicker-component
Continuous Integration / config-sls (pull_request) Successful in 9s
Continuous Integration / config-asf (pull_request) Successful in 5s
Continuous Integration / changes (pull_request) Canceled after 2m2s
Continuous Integration / backend-build (pull_request) Canceled after 0s
Continuous Integration / compile-sites (pull_request) Canceled after 0s
Continuous Integration / backend-test (pull_request) Canceled after 0s
Continuous Integration / vulnerability-scan (pull_request) Canceled after 0s
Continuous Integration / frontend-prepare (pull_request) Canceled after 0s
Continuous Integration / frontend-build (pull_request) Canceled after 0s
Continuous Integration / frontend-test (pull_request) Canceled after 0s
Continuous Integration / frontend-lint (pull_request) Canceled after 0s
Continuous Integration / publish-sls-test (pull_request) Canceled after 0s
Continuous Integration / publish-sls-production (pull_request) Canceled after 0s
Continuous Integration / deploy-sls-test (pull_request) Canceled after 0s
Continuous Integration / deploy-sls-production (pull_request) Canceled after 0s
Continuous Integration / publish-asf-test (pull_request) Canceled after 0s
Continuous Integration / deploy-asf-test (pull_request) Canceled after 0s
Continuous Integration / smoke-sls-test (pull_request) Canceled after 0s
Continuous Integration / smoke-asf-test (pull_request) Canceled after 0s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 14:24:53 +01:00
co-authored by Claude Sonnet 5.5
parent 1e89d8f3d7
commit 58f1878604
8 changed files with 278 additions and 2 deletions
@@ -0,0 +1,90 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useState } from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import i18n from '@/i18n/config';
import { validateUpload } from '../lib/validateUpload';
import { ImagePicker } from './ImagePicker';
import type { PhotoItem } from './PhotoSelectionList';
const photo = (id: string, name: string): PhotoItem => ({ id, name, bytes: 1, createdAt: '2026-11-17T10:00:00Z', uses: [], thumbnailUrl: null });
const items = [photo('a', 'Foto A'), photo('b', 'Foto B')];
const MB = 1024 * 1024;
function Harness({ onUpload, initial = null }: { onUpload?: (file: File) => Promise<PhotoItem>; initial?: string | null }) {
const [value, setValue] = useState<string | null>(initial);
return <ImagePicker items={items} value={value} onChange={setValue} onUpload={onUpload} maxUploadBytes={10 * MB} label="Afbeelding van slide 1" limitsText="JPEG, PNG, WebP, AVIF" />;
}
const file = (name = 'x.jpg', type = 'image/jpeg', size = 1000) => new File([new Uint8Array(size)], name, { type });
beforeEach(async () => {
await i18n.changeLanguage('nl');
});
describe('validateUpload', () => {
it.each([
[{ type: 'image/jpeg', size: 100 }, null],
[{ type: '', size: 100 }, null],
[{ type: 'application/pdf', size: 100 }, 'notAnImage'],
[{ type: 'image/png', size: 10 * MB + 1 }, 'tooLarge'],
[{ type: 'image/png', size: 10 * MB }, null],
])('%j gives %s', (f, expected) => expect(validateUpload(f, 10 * MB)).toBe(expected));
});
describe('ImagePicker', () => {
it('chooses a library photo as a radio group, with the arrow keys', async () => {
render(<Harness initial="a" />);
expect(screen.getByRole('radiogroup', { name: 'Afbeelding van slide 1' })).toBeInTheDocument();
expect(screen.getByRole('radio', { name: 'Foto A' })).toBeChecked();
screen.getByRole('radio', { name: 'Foto A' }).focus();
await userEvent.keyboard('{ArrowRight}');
expect(screen.getByRole('radio', { name: 'Foto B' })).toBeChecked();
});
it('has no upload button when the module gives no upload', () => {
render(<Harness />);
expect(screen.queryByTestId('picker-upload-button')).not.toBeInTheDocument();
});
it('uploads on the spot, then chooses the new photo', async () => {
const upload = vi.fn().mockResolvedValue(photo('c', 'Nieuwe foto'));
render(<Harness onUpload={upload} />);
await userEvent.upload(screen.getByTestId('picker-file'), file());
await waitFor(() => expect(upload).toHaveBeenCalledTimes(1));
await waitFor(() => expect(screen.getByTestId('picker-upload-button')).toHaveTextContent('Afbeelding uploaden'));
expect(screen.queryByTestId('picker-problem')).not.toBeInTheDocument();
});
it('refuses what the host would refuse, without calling the upload', async () => {
const upload = vi.fn();
render(<Harness onUpload={upload} />);
await userEvent.upload(screen.getByTestId('picker-file'), file('x.pdf', 'application/pdf'), { applyAccept: false });
expect(screen.getByTestId('picker-problem')).toHaveTextContent('geen afbeelding');
await userEvent.upload(screen.getByTestId('picker-file'), file('big.jpg', 'image/jpeg', 10 * MB + 1));
expect(screen.getByTestId('picker-problem')).toHaveTextContent('maximaal 10 MB');
expect(upload).not.toHaveBeenCalled();
});
it('shows a message when the upload fails and keeps the current choice', async () => {
render(<Harness onUpload={() => Promise.reject(new Error('nope'))} initial="b" />);
await userEvent.upload(screen.getByTestId('picker-file'), file());
expect(await screen.findByTestId('picker-problem')).toHaveTextContent('niet gelukt');
expect(screen.getByRole('radio', { name: 'Foto B' })).toBeChecked();
});
it('says so when the library is empty', () => {
render(<ImagePicker items={[]} value={null} onChange={vi.fn()} maxUploadBytes={MB} label="x" />);
expect(screen.getByTestId('picker-empty')).toHaveTextContent('nog geen foto');
});
});
@@ -0,0 +1,123 @@
import { useId, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ImagePlus } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { validateUpload } from '../lib/validateUpload';
import type { PhotoItem } from './PhotoSelectionList';
interface ImagePickerProps {
/** The photos of the library to choose from, newest first. */
items: readonly PhotoItem[];
/** The id of the chosen photo, or null. */
value: string | null;
onChange: (id: string) => void;
/**
* Uploads one file and answers with the photo as the library lists it. The module decides how (the hero uses its own
* upload and background processing); the picker only shows the state and chooses the result. Without it there is no
* upload button.
*/
onUpload?: (file: File) => Promise<PhotoItem>;
/** The largest file the host accepts, in bytes. */
maxUploadBytes: number;
/** A short line about formats and limits, shown under the buttons. */
limitsText?: string;
/** Accessible name of the group (what the image is for, for example "Image of slide 2"). */
label: string;
}
/**
* "Choose an image or upload one": the photos of the library as a group of radio buttons (arrow keys move and choose)
* and an upload button that adds the new photo to the library and chooses it at once. One component for every module that
* needs an image. It holds no data of its own and calls nothing by itself: the module passes the list and the upload.
*/
export function ImagePicker({ items, value, onChange, onUpload, maxUploadBytes, limitsText, label }: ImagePickerProps) {
const { t } = useTranslation();
const groupName = useId();
const fileInput = useRef<HTMLInputElement>(null);
const [uploading, setUploading] = useState(false);
const [problem, setProblem] = useState<string | null>(null);
const upload = async (file: File | undefined) => {
if (!file || !onUpload || uploading) return;
const refused = validateUpload(file, maxUploadBytes);
if (refused) {
setProblem(refused === 'tooLarge' ? t('media.picker.tooLarge', { max: Math.round(maxUploadBytes / (1024 * 1024)) }) : t('media.picker.notAnImage'));
return;
}
setProblem(null);
setUploading(true);
try {
const photo = await onUpload(file);
onChange(photo.id);
} catch {
setProblem(t('media.picker.failed'));
} finally {
setUploading(false);
if (fileInput.current) fileInput.current.value = '';
}
};
return (
<div className="space-y-3" data-testid="image-picker">
{onUpload && (
<div className="flex flex-wrap items-center gap-3">
<input
ref={fileInput}
type="file"
accept="image/*"
className="sr-only"
aria-label={t('media.picker.upload')}
data-testid="picker-file"
onChange={(event) => void upload(event.target.files?.[0])}
/>
<Button type="button" variant="outline" disabled={uploading} onClick={() => fileInput.current?.click()} data-testid="picker-upload-button">
<ImagePlus className="mr-2 size-4" aria-hidden="true" />
{uploading ? t('media.picker.uploading') : t('media.picker.upload')}
</Button>
{limitsText && <p className="text-xs text-muted-foreground">{limitsText}</p>}
</div>
)}
{problem && (
<p role="alert" className="text-sm text-destructive" data-testid="picker-problem">
{problem}
</p>
)}
{items.length === 0 ? (
<p className="rounded-md border border-dashed p-4 text-sm text-muted-foreground" data-testid="picker-empty">
{t('media.picker.empty')}
</p>
) : (
<div role="radiogroup" aria-label={label} className="grid grid-cols-2 gap-3 sm:grid-cols-4" data-testid="picker-grid">
{items.map((item) => (
<label key={item.id} className="relative block cursor-pointer" data-testid={`picker-item-${item.id}`}>
<input
type="radio"
name={groupName}
value={item.id}
checked={value === item.id}
onChange={() => onChange(item.id)}
aria-label={item.name}
className="peer sr-only"
/>
<span
className={cn(
'block overflow-hidden rounded-md border-2 border-transparent bg-muted transition-colors',
'peer-checked:border-primary peer-focus-visible:ring-2 peer-focus-visible:ring-ring peer-focus-visible:ring-offset-2 ring-offset-background',
'hover:border-muted-foreground forced-colors:peer-checked:border-[Highlight]',
)}
>
{item.thumbnailUrl ? (
<img src={item.thumbnailUrl} alt="" loading="lazy" className="aspect-[3/2] w-full object-cover" />
) : (
<span className="flex aspect-[3/2] items-center justify-center text-xs text-muted-foreground">{t('media.list.noThumbnail')}</span>
)}
</span>
<span className="mt-1 block truncate text-xs">{item.name}</span>
</label>
))}
</div>
)}
</div>
);
}
@@ -0,0 +1,11 @@
export type UploadProblem = 'notAnImage' | 'tooLarge';
/**
* The quick checks before a file is sent (the same two the hero upload makes): it must be an image and not over the
* limit. The host checks everything again (signature, pixels, rate); this only spares sending a file it will refuse.
*/
export function validateUpload(file: { type: string; size: number }, maxBytes: number): UploadProblem | null {
if (file.type !== '' && !file.type.startsWith('image/')) return 'notAnImage';
if (file.size > maxBytes) return 'tooLarge';
return null;
}
@@ -829,6 +829,14 @@
"summary_one": "{{count}} photo ({{size}}) qualifies.",
"summary_other": "{{count}} photos ({{size}}) qualify.",
"selectedSize": "Selected: {{size}}"
},
"picker": {
"upload": "Upload an image",
"uploading": "Uploading...",
"empty": "There are no photos in the library yet. Upload one.",
"notAnImage": "This file is not an image.",
"tooLarge": "This file is too large (at most {{max}} MB).",
"failed": "Uploading failed. Try again."
}
}
}
@@ -829,6 +829,14 @@
"summary_one": "{{count}} foto ({{size}}) komt in aanmerking.",
"summary_other": "{{count}} foto's ({{size}}) komen in aanmerking.",
"selectedSize": "Geselecteerd: {{size}}"
},
"picker": {
"upload": "Afbeelding uploaden",
"uploading": "Bezig met uploaden...",
"empty": "Er staan nog geen foto's in de bibliotheek. Upload er een.",
"notAnImage": "Dit bestand is geen afbeelding.",
"tooLarge": "Dit bestand is te groot (maximaal {{max}} MB).",
"failed": "Uploaden is niet gelukt. Probeer het opnieuw."
}
}
}