diff --git a/aidlc-docs/features/hero-module/aidlc-state.md b/aidlc-docs/features/hero-module/aidlc-state.md index 998ffcd..6e346f9 100644 --- a/aidlc-docs/features/hero-module/aidlc-state.md +++ b/aidlc-docs/features/hero-module/aidlc-state.md @@ -53,7 +53,7 @@ - [x] NFR Requirements (construction/nfr-requirements/) - [x] NFR Design (construction/nfr-design/) - [x] Infrastructure Design (media directory; construction/infrastructure-design/) -- [ ] Code Generation - per unit: H0, H1, H2, H3, H4 done; H5 (admin) and H6 (seed, docs, smoke) open +- [ ] Code Generation - per unit: H0 to H5 done; H6 (seed, docs, smoke, LCP measure) open - [ ] Build and Test - EXECUTE ### 🟡 OPERATIONS PHASE - [ ] SKIP (Q19 = B; points go into the joint production checklist) diff --git a/aidlc-docs/features/hero-module/construction/h5-admin/code/summary.md b/aidlc-docs/features/hero-module/construction/h5-admin/code/summary.md new file mode 100644 index 0000000..069207d --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/h5-admin/code/summary.md @@ -0,0 +1,20 @@ +# H5 Admin frontend: code summary + +Built 2026-11-16 on `feature/hero-module`. Frontend: 604 of 604 tests pass (73 new), `tsc` and `eslint` are clean. + +| Area | What | +|---|---| +| Navigation | route `/hero` (Owner and Administrator, module `Hero`), sidebar item "Hero", nl and en texts under `hero.*` | +| Screen | `features/hero/pages/HeroPage.tsx`: live or not-live badge (only a badge, Bryan, Q5), title (new line = line break, 5 lines), tagline, lead, display (single or slideshow), two buttons with label and target, schedule (on or off, from, until), slide list | +| Slides | upload (file picker, the server messages on refusal), alt text per slide or decorative, on or off, up and down, remove from the hero, a note when there are more slides than the publication ceiling; the number of slides has no limit in the screen | +| Focus | `FocusDialog`: the photo with a draggable and keyboard-movable focus point (arrow keys, Shift for bigger steps), numeric X and Y, a zoom slider, a general setting plus an optional own setting for the wide and the tall display with a reset, outlines of both crops on the photo and live previews of the two crops | +| Maths | `lib/focusMath.ts` is the twin of the host `FocusMath` (round half up); its tests use the same vectors as the C# tests plus a random check that the crop stays inside the image and holds the focus point | +| Validation | `schemas/hero.ts` (zod): title, tagline, lead, buttons (both or neither, target allow-list twin of the host validator, tested with the same cases), alt text unless decorative, schedule order; error texts are i18n keys in both languages | +| Client | `ApiClient` sends `FormData` as is (multipart upload) | +| Safety | unsaved changes trigger the browser warning when leaving | +| Tests | form, validation, navigation, saving, reorder, remove, switch off, decorative, upload and refused upload, ceiling note, focus dialog (stored values, keyboard, general plus own tall setting, reset, cancel), the shared maths vectors, the target validator cases | + +## Notes + +- Uploaded images that are never saved into a slide are removed by the host clean-up after 7 days; the screen has no separate delete for an image. +- Changing the focus of an image that is live changes the live hero at once (the images are shared by the hero), as the host re-cuts the variants. diff --git a/frontend/src/components/layout/Sidebar.tsx b/frontend/src/components/layout/Sidebar.tsx index f1680f3..539798e 100644 --- a/frontend/src/components/layout/Sidebar.tsx +++ b/frontend/src/components/layout/Sidebar.tsx @@ -1,6 +1,6 @@ import { Link } from '@tanstack/react-router'; import { useTranslation } from 'react-i18next'; -import { LayoutDashboard, Users, FileText, Package, Mail, Settings, X } from 'lucide-react'; +import { LayoutDashboard, Users, FileText, Package, Mail, Settings, X, Image as ImageIcon } from 'lucide-react'; import type { LucideIcon } from 'lucide-react'; import { cn } from '@/lib/utils'; import { useAuth } from '@/features/auth/context/auth-context'; @@ -29,6 +29,14 @@ const NAV_ITEMS: NavItem[] = [ { to: '/dashboard', labelKey: 'nav.dashboard', icon: LayoutDashboard, testId: 'nav-dashboard' }, { to: '/users', labelKey: 'nav.users', icon: Users, testId: 'nav-users', roles: ['Owner', 'Administrator'] }, { to: '/cms', labelKey: 'nav.cms', icon: FileText, testId: 'nav-cms', roles: ['Owner'], requiredModule: 'Master' }, + { + to: '/hero', + labelKey: 'nav.hero', + icon: ImageIcon, + testId: 'nav-hero', + roles: ['Owner', 'Administrator'], + requiredModule: 'Hero', + }, { to: '/offerings', labelKey: 'nav.offerings', diff --git a/frontend/src/features/hero/components/FocusDialog.tsx b/frontend/src/features/hero/components/FocusDialog.tsx new file mode 100644 index 0000000..af20cff --- /dev/null +++ b/frontend/src/features/hero/components/FocusDialog.tsx @@ -0,0 +1,253 @@ +import { useRef, useState, type KeyboardEvent, type PointerEvent } from 'react'; +import { useTranslation } from 'react-i18next'; +import { toast } from 'sonner'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { FormErrorBanner } from '@/components/ui/FormErrorBanner'; +import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; +import { mediaUrl } from '../lib/media'; +import { CENTRE, MAX_ZOOM, TALL, WIDE, cropFor, normalizeFocus, type Ratio } from '../lib/focusMath'; +import { useSetImageFocus } from '../services/hooks'; +import type { FocusDto, HeroImageDto } from '../services/types'; + +type Target = 'general' | 'wide' | 'tall'; + +interface FocusDialogProps { + /** The image to edit; null = closed. */ + image: HeroImageDto | null; + onClose: () => void; +} + +export function FocusDialog({ image, onClose }: FocusDialogProps) { + const { t } = useTranslation(); + return ( + { if (!next) onClose(); }}> + + + {t('hero.focus.title')} + + {/* Mounted only while open, so every opening starts from the stored values. */} + {image && } + + + ); +} + +const percent = (fraction: number) => Math.round(fraction * 1000) / 10; + +function FocusEditor({ image, onClose }: { image: HeroImageDto; onClose: () => void }) { + const { t } = useTranslation(); + const save = useSetImageFocus(); + const area = useRef(null); + const [serverError, setServerError] = useState(null); + const [target, setTarget] = useState('general'); + const [general, setGeneral] = useState(image.focus ?? CENTRE); + const [wide, setWide] = useState(image.wideFocus); + const [tall, setTall] = useState(image.tallFocus); + + const effective = { wide: wide ?? general, tall: tall ?? general }; + const active: FocusDto = target === 'general' ? general : (target === 'wide' ? wide : tall) ?? general; + const editable = target === 'general' || (target === 'wide' ? wide : tall) !== null; + + const update = (next: FocusDto) => { + const clean = normalizeFocus(next); + if (target === 'general') setGeneral(clean); + else if (target === 'wide') setWide(clean); + else setTall(clean); + }; + + const toggleOverride = (checked: boolean) => { + const value = checked ? { ...general } : null; + if (target === 'wide') setWide(value); + if (target === 'tall') setTall(value); + }; + + const moveTo = (event: PointerEvent) => { + const box = area.current?.getBoundingClientRect(); + if (!box || box.width === 0 || box.height === 0 || !editable) return; + update({ ...active, x: (event.clientX - box.left) / box.width, y: (event.clientY - box.top) / box.height }); + }; + + const onKeyDown = (event: KeyboardEvent) => { + if (!editable) return; + const step = event.shiftKey ? 0.05 : 0.01; + const moves: Record = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }; + const move = moves[event.key]; + if (!move) return; + event.preventDefault(); + update({ ...active, x: active.x + move[0], y: active.y + move[1] }); + }; + + const onSave = async () => { + setServerError(null); + try { + await save.mutateAsync({ imageId: image.id, body: { focus: general, wide, tall } }); + toast.success(t('hero.focus.savedToast')); + onClose(); + } catch (error) { + const message = (error as { problem?: { message?: unknown } }).problem?.message; + setServerError(typeof message === 'string' ? message : t('errors.generic')); + } + }; + + const outline = (ratio: Ratio, focus: FocusDto) => { + const c = cropFor(image.width, image.height, ratio, focus); + return { + left: `${(c.x / image.width) * 100}%`, + top: `${(c.y / image.height) * 100}%`, + width: `${(c.width / image.width) * 100}%`, + height: `${(c.height / image.height) * 100}%`, + }; + }; + + return ( +
+ setServerError(null)} /> +

{t('hero.focus.intro')}

+ +
+ {t('hero.focus.targetLegend')} + {(['general', 'wide', 'tall'] as const).map((value) => ( + + ))} +
+ + {target !== 'general' && ( + + )} + +
+
+
{ + event.currentTarget.setPointerCapture?.(event.pointerId); + moveTo(event); + }} + onPointerMove={(event) => { + if (event.buttons === 1) moveTo(event); + }} + onKeyDown={onKeyDown} + data-testid="focus-area" + > + +
+
+
+
+

{t('hero.focus.areaHint')}

+
+ +
+
+
+ + update({ ...active, x: Number(event.target.value) / 100 })} + data-testid="focus-x" + /> +
+
+ + update({ ...active, y: Number(event.target.value) / 100 })} + data-testid="focus-y" + /> +
+
+
+ + update({ ...active, zoom: Number(event.target.value) })} + className="w-full" + data-testid="focus-zoom" + /> +
+ + {([WIDE, TALL] as const).map((ratio) => { + const crop = cropFor(image.width, image.height, ratio, effective[ratio.name]); + return ( +
+

{t(`hero.focus.preview.${ratio.name}`)}

+
+ +
+
+ ); + })} +
+
+ +
+ + +
+
+ ); +} diff --git a/frontend/src/features/hero/lib/focusMath.test.ts b/frontend/src/features/hero/lib/focusMath.test.ts new file mode 100644 index 0000000..39ba846 --- /dev/null +++ b/frontend/src/features/hero/lib/focusMath.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest'; +import { CENTRE, TALL, WIDE, cropFor, normalizeFocus, roundHalfUp } from './focusMath'; + +// The same vectors as src/SlpModularCms.Core.Tests/Media/MediaPureFunctionTests.cs (FocusMathTests.KnownVectors). +const vectors: [number, number, 'wide' | 'tall', number, number, number, [number, number, number, number]][] = [ + [1600, 1067, 'wide', 0.5, 0.5, 1.0, [0, 0, 1600, 1067]], + [1600, 1067, 'tall', 0.5, 0.5, 1.0, [374, 1, 853, 1066]], + [1600, 1067, 'tall', 0.0, 0.5, 1.0, [0, 1, 853, 1066]], + [1600, 1067, 'tall', 1.0, 0.5, 1.0, [747, 1, 853, 1066]], + [1600, 1067, 'wide', 0.45, 0.35, 2.0, [320, 107, 800, 533]], + [2560, 1702, 'tall', 0.55, 0.6, 1.0, [728, 1, 1361, 1701]], + [1000, 2000, 'wide', 0.5, 0.5, 1.0, [0, 667, 1000, 667]], +]; + +describe('cropFor', () => { + it.each(vectors)('%i x %i %s at (%d, %d) zoom %d', (w, h, ratio, x, y, zoom, [cx, cy, cw, ch]) => { + expect(cropFor(w, h, ratio === 'tall' ? TALL : WIDE, { x, y, zoom })).toEqual({ x: cx, y: cy, width: cw, height: ch }); + }); + + it('always stays inside the image and keeps the focus point inside the crop', () => { + for (let i = 0; i < 2000; i++) { + const w = 1 + Math.floor(Math.random() * 6000); + const h = 1 + Math.floor(Math.random() * 6000); + const focus = { x: Math.random(), y: Math.random(), zoom: 1 + Math.random() * 3 }; + for (const ratio of [WIDE, TALL]) { + const c = cropFor(w, h, ratio, focus); + expect(c.x).toBeGreaterThanOrEqual(0); + expect(c.y).toBeGreaterThanOrEqual(0); + expect(c.x + c.width).toBeLessThanOrEqual(w); + expect(c.y + c.height).toBeLessThanOrEqual(h); + expect(focus.x * w).toBeGreaterThanOrEqual(c.x - 1); + expect(focus.x * w).toBeLessThanOrEqual(c.x + c.width + 1); + expect(focus.y * h).toBeGreaterThanOrEqual(c.y - 1); + expect(focus.y * h).toBeLessThanOrEqual(c.y + c.height + 1); + } + } + }); + + it('survives values that are out of range or not numbers', () => { + const c = cropFor(1600, 1067, TALL, { x: Number.NaN, y: Infinity, zoom: -Infinity }); + expect(c.x).toBeGreaterThanOrEqual(0); + expect(c.x + c.width).toBeLessThanOrEqual(1600); + }); + + it('rejects an image without a size', () => { + expect(() => cropFor(0, 100, WIDE, CENTRE)).toThrow(RangeError); + }); +}); + +describe('normalizeFocus and roundHalfUp', () => { + it('clamps and defaults', () => { + expect(normalizeFocus({ x: -1, y: 2, zoom: 9 })).toEqual({ x: 0, y: 1, zoom: 4 }); + expect(normalizeFocus({ x: Number.NaN, y: Number.NaN, zoom: Number.NaN })).toEqual({ x: 0.5, y: 0.5, zoom: 1 }); + }); + + it('rounds .5 up like the host', () => { + expect(roundHalfUp(373.5)).toBe(374); + expect(roundHalfUp(0.5)).toBe(1); + expect(roundHalfUp(2.4)).toBe(2); + }); +}); diff --git a/frontend/src/features/hero/lib/focusMath.ts b/frontend/src/features/hero/lib/focusMath.ts new file mode 100644 index 0000000..ebe4d3f --- /dev/null +++ b/frontend/src/features/hero/lib/focusMath.ts @@ -0,0 +1,65 @@ +import type { FocusDto } from '../services/types'; + +/** A named aspect ratio (width:height). The same two as the host cuts. */ +export interface Ratio { + name: 'wide' | 'tall'; + numerator: number; + denominator: number; +} + +export const WIDE: Ratio = { name: 'wide', numerator: 3, denominator: 2 }; +export const TALL: Ratio = { name: 'tall', numerator: 4, denominator: 5 }; + +export const MAX_ZOOM = 4; +export const CENTRE: FocusDto = { x: 0.5, y: 0.5, zoom: 1 }; + +export interface CropRect { + x: number; + y: number; + width: number; + height: number; +} + +/** Rounds .5 up, like the host (C# FocusMath.RoundHalfUp), so the preview is the same crop as the stored file. */ +export const roundHalfUp = (value: number): number => Math.floor(value + 0.5); + +const clamp = (value: number, min: number, max: number): number => Math.min(Math.max(value, min), max); + +/** Clamps every value into its valid range; anything that is not a number becomes the default. */ +export function normalizeFocus(focus: FocusDto): FocusDto { + const finite = (v: number, fallback: number) => (Number.isNaN(v) ? fallback : v); + return { + x: clamp(finite(focus.x, 0.5), 0, 1), + y: clamp(finite(focus.y, 0.5), 0, 1), + zoom: clamp(finite(focus.zoom, 1), 1, MAX_ZOOM), + }; +} + +/** + * The crop for a ratio around a focus point: the largest rectangle of the ratio that fits the image, shrunk by the + * zoom, centred on the point and moved the smallest amount needed to stay inside. Twin of the host's C# `FocusMath`; + * `focusMath.test.ts` and the C# tests share their vectors. + */ +export function cropFor(imageWidth: number, imageHeight: number, ratio: Ratio, focus: FocusDto): CropRect { + if (imageWidth <= 0 || imageHeight <= 0) { + throw new RangeError('The image must have a size.'); + } + + const f = normalizeFocus(focus); + // The largest crop of the ratio inside the image: as wide as the image, or as high as the image. + const cw0 = + imageWidth * ratio.denominator > imageHeight * ratio.numerator + ? (imageHeight * ratio.numerator) / ratio.denominator + : imageWidth; + + let cw = clamp(Math.floor(cw0 / f.zoom), 1, imageWidth); + let ch = Math.max(1, roundHalfUp((cw * ratio.denominator) / ratio.numerator)); + if (ch > imageHeight) { + ch = imageHeight; + cw = clamp(Math.floor((ch * ratio.numerator) / ratio.denominator), 1, imageWidth); + } + + const x = clamp(roundHalfUp(f.x * imageWidth - cw / 2), 0, imageWidth - cw); + const y = clamp(roundHalfUp(f.y * imageHeight - ch / 2), 0, imageHeight - ch); + return { x, y, width: cw, height: ch }; +} diff --git a/frontend/src/features/hero/lib/media.ts b/frontend/src/features/hero/lib/media.ts new file mode 100644 index 0000000..8d772e7 --- /dev/null +++ b/frontend/src/features/hero/lib/media.ts @@ -0,0 +1,4 @@ +import { getAppConfig } from '@/lib/config'; + +/** A media address of the host (/media/...) as the browser must request it from the admin. */ +export const mediaUrl = (path: string): string => `${getAppConfig().apiBaseUrl.replace(/\/$/, '')}${path}`; diff --git a/frontend/src/features/hero/mocks/handlers.ts b/frontend/src/features/hero/mocks/handlers.ts new file mode 100644 index 0000000..daf5a60 --- /dev/null +++ b/frontend/src/features/hero/mocks/handlers.ts @@ -0,0 +1,126 @@ +import { http, HttpResponse } from 'msw'; +import { API_BASE } from '@/features/auth/mocks/fixtures'; +import type { FocusDto, HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest, HeroSlideAdminDto } from '@/features/hero/services/types'; + +const seedImage = (id: string, width = 1600, height = 1067): HeroImageDto => ({ + id, + width, + height, + focus: { x: 0.5, y: 0.5, zoom: 1 }, + wideFocus: null, + tallFocus: null, + src: `/media/hero/0123456789abcdef/wide-${width}.webp`, + variants: [ + { ratio: 'wide', width: 960, height: 640, type: 'image/webp', url: '/media/hero/0123456789abcdef/wide-960.webp' }, + { ratio: 'wide', width, height, type: 'image/webp', url: `/media/hero/0123456789abcdef/wide-${width}.webp` }, + { ratio: 'tall', width: 640, height: 800, type: 'image/webp', url: '/media/hero/0123456789abcdef/tall-640.webp' }, + ], +}); + +export const emptyHero = (): HeroAdminDto => ({ + id: null, + title: '', + tagline: null, + lead: null, + display: 'single', + buttons: [], + isActive: true, + startsAt: null, + endsAt: null, + slides: [], + isLive: false, + updatedAt: null, + maxPublishedSlides: 50, +}); + +export const slide = (index: number, over: Partial = {}): HeroSlideAdminDto => ({ + id: `00000000-0000-0000-0000-00000000000${index}`, + imageId: `10000000-0000-0000-0000-00000000000${index}`, + alt: `Foto ${index}`, + decorative: false, + isActive: true, + sortOrder: index - 1, + image: seedImage(`10000000-0000-0000-0000-00000000000${index}`), + ...over, +}); + +let hero: HeroAdminDto = emptyHero(); +let images: Record = {}; +let saved: HeroSaveRequest[] = []; +let uploads = 0; +let uploadFailure: { status: number; error: string; message: string } | null = null; + +export const resetMockHero = (): void => { + hero = emptyHero(); + images = {}; + saved = []; + uploads = 0; + uploadFailure = null; +}; + +export const setMockHero = (next: HeroAdminDto): void => { + hero = next; + images = Object.fromEntries(next.slides.map((s) => [s.imageId, s.image])); +}; + +export const getSavedHeroRequests = (): HeroSaveRequest[] => saved; + +export const failNextUpload = (failure: { status: number; error: string; message: string } | null): void => { + uploadFailure = failure; +}; + +export const heroHandlers = [ + http.get(`${API_BASE}/api/v1/hero/all`, () => HttpResponse.json(hero)), + + http.put(`${API_BASE}/api/v1/hero`, async ({ request }) => { + const body = (await request.json()) as HeroSaveRequest; + saved.push(body); + hero = { + ...hero, + id: hero.id ?? '99999999-9999-9999-9999-999999999999', + title: body.title, + tagline: body.tagline, + lead: body.lead, + display: body.display, + buttons: body.buttons, + isActive: body.isActive, + startsAt: body.startsAt, + endsAt: body.endsAt, + isLive: body.isActive && body.title.trim() !== '', + updatedAt: '2026-11-16T12:00:00Z', + slides: body.slides.map((s, i) => ({ + id: s.id ?? `20000000-0000-0000-0000-00000000000${i}`, + imageId: s.imageId, + alt: s.alt ?? '', + decorative: s.decorative, + isActive: s.isActive, + sortOrder: i, + image: images[s.imageId] ?? seedImage(s.imageId), + })), + }; + return HttpResponse.json(hero); + }), + + http.post(`${API_BASE}/api/v1/hero/images`, () => { + if (uploadFailure) { + const { status, error, message } = uploadFailure; + uploadFailure = null; + return HttpResponse.json({ error, message }, { status }); + } + uploads += 1; + const image = seedImage(`30000000-0000-0000-0000-00000000000${uploads}`); + images[image.id] = image; + return HttpResponse.json(image, { status: 201 }); + }), + + http.put(`${API_BASE}/api/v1/hero/images/:id/focus`, async ({ params, request }) => { + const body = (await request.json()) as HeroFocusRequest; + const id = String(params.id); + const current = images[id] ?? hero.slides.find((s) => s.imageId === id)?.image ?? seedImage(id); + const asDto = (f: FocusDto | null) => (f ? { ...f } : null); + const next: HeroImageDto = { ...current, focus: body.focus, wideFocus: asDto(body.wide), tallFocus: asDto(body.tall) }; + images[id] = next; + hero = { ...hero, slides: hero.slides.map((s) => (s.imageId === id ? { ...s, image: next } : s)) }; + return HttpResponse.json(next); + }), +]; diff --git a/frontend/src/features/hero/pages/HeroPage.test.tsx b/frontend/src/features/hero/pages/HeroPage.test.tsx new file mode 100644 index 0000000..7848137 --- /dev/null +++ b/frontend/src/features/hero/pages/HeroPage.test.tsx @@ -0,0 +1,273 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { fireEvent, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { renderApp, mockAuthenticated } from '@/test/utils'; +import { emptyHero, failNextUpload, getSavedHeroRequests, resetMockHero, setMockHero, slide } from '@/features/hero/mocks/handlers'; +import { _resetSetupStatusCache } from '@/router'; + +const T = { timeout: 10000 }; + +beforeEach(() => { + _resetSetupStatusCache(); + resetMockHero(); +}); + +async function openPage() { + mockAuthenticated(); + renderApp('/hero'); + return screen.findByTestId('hero-form', {}, T); +} + +describe('Hero page', () => { + it('shows an empty form and the not-live badge when there is no hero yet', async () => { + await openPage(); + + expect(screen.getByTestId('hero-live-badge')).toHaveTextContent(/Niet live|Not live/); + expect(screen.getByTestId('hero-slides-empty')).toBeInTheDocument(); + expect(screen.getByTestId('hero-title-input')).toHaveValue(''); + expect(screen.getByTestId('hero-display-single')).toBeChecked(); + }); + + it('is reachable from the navigation for an administrator', async () => { + mockAuthenticated(); + renderApp('/dashboard'); + + await userEvent.click(await screen.findByTestId('nav-hero', {}, T)); + + expect(await screen.findByTestId('hero-form', {}, T)).toBeInTheDocument(); + }); + + it('saves the texts, the buttons and the schedule, and shows the hero as live', async () => { + await openPage(); + + await userEvent.type(screen.getByTestId('hero-title-input'), 'Websites,{enter}apps{enter}& meer.'); + await userEvent.type(screen.getByTestId('hero-lead'), 'Een lead.'); + await userEvent.click(screen.getByTestId('hero-display-slideshow')); + await userEvent.type(screen.getByTestId('hero-button-0-label'), 'Bekijk pakketten'); + await userEvent.type(screen.getByTestId('hero-button-0-target'), '#pakketten'); + await userEvent.type(screen.getByTestId('hero-button-1-label'), 'Plan een gesprek'); + await userEvent.type(screen.getByTestId('hero-button-1-target'), '#contact'); + await userEvent.click(screen.getByTestId('hero-save')); + + await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1)); + expect(getSavedHeroRequests()[0]).toMatchObject({ + title: 'Websites,\napps\n& meer.', + tagline: null, + lead: 'Een lead.', + display: 'slideshow', + buttons: [ + { label: 'Bekijk pakketten', target: '#pakketten' }, + { label: 'Plan een gesprek', target: '#contact' }, + ], + isActive: true, + startsAt: null, + endsAt: null, + slides: [], + }); + }); + + it('does not save without a title and says why', async () => { + await openPage(); + + await userEvent.click(screen.getByTestId('hero-save')); + + expect(await screen.findByTestId('hero-title-error')).toHaveTextContent(/Een titel is verplicht\.|A title is required\./); + expect(getSavedHeroRequests()).toHaveLength(0); + }); + + it.each([ + ['javascript:alert(1)', 'hero-button-0-target-error', /Kies een #anker|Choose an #anchor/], + ['//evil.example', 'hero-button-0-target-error', /Kies een #anker|Choose an #anchor/], + ['http://example.com', 'hero-button-0-target-error', /Kies een #anker|Choose an #anchor/], + ])('rejects the button target %s', async (target, errorId, message) => { + await openPage(); + await userEvent.type(screen.getByTestId('hero-title-input'), 'Titel'); + await userEvent.type(screen.getByTestId('hero-button-0-label'), 'Knop'); + await userEvent.type(screen.getByTestId('hero-button-0-target'), target); + + await userEvent.click(screen.getByTestId('hero-save')); + + expect(await screen.findByTestId(errorId)).toHaveTextContent(message); + expect(getSavedHeroRequests()).toHaveLength(0); + }); + + it('wants a button text and a target together', async () => { + await openPage(); + await userEvent.type(screen.getByTestId('hero-title-input'), 'Titel'); + await userEvent.type(screen.getByTestId('hero-button-1-label'), 'Alleen een tekst'); + + await userEvent.click(screen.getByTestId('hero-save')); + + expect(await screen.findByTestId('hero-button-1-target-error')).toHaveTextContent(/Vul zowel de tekst als het doel|Fill in both the text and the target/); + }); + + it('wants the end after the start', async () => { + await openPage(); + await userEvent.type(screen.getByTestId('hero-title-input'), 'Titel'); + fireEvent.change(screen.getByTestId('hero-starts'), { target: { value: '2026-12-10T10:00' } }); + fireEvent.change(screen.getByTestId('hero-ends'), { target: { value: '2026-12-01T10:00' } }); + + await userEvent.click(screen.getByTestId('hero-save')); + + expect(await screen.findByTestId('hero-ends-error')).toHaveTextContent(/Het einde moet na het begin liggen\.|The end must be after the start\./); + }); +}); + +describe('Slides', () => { + const withTwoSlides = () => + setMockHero({ ...emptyHero(), id: 'h1', title: 'Andrea Slop', isLive: true, updatedAt: '2026-11-16T12:00:00Z', slides: [slide(1), slide(2)] }); + + it('lists the saved slides with their description, and the live badge', async () => { + withTwoSlides(); + + await openPage(); + + expect(screen.getByTestId('hero-live-badge')).toHaveTextContent(/^(Live)$/); + expect(screen.getByTestId('hero-slide-0-alt')).toHaveValue('Foto 1'); + expect(screen.getByTestId('hero-slide-1-alt')).toHaveValue('Foto 2'); + }); + + it('reorders slides and saves the new order with the slide ids', async () => { + withTwoSlides(); + await openPage(); + + await userEvent.click(screen.getByTestId('hero-slide-1-up')); + await userEvent.click(screen.getByTestId('hero-save')); + + await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1)); + const { slides } = getSavedHeroRequests()[0]; + expect(slides.map((s) => s.alt)).toEqual(['Foto 2', 'Foto 1']); + expect(slides[0].id).toBe('00000000-0000-0000-0000-000000000002'); + }); + + it('cannot move the first slide up or the last one down', async () => { + withTwoSlides(); + await openPage(); + + expect(screen.getByTestId('hero-slide-0-up')).toBeDisabled(); + expect(screen.getByTestId('hero-slide-1-down')).toBeDisabled(); + }); + + it('removes a slide from the hero, switches one off and marks one decorative', async () => { + withTwoSlides(); + await openPage(); + + await userEvent.click(screen.getByTestId('hero-slide-1-remove')); + await userEvent.click(screen.getByTestId('hero-slide-0-active')); + await userEvent.click(screen.getByTestId('hero-slide-0-decorative')); + expect(screen.getByTestId('hero-slide-0-alt')).toBeDisabled(); + await userEvent.click(screen.getByTestId('hero-save')); + + await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1)); + expect(getSavedHeroRequests()[0].slides).toEqual([ + { id: '00000000-0000-0000-0000-000000000001', imageId: '10000000-0000-0000-0000-000000000001', alt: null, decorative: true, isActive: false }, + ]); + }); + + it('adds an uploaded image as a slide that needs a description before it can be saved', async () => { + withTwoSlides(); + await openPage(); + + await userEvent.upload(screen.getByTestId('hero-upload'), new File(['x'], 'foto.jpg', { type: 'image/jpeg' })); + expect(await screen.findByTestId('hero-slide-2')).toBeInTheDocument(); + await userEvent.click(screen.getByTestId('hero-save')); + + expect(await screen.findByTestId('hero-slide-2-alt-error')).toHaveTextContent(/Geef een beschrijving|Give a description/); + expect(getSavedHeroRequests()).toHaveLength(0); + + await userEvent.type(screen.getByTestId('hero-slide-2-alt'), 'Nieuwe foto'); + await userEvent.click(screen.getByTestId('hero-save')); + + await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1)); + const slides = getSavedHeroRequests()[0].slides; + expect(slides).toHaveLength(3); + expect(slides[2]).toMatchObject({ id: null, alt: 'Nieuwe foto', decorative: false, isActive: true }); + }); + + it('shows the message of the server when an upload is refused', async () => { + await openPage(); + failNextUpload({ status: 400, error: 'unsupported_format', message: 'Dit bestandstype wordt niet ondersteund.' }); + + await userEvent.upload(screen.getByTestId('hero-upload'), new File(['x'], 'x.svg', { type: 'image/svg+xml' })); + + expect(await screen.findByTestId('hero-upload-error')).toHaveTextContent('Dit bestandstype wordt niet ondersteund.'); + expect(screen.getByTestId('hero-slides-empty')).toBeInTheDocument(); + }); + + it('notes that only the first slides are published when there are more than the ceiling', async () => { + setMockHero({ ...emptyHero(), id: 'h1', title: 'T', maxPublishedSlides: 1, slides: [slide(1), slide(2)] }); + + await openPage(); + + expect(screen.getByTestId('hero-ceiling-note')).toHaveTextContent(/Alleen de eerste 1 afbeeldingen|Only the first 1 images/); + }); +}); + +describe('Focus dialog', () => { + const open = async () => { + setMockHero({ ...emptyHero(), id: 'h1', title: 'Andrea Slop', isLive: true, slides: [slide(1)] }); + await openPage(); + await userEvent.click(screen.getByTestId('hero-slide-0-focus')); + return screen.findByTestId('focus-dialog'); + }; + + it('starts with the stored point and shows both previews', async () => { + await open(); + + expect(screen.getByTestId('focus-x')).toHaveValue(50); + expect(screen.getByTestId('focus-y')).toHaveValue(50); + expect(screen.getByTestId('focus-preview-wide')).toBeInTheDocument(); + expect(screen.getByTestId('focus-preview-tall')).toBeInTheDocument(); + }); + + it('moves the point with the keyboard', async () => { + await open(); + + const area = screen.getByTestId('focus-area'); + area.focus(); + await userEvent.keyboard('{ArrowRight}{ArrowRight}{Shift>}{ArrowDown}{/Shift}'); + + expect(screen.getByTestId('focus-x')).toHaveValue(52); + expect(screen.getByTestId('focus-y')).toHaveValue(55); + }); + + it('saves a general point and an own setting for the tall display', async () => { + await open(); + + fireEvent.change(screen.getByTestId('focus-x'), { target: { value: '30' } }); + await userEvent.click(screen.getByTestId('focus-target-tall')); + expect(screen.getByTestId('focus-x')).toBeDisabled(); + await userEvent.click(screen.getByTestId('focus-override-tall')); + fireEvent.change(screen.getByTestId('focus-x'), { target: { value: '80' } }); + fireEvent.change(screen.getByTestId('focus-zoom'), { target: { value: '2' } }); + await userEvent.click(screen.getByTestId('focus-save')); + + await waitFor(() => expect(screen.queryByTestId('focus-dialog')).not.toBeInTheDocument()); + // The dialog closed after the server accepted it; reopening shows the stored values. + await userEvent.click(screen.getByTestId('hero-slide-0-focus')); + expect(screen.getByTestId('focus-x')).toHaveValue(30); + await userEvent.click(screen.getByTestId('focus-target-tall')); + expect(screen.getByTestId('focus-override-tall')).toBeChecked(); + expect(screen.getByTestId('focus-x')).toHaveValue(80); + expect(screen.getByTestId('focus-zoom')).toHaveValue('2'); + }); + + it('goes back to the general point when the own setting is switched off', async () => { + await open(); + await userEvent.click(screen.getByTestId('focus-target-wide')); + await userEvent.click(screen.getByTestId('focus-override-wide')); + fireEvent.change(screen.getByTestId('focus-x'), { target: { value: '10' } }); + await userEvent.click(screen.getByTestId('focus-override-wide')); + + expect(screen.getByTestId('focus-x')).toHaveValue(50); + expect(screen.getByTestId('focus-x')).toBeDisabled(); + }); + + it('closes without saving', async () => { + await open(); + + await userEvent.click(screen.getByTestId('focus-cancel')); + + await waitFor(() => expect(screen.queryByTestId('focus-dialog')).not.toBeInTheDocument()); + }); +}); diff --git a/frontend/src/features/hero/pages/HeroPage.tsx b/frontend/src/features/hero/pages/HeroPage.tsx new file mode 100644 index 0000000..dba105f --- /dev/null +++ b/frontend/src/features/hero/pages/HeroPage.tsx @@ -0,0 +1,321 @@ +import { useEffect, useMemo, useRef, useState } from 'react'; +import { useFieldArray, useForm, useWatch } from 'react-hook-form'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { useTranslation } from 'react-i18next'; +import { toast } from 'sonner'; +import { ArrowDown, ArrowUp, Crosshair, ImagePlus, Trash2 } from 'lucide-react'; +import { Badge } from '@/components/ui/badge'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { FieldError } from '@/components/ui/FieldError'; +import { FormErrorBanner } from '@/components/ui/FormErrorBanner'; +import { NetworkError, ProblemDetailsError } from '@/lib/api-client'; +import { FocusDialog } from '../components/FocusDialog'; +import { mediaUrl } from '../lib/media'; +import { fromLocalInput, heroFormSchema, toLocalInput, type HeroFormData } from '../schemas/hero'; +import { useHero, useSaveHero, useUploadHeroImage } from '../services/hooks'; +import type { HeroAdminDto, HeroImageDto, HeroSaveRequest } from '../services/types'; + +const textareaClass = + 'w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'; + +function toForm(hero: HeroAdminDto): HeroFormData { + const buttons = [0, 1].map((i) => ({ label: hero.buttons[i]?.label ?? '', target: hero.buttons[i]?.target ?? '' })); + return { + title: hero.title, + tagline: hero.tagline ?? '', + lead: hero.lead ?? '', + display: hero.display, + buttons, + isActive: hero.isActive, + startsAt: toLocalInput(hero.startsAt), + endsAt: toLocalInput(hero.endsAt), + slides: hero.slides.map((s) => ({ id: s.id, imageId: s.imageId, alt: s.alt, decorative: s.decorative, isActive: s.isActive })), + }; +} + +function toRequest(values: HeroFormData): HeroSaveRequest { + return { + title: values.title, + tagline: values.tagline || null, + lead: values.lead || null, + display: values.display, + buttons: values.buttons.filter((b) => b.label !== '' && b.target !== ''), + isActive: values.isActive, + startsAt: fromLocalInput(values.startsAt), + endsAt: fromLocalInput(values.endsAt), + slides: values.slides.map((s) => ({ id: s.id, imageId: s.imageId, alt: s.decorative ? null : s.alt, decorative: s.decorative, isActive: s.isActive })), + }; +} + +/** The messages a failed save carries: the field errors of a 400, or a generic text. */ +function serverMessage(error: unknown, generic: string, network: string): string { + if (error instanceof NetworkError) return network; + if (error instanceof ProblemDetailsError && error.status === 400) { + const errors = error.problem.errors; + if (errors && typeof errors === 'object') { + const messages = Object.values(errors as Record).flatMap((v) => (Array.isArray(v) ? v : [v])).filter((v): v is string => typeof v === 'string'); + if (messages.length > 0) return messages.join(' '); + } + } + return generic; +} + +/** The smallest WebP of the wide ratio for a thumbnail; the plain source when there is none. */ +function thumbnail(image: HeroImageDto): string { + const small = image.variants + .filter((v) => v.type === 'image/webp' && v.ratio === 'wide') + .sort((a, b) => a.width - b.width)[0]; + return mediaUrl(small?.url ?? image.src); +} + +export function HeroPage() { + const { t } = useTranslation(); + const { data: hero, isLoading, isError, refetch } = useHero(); + + return ( +
+
+

{t('hero.title')}

+ {hero && ( + + {hero.isLive ? t('hero.live') : t('hero.notLive')} + + )} +
+

{t('hero.intro')}

+ + {isLoading &&

{t('common.loading')}

} + {isError && ( +
+

{t('errors.generic')}

+ +
+ )} + {hero && } +
+ ); +} + +function HeroEditor({ hero }: { hero: HeroAdminDto }) { + const { t } = useTranslation(); + const save = useSaveHero(); + const upload = useUploadHeroImage(); + const [serverError, setServerError] = useState(null); + const [uploadError, setUploadError] = useState(null); + const [localImages, setLocalImages] = useState>({}); + const [focusImageId, setFocusImageId] = useState(null); + const fileInput = useRef(null); + + const { + register, + handleSubmit, + control, + formState: { errors, isDirty }, + } = useForm({ resolver: zodResolver(heroFormSchema), mode: 'onTouched', defaultValues: toForm(hero) }); + const slides = useFieldArray({ control, name: 'slides' }); + const watchedSlides = useWatch({ control, name: 'slides' }) ?? []; + + // The images of the saved hero (always current: a change of focus refreshes them) plus the ones uploaded in this session. + const images = useMemo(() => { + const map: Record = { ...localImages }; + for (const s of hero.slides) map[s.imageId] = s.image; + return map; + }, [hero.slides, localImages]); + + useEffect(() => { + if (!isDirty) return undefined; + const warn = (event: BeforeUnloadEvent) => { + event.preventDefault(); + }; + window.addEventListener('beforeunload', warn); + return () => window.removeEventListener('beforeunload', warn); + }, [isDirty]); + + const onUpload = async (files: FileList | null) => { + const file = files?.[0]; + if (!file) return; + setUploadError(null); + try { + const image = await upload.mutateAsync(file); + setLocalImages((current) => ({ ...current, [image.id]: image })); + slides.append({ id: null, imageId: image.id, alt: '', decorative: false, isActive: true }, { shouldFocus: false }); + } catch (error) { + const message = error instanceof ProblemDetailsError ? error.problem.message : undefined; + setUploadError(typeof message === 'string' ? message : error instanceof NetworkError ? t('errors.network') : t('errors.generic')); + } finally { + if (fileInput.current) fileInput.current.value = ''; + } + }; + + const onSubmit = async (values: HeroFormData) => { + setServerError(null); + try { + await save.mutateAsync(toRequest(values)); + toast.success(t('hero.savedToast')); + } catch (error) { + setServerError(serverMessage(error, t('errors.generic'), t('errors.network'))); + } + }; + + const err = (message?: string) => (message ? t(message) : undefined); + const heroErrors = errors; + + return ( +
+ setServerError(null)} /> + +
+
+ +