H5: admin-scherm voor de hero (formulier, slides, upload, focus-editor met voorbeeld, TypeScript-tweeling van FocusMath)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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.
|
||||
@@ -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',
|
||||
|
||||
@@ -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 (
|
||||
<Dialog open={image !== null} onOpenChange={(next) => { if (!next) onClose(); }}>
|
||||
<DialogContent className="max-h-[92vh] overflow-y-auto sm:max-w-3xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('hero.focus.title')}</DialogTitle>
|
||||
</DialogHeader>
|
||||
{/* Mounted only while open, so every opening starts from the stored values. */}
|
||||
{image && <FocusEditor image={image} onClose={onClose} />}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
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<HTMLDivElement>(null);
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
const [target, setTarget] = useState<Target>('general');
|
||||
const [general, setGeneral] = useState<FocusDto>(image.focus ?? CENTRE);
|
||||
const [wide, setWide] = useState<FocusDto | null>(image.wideFocus);
|
||||
const [tall, setTall] = useState<FocusDto | null>(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<HTMLDivElement>) => {
|
||||
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<HTMLDivElement>) => {
|
||||
if (!editable) return;
|
||||
const step = event.shiftKey ? 0.05 : 0.01;
|
||||
const moves: Record<string, [number, number]> = { 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 (
|
||||
<div className="space-y-4" data-testid="focus-dialog">
|
||||
<FormErrorBanner error={serverError !== null ? { message: serverError } : null} onDismiss={() => setServerError(null)} />
|
||||
<p className="text-sm text-muted-foreground">{t('hero.focus.intro')}</p>
|
||||
|
||||
<fieldset className="flex flex-wrap gap-4">
|
||||
<legend className="sr-only">{t('hero.focus.targetLegend')}</legend>
|
||||
{(['general', 'wide', 'tall'] as const).map((value) => (
|
||||
<label key={value} className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="radio"
|
||||
name="focus-target"
|
||||
checked={target === value}
|
||||
onChange={() => setTarget(value)}
|
||||
data-testid={`focus-target-${value}`}
|
||||
/>
|
||||
{t(`hero.focus.target.${value}`)}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
|
||||
{target !== 'general' && (
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={editable}
|
||||
onChange={(event) => toggleOverride(event.target.checked)}
|
||||
data-testid={`focus-override-${target}`}
|
||||
/>
|
||||
{t('hero.focus.override')}
|
||||
</label>
|
||||
)}
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-[2fr_1fr]">
|
||||
<div>
|
||||
<div
|
||||
ref={area}
|
||||
role="group"
|
||||
tabIndex={0}
|
||||
aria-label={t('hero.focus.areaLabel')}
|
||||
className="relative touch-none select-none overflow-hidden rounded-md border"
|
||||
style={{ aspectRatio: `${image.width} / ${image.height}` }}
|
||||
onPointerDown={(event) => {
|
||||
event.currentTarget.setPointerCapture?.(event.pointerId);
|
||||
moveTo(event);
|
||||
}}
|
||||
onPointerMove={(event) => {
|
||||
if (event.buttons === 1) moveTo(event);
|
||||
}}
|
||||
onKeyDown={onKeyDown}
|
||||
data-testid="focus-area"
|
||||
>
|
||||
<img src={mediaUrl(image.src)} alt="" draggable={false} className="pointer-events-none absolute inset-0 h-full w-full" />
|
||||
<div className="pointer-events-none absolute border-2 border-sky-400" style={outline(WIDE, effective.wide)} data-testid="focus-outline-wide" />
|
||||
<div className="pointer-events-none absolute border-2 border-amber-400" style={outline(TALL, effective.tall)} data-testid="focus-outline-tall" />
|
||||
<div
|
||||
className="pointer-events-none absolute size-5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white bg-red-500/80 shadow"
|
||||
style={{ left: `${active.x * 100}%`, top: `${active.y * 100}%` }}
|
||||
data-testid="focus-marker"
|
||||
/>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-muted-foreground">{t('hero.focus.areaHint')}</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="focus-x">{t('hero.focus.x')}</Label>
|
||||
<Input
|
||||
id="focus-x"
|
||||
type="number"
|
||||
min={0}
|
||||
max={100}
|
||||
step={0.5}
|
||||
disabled={!editable}
|
||||
value={percent(active.x)}
|
||||
onChange={(event) => update({ ...active, x: Number(event.target.value) / 100 })}
|
||||
data-testid="focus-x"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="focus-y">{t('hero.focus.y')}</Label>
|
||||
<Input
|
||||
id="focus-y"
|
||||
type="number"
|
||||
min={0}
|
||||
max={100}
|
||||
step={0.5}
|
||||
disabled={!editable}
|
||||
value={percent(active.y)}
|
||||
onChange={(event) => update({ ...active, y: Number(event.target.value) / 100 })}
|
||||
data-testid="focus-y"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="focus-zoom">{t('hero.focus.zoom', { value: active.zoom.toFixed(2) })}</Label>
|
||||
<input
|
||||
id="focus-zoom"
|
||||
type="range"
|
||||
min={1}
|
||||
max={MAX_ZOOM}
|
||||
step={0.05}
|
||||
disabled={!editable}
|
||||
value={active.zoom}
|
||||
onChange={(event) => update({ ...active, zoom: Number(event.target.value) })}
|
||||
className="w-full"
|
||||
data-testid="focus-zoom"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{([WIDE, TALL] as const).map((ratio) => {
|
||||
const crop = cropFor(image.width, image.height, ratio, effective[ratio.name]);
|
||||
return (
|
||||
<div key={ratio.name}>
|
||||
<p className="mb-1 text-xs font-medium">{t(`hero.focus.preview.${ratio.name}`)}</p>
|
||||
<div
|
||||
className="relative overflow-hidden rounded border bg-muted"
|
||||
style={{ aspectRatio: `${ratio.numerator} / ${ratio.denominator}`, maxWidth: ratio.name === 'tall' ? '8rem' : '12rem' }}
|
||||
data-testid={`focus-preview-${ratio.name}`}
|
||||
>
|
||||
<img
|
||||
src={mediaUrl(image.src)}
|
||||
alt=""
|
||||
className="absolute max-w-none"
|
||||
style={{
|
||||
width: `${(image.width / crop.width) * 100}%`,
|
||||
left: `${(-crop.x / crop.width) * 100}%`,
|
||||
// top is a percentage of the box height, which is the box width times denominator over numerator.
|
||||
top: `${(-crop.y / crop.width) * (ratio.numerator / ratio.denominator) * 100}%`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button type="button" variant="outline" onClick={onClose} data-testid="focus-cancel">
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button type="button" onClick={onSave} disabled={save.isPending} data-testid="focus-save">
|
||||
{save.isPending ? '…' : t('common.save')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { getAppConfig } from '@/lib/config';
|
||||
|
||||
/** A media address of the host (<c>/media/...</c>) as the browser must request it from the admin. */
|
||||
export const mediaUrl = (path: string): string => `${getAppConfig().apiBaseUrl.replace(/\/$/, '')}${path}`;
|
||||
@@ -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> = {}): 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<string, HeroImageDto> = {};
|
||||
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);
|
||||
}),
|
||||
];
|
||||
@@ -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());
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown>).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 (
|
||||
<div className="space-y-6" data-testid="hero-page">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<h1 className="text-2xl font-semibold" data-testid="hero-title">{t('hero.title')}</h1>
|
||||
{hero && (
|
||||
<Badge variant={hero.isLive ? 'default' : 'secondary'} data-testid="hero-live-badge">
|
||||
{hero.isLive ? t('hero.live') : t('hero.notLive')}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="max-w-3xl text-sm text-muted-foreground">{t('hero.intro')}</p>
|
||||
|
||||
{isLoading && <p data-testid="hero-loading">{t('common.loading')}</p>}
|
||||
{isError && (
|
||||
<div className="space-y-2" data-testid="hero-error">
|
||||
<p>{t('errors.generic')}</p>
|
||||
<Button variant="outline" onClick={() => void refetch()}>{t('common.retry')}</Button>
|
||||
</div>
|
||||
)}
|
||||
{hero && <HeroEditor key={hero.id ?? 'new'} hero={hero} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
const { t } = useTranslation();
|
||||
const save = useSaveHero();
|
||||
const upload = useUploadHeroImage();
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
const [uploadError, setUploadError] = useState<string | null>(null);
|
||||
const [localImages, setLocalImages] = useState<Record<string, HeroImageDto>>({});
|
||||
const [focusImageId, setFocusImageId] = useState<string | null>(null);
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
control,
|
||||
formState: { errors, isDirty },
|
||||
} = useForm<HeroFormData>({ 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<string, HeroImageDto> = { ...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 (
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-8" noValidate data-testid="hero-form">
|
||||
<FormErrorBanner error={serverError !== null ? { message: serverError } : null} onDismiss={() => setServerError(null)} />
|
||||
|
||||
<section className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="hero-title-input">{t('hero.fields.title')}</Label>
|
||||
<textarea id="hero-title-input" rows={3} className={textareaClass} data-testid="hero-title-input" {...register('title')} />
|
||||
<p className="text-xs text-muted-foreground">{t('hero.fields.titleHint')}</p>
|
||||
<FieldError message={err(heroErrors.title?.message)} testId="hero-title-error" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="hero-tagline">{t('hero.fields.tagline')}</Label>
|
||||
<Input id="hero-tagline" maxLength={120} data-testid="hero-tagline" {...register('tagline')} />
|
||||
<FieldError message={err(heroErrors.tagline?.message)} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="hero-lead">{t('hero.fields.lead')}</Label>
|
||||
<textarea id="hero-lead" rows={3} className={textareaClass} data-testid="hero-lead" {...register('lead')} />
|
||||
<FieldError message={err(heroErrors.lead?.message)} />
|
||||
</div>
|
||||
<fieldset className="space-y-2">
|
||||
<legend className="text-sm font-medium">{t('hero.fields.display')}</legend>
|
||||
<div className="flex flex-wrap gap-4 text-sm">
|
||||
{(['single', 'slideshow'] as const).map((value) => (
|
||||
<label key={value} className="flex items-center gap-2">
|
||||
<input type="radio" value={value} data-testid={`hero-display-${value}`} {...register('display')} />
|
||||
{t(`hero.display.${value}`)}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
</section>
|
||||
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-lg font-medium">{t('hero.buttons.title')}</h2>
|
||||
<p className="text-xs text-muted-foreground">{t('hero.buttons.hint')}</p>
|
||||
{[0, 1].map((i) => (
|
||||
<div key={i} className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor={`hero-button-${i}-label`}>{t('hero.buttons.label', { n: i + 1 })}</Label>
|
||||
<Input id={`hero-button-${i}-label`} maxLength={50} data-testid={`hero-button-${i}-label`} {...register(`buttons.${i}.label` as const)} />
|
||||
<FieldError message={err(heroErrors.buttons?.[i]?.label?.message)} testId={`hero-button-${i}-label-error`} />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor={`hero-button-${i}-target`}>{t('hero.buttons.target', { n: i + 1 })}</Label>
|
||||
<Input id={`hero-button-${i}-target`} maxLength={500} placeholder="#contact, /over-mij, https://…" data-testid={`hero-button-${i}-target`} {...register(`buttons.${i}.target` as const)} />
|
||||
<FieldError message={err(heroErrors.buttons?.[i]?.target?.message)} testId={`hero-button-${i}-target-error`} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-lg font-medium">{t('hero.schedule.title')}</h2>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" className="size-4 rounded border-input" data-testid="hero-active" {...register('isActive')} />
|
||||
{t('hero.schedule.active')}
|
||||
</label>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="hero-starts">{t('hero.schedule.starts')}</Label>
|
||||
<Input id="hero-starts" type="datetime-local" data-testid="hero-starts" {...register('startsAt')} />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="hero-ends">{t('hero.schedule.ends')}</Label>
|
||||
<Input id="hero-ends" type="datetime-local" data-testid="hero-ends" {...register('endsAt')} />
|
||||
<FieldError message={err(heroErrors.endsAt?.message)} testId="hero-ends-error" />
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{t('hero.schedule.hint')}</p>
|
||||
</section>
|
||||
|
||||
<section className="space-y-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<h2 className="text-lg font-medium">{t('hero.slides.title')}</h2>
|
||||
<div>
|
||||
<input
|
||||
ref={fileInput}
|
||||
id="hero-upload"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
className="sr-only"
|
||||
data-testid="hero-upload"
|
||||
onChange={(event) => void onUpload(event.target.files)}
|
||||
/>
|
||||
<Button type="button" variant="outline" disabled={upload.isPending} onClick={() => fileInput.current?.click()} data-testid="hero-upload-button">
|
||||
<ImagePlus className="mr-2 size-4" aria-hidden="true" />
|
||||
{upload.isPending ? t('hero.slides.uploading') : t('hero.slides.add')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{t('hero.slides.hint')}</p>
|
||||
{uploadError && <p className="text-sm text-destructive" role="alert" data-testid="hero-upload-error">{uploadError}</p>}
|
||||
{slides.fields.length === 0 && <p className="text-sm text-muted-foreground" data-testid="hero-slides-empty">{t('hero.slides.empty')}</p>}
|
||||
|
||||
<ol className="space-y-3" data-testid="hero-slides">
|
||||
{slides.fields.map((field, index) => {
|
||||
const image = images[field.imageId];
|
||||
const decorative = watchedSlides[index]?.decorative ?? false;
|
||||
return (
|
||||
<li key={field.id} className="flex flex-wrap items-start gap-3 rounded-md border p-3" data-testid={`hero-slide-${index}`}>
|
||||
{image ? (
|
||||
<img src={thumbnail(image)} alt="" className="h-20 w-28 rounded object-cover" />
|
||||
) : (
|
||||
<div className="flex h-20 w-28 items-center justify-center rounded bg-muted text-xs">?</div>
|
||||
)}
|
||||
<div className="min-w-[12rem] flex-1 space-y-2">
|
||||
<Label htmlFor={`hero-slide-${index}-alt`}>{t('hero.slides.alt', { n: index + 1 })}</Label>
|
||||
<Input id={`hero-slide-${index}-alt`} maxLength={300} disabled={decorative} data-testid={`hero-slide-${index}-alt`} {...register(`slides.${index}.alt` as const)} />
|
||||
<FieldError message={err(heroErrors.slides?.[index]?.alt?.message)} testId={`hero-slide-${index}-alt-error`} />
|
||||
<div className="flex flex-wrap gap-4 text-sm">
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="checkbox" className="size-4 rounded border-input" data-testid={`hero-slide-${index}-decorative`} {...register(`slides.${index}.decorative` as const)} />
|
||||
{t('hero.slides.decorative')}
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="checkbox" className="size-4 rounded border-input" data-testid={`hero-slide-${index}-active`} {...register(`slides.${index}.isActive` as const)} />
|
||||
{t('hero.slides.active')}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-1">
|
||||
<Button type="button" variant="outline" size="icon" aria-label={t('hero.slides.up')} disabled={index === 0} onClick={() => slides.move(index, index - 1)} data-testid={`hero-slide-${index}-up`}>
|
||||
<ArrowUp className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
<Button type="button" variant="outline" size="icon" aria-label={t('hero.slides.down')} disabled={index === slides.fields.length - 1} onClick={() => slides.move(index, index + 1)} data-testid={`hero-slide-${index}-down`}>
|
||||
<ArrowDown className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
<Button type="button" variant="outline" size="icon" aria-label={t('hero.slides.focus')} disabled={!image} onClick={() => setFocusImageId(field.imageId)} data-testid={`hero-slide-${index}-focus`}>
|
||||
<Crosshair className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
<Button type="button" variant="outline" size="icon" aria-label={t('hero.slides.remove')} onClick={() => slides.remove(index)} data-testid={`hero-slide-${index}-remove`}>
|
||||
<Trash2 className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
{slides.fields.length > hero.maxPublishedSlides && (
|
||||
<p className="text-xs text-muted-foreground" data-testid="hero-ceiling-note">
|
||||
{t('hero.slides.ceiling', { max: hero.maxPublishedSlides })}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button type="submit" disabled={save.isPending} data-testid="hero-save">
|
||||
{save.isPending ? '…' : t('common.save')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<FocusDialog image={focusImageId ? images[focusImageId] ?? null : null} onClose={() => setFocusImageId(null)} />
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { fromLocalInput, heroFormSchema, isAllowedButtonTarget, toLocalInput } from './hero';
|
||||
|
||||
// The same cases as ButtonTargetValidatorTests in src/SlpModularCms.Modules.Hero.Tests/HeroRulesTests.cs.
|
||||
describe('isAllowedButtonTarget', () => {
|
||||
it.each(['#contact', '#pakketten', '#a-b_c9', '/over-mij', '/', '/a/b/c?x=1&y=2', 'https://andreaslop.nl/portfolio', 'https://sub.example.com:8443/p?q=1#top'])(
|
||||
'accepts %s',
|
||||
(target) => expect(isAllowedButtonTarget(target)).toBe(true),
|
||||
);
|
||||
|
||||
it.each([
|
||||
'', ' ', 'contact', '#', '#1abc', '# contact', '#a b', '//evil.example/x', '/\\evil.example', '/a b', 'http://example.com', 'HTTPS://example.com',
|
||||
'https://user:pw@example.com', 'https://', 'https:///path', 'javascript:alert(1)', 'JaVaScRiPt:alert(1)', 'data:text/html;base64,AAAA', 'mailto:a@b.nl',
|
||||
'tel:+31612345678', 'ftp://example.com/x', '/ok"onmouseover="x', '/ok<script>', ' /leading-space', '/trailing-space ', '/tab\tx', '/new\nline',
|
||||
])('rejects %j', (target) => expect(isAllowedButtonTarget(target)).toBe(false));
|
||||
});
|
||||
|
||||
const base = {
|
||||
title: 'Titel',
|
||||
tagline: '',
|
||||
lead: '',
|
||||
display: 'single' as const,
|
||||
buttons: [{ label: '', target: '' }, { label: '', target: '' }],
|
||||
isActive: true,
|
||||
startsAt: '',
|
||||
endsAt: '',
|
||||
slides: [],
|
||||
};
|
||||
|
||||
describe('heroFormSchema', () => {
|
||||
it('accepts a minimal hero', () => expect(heroFormSchema.safeParse(base).success).toBe(true));
|
||||
|
||||
it('wants a title of at most 200 characters and 5 lines', () => {
|
||||
expect(heroFormSchema.safeParse({ ...base, title: ' ' }).success).toBe(false);
|
||||
expect(heroFormSchema.safeParse({ ...base, title: 'x'.repeat(201) }).success).toBe(false);
|
||||
expect(heroFormSchema.safeParse({ ...base, title: 'a\nb\nc\nd\ne\nf' }).success).toBe(false);
|
||||
expect(heroFormSchema.safeParse({ ...base, title: 'a\nb\nc\nd\ne' }).success).toBe(true);
|
||||
});
|
||||
|
||||
it('wants an alt text unless the slide is decorative', () => {
|
||||
const slide = { id: null, imageId: 'i1', alt: '', decorative: false, isActive: true };
|
||||
expect(heroFormSchema.safeParse({ ...base, slides: [slide] }).success).toBe(false);
|
||||
expect(heroFormSchema.safeParse({ ...base, slides: [{ ...slide, decorative: true }] }).success).toBe(true);
|
||||
expect(heroFormSchema.safeParse({ ...base, slides: [{ ...slide, alt: 'Een foto' }] }).success).toBe(true);
|
||||
});
|
||||
|
||||
it('allows any number of slides', () => {
|
||||
const slides = Array.from({ length: 80 }, (_, i) => ({ id: null, imageId: `i${i}`, alt: 'foto', decorative: false, isActive: true }));
|
||||
expect(heroFormSchema.safeParse({ ...base, slides }).success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('local date inputs', () => {
|
||||
it('round-trips an instant', () => {
|
||||
const iso = '2026-12-01T09:30:00.000Z';
|
||||
expect(fromLocalInput(toLocalInput(iso))).toBe(iso);
|
||||
expect(toLocalInput(null)).toBe('');
|
||||
expect(fromLocalInput('')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const TITLE_MAX = 200;
|
||||
export const TITLE_MAX_LINES = 5;
|
||||
export const TAGLINE_MAX = 120;
|
||||
export const LEAD_MAX = 600;
|
||||
export const BUTTON_LABEL_MAX = 50;
|
||||
export const BUTTON_TARGET_MAX = 500;
|
||||
export const ALT_MAX = 300;
|
||||
|
||||
/**
|
||||
* Twin of the host's `ButtonTargetValidator`: a page anchor (#contact), a path of the site (/over-mij) or an absolute
|
||||
* https address. Nothing else, so a button can never carry javascript:, data: or a protocol-relative address.
|
||||
*/
|
||||
export function isAllowedButtonTarget(target: string): boolean {
|
||||
if (target === '' || target !== target.trim()) return false;
|
||||
if ([...target].some((c) => /\s/.test(c) || c.charCodeAt(0) < 32 || '\\"<>`'.includes(c))) return false;
|
||||
if (target.startsWith('#')) return /^#[A-Za-z][A-Za-z0-9_-]{0,99}$/.test(target);
|
||||
if (target.startsWith('/')) return target.length === 1 || target[1] !== '/';
|
||||
try {
|
||||
const url = new URL(target);
|
||||
// A host must follow the two slashes directly ("https:///path" is no address, even where a parser repairs it).
|
||||
return /^https:[/][/][^/?#]/.test(target) && url.protocol === 'https:' && url.hostname !== '' && url.username === '';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const buttonSchema = z
|
||||
.object({
|
||||
label: z.string().trim().max(BUTTON_LABEL_MAX, 'hero.errors.buttonLabelTooLong'),
|
||||
target: z.string().trim().max(BUTTON_TARGET_MAX, 'hero.errors.buttonTargetTooLong'),
|
||||
})
|
||||
.superRefine((b, ctx) => {
|
||||
const hasLabel = b.label !== '';
|
||||
const hasTarget = b.target !== '';
|
||||
if (hasLabel !== hasTarget) {
|
||||
ctx.addIssue({ code: 'custom', path: [hasTarget ? 'label' : 'target'], message: 'hero.errors.buttonIncomplete' });
|
||||
} else if (hasTarget && !isAllowedButtonTarget(b.target)) {
|
||||
ctx.addIssue({ code: 'custom', path: ['target'], message: 'hero.errors.buttonTargetInvalid' });
|
||||
}
|
||||
});
|
||||
|
||||
const slideSchema = z
|
||||
.object({
|
||||
id: z.string().nullable(),
|
||||
imageId: z.string().min(1),
|
||||
alt: z.string().trim().max(ALT_MAX, 'hero.errors.altTooLong'),
|
||||
decorative: z.boolean(),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
.superRefine((s, ctx) => {
|
||||
if (!s.decorative && s.alt === '') {
|
||||
ctx.addIssue({ code: 'custom', path: ['alt'], message: 'hero.errors.altRequired' });
|
||||
}
|
||||
});
|
||||
|
||||
export const heroFormSchema = z
|
||||
.object({
|
||||
title: z.string().trim().min(1, 'hero.errors.titleRequired').max(TITLE_MAX, 'hero.errors.titleTooLong'),
|
||||
tagline: z.string().trim().max(TAGLINE_MAX, 'hero.errors.taglineTooLong'),
|
||||
lead: z.string().trim().max(LEAD_MAX, 'hero.errors.leadTooLong'),
|
||||
display: z.enum(['single', 'slideshow']),
|
||||
buttons: z.array(buttonSchema).length(2),
|
||||
isActive: z.boolean(),
|
||||
/** datetime-local value ("YYYY-MM-DDTHH:mm") in the browser's time zone, or ''. */
|
||||
startsAt: z.string(),
|
||||
endsAt: z.string(),
|
||||
slides: z.array(slideSchema),
|
||||
})
|
||||
.superRefine((v, ctx) => {
|
||||
if (v.title.replace(/\r\n/g, '\n').split('\n').length > TITLE_MAX_LINES) {
|
||||
ctx.addIssue({ code: 'custom', path: ['title'], message: 'hero.errors.titleTooManyLines' });
|
||||
}
|
||||
if (v.startsAt !== '' && v.endsAt !== '' && fromLocalInput(v.endsAt)! <= fromLocalInput(v.startsAt)!) {
|
||||
ctx.addIssue({ code: 'custom', path: ['endsAt'], message: 'hero.errors.endAfterStart' });
|
||||
}
|
||||
});
|
||||
|
||||
export type HeroFormData = z.infer<typeof heroFormSchema>;
|
||||
|
||||
/** ISO instant to the value of a datetime-local input (browser time zone). */
|
||||
export function toLocalInput(iso: string | null): string {
|
||||
if (!iso) return '';
|
||||
const d = new Date(iso);
|
||||
if (Number.isNaN(d.getTime())) return '';
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
|
||||
/** Value of a datetime-local input to an ISO instant, or null when empty. */
|
||||
export function fromLocalInput(value: string): string | null {
|
||||
if (!value) return null;
|
||||
const d = new Date(value);
|
||||
return Number.isNaN(d.getTime()) ? null : d.toISOString();
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { api } from '@/lib/api-client';
|
||||
import type { HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest } from './types';
|
||||
|
||||
export const HERO_KEY = ['hero'];
|
||||
|
||||
/** The hero as the admin edits it (also the image variants of every slide). */
|
||||
export function useHero() {
|
||||
return useQuery<HeroAdminDto, Error>({
|
||||
queryKey: HERO_KEY,
|
||||
queryFn: () => api.get<HeroAdminDto>('/api/v1/hero/all'),
|
||||
});
|
||||
}
|
||||
|
||||
export function useSaveHero() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<HeroAdminDto, Error, HeroSaveRequest>({
|
||||
mutationFn: (body) => api.put<HeroAdminDto>('/api/v1/hero', body),
|
||||
onSuccess: (hero) => {
|
||||
queryClient.setQueryData(HERO_KEY, hero);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Uploads one image file; the server answers with the image and its variants. */
|
||||
export function useUploadHeroImage() {
|
||||
return useMutation<HeroImageDto, Error, File>({
|
||||
mutationFn: (file) => {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
return api.post<HeroImageDto>('/api/v1/hero/images', form);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useSetImageFocus() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<HeroImageDto, Error, { imageId: string; body: HeroFocusRequest }>({
|
||||
mutationFn: ({ imageId, body }) => api.put<HeroImageDto>(`/api/v1/hero/images/${imageId}/focus`, body),
|
||||
onSuccess: () => {
|
||||
// The slide list shows the image variants; they have new addresses after a change of focus.
|
||||
void queryClient.invalidateQueries({ queryKey: HERO_KEY });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteHeroImage() {
|
||||
return useMutation<void, Error, string>({
|
||||
mutationFn: (imageId) => api.delete<void>(`/api/v1/hero/images/${imageId}`),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
export type HeroDisplay = 'single' | 'slideshow';
|
||||
|
||||
export interface FocusDto {
|
||||
x: number;
|
||||
y: number;
|
||||
zoom: number;
|
||||
}
|
||||
|
||||
export interface HeroVariantDto {
|
||||
ratio: string;
|
||||
width: number;
|
||||
height: number;
|
||||
type: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
export interface HeroImageDto {
|
||||
id: string;
|
||||
width: number;
|
||||
height: number;
|
||||
focus: FocusDto;
|
||||
wideFocus: FocusDto | null;
|
||||
tallFocus: FocusDto | null;
|
||||
src: string;
|
||||
variants: HeroVariantDto[];
|
||||
}
|
||||
|
||||
export interface HeroButtonDto {
|
||||
label: string;
|
||||
target: string;
|
||||
}
|
||||
|
||||
export interface HeroSlideAdminDto {
|
||||
id: string;
|
||||
imageId: string;
|
||||
alt: string;
|
||||
decorative: boolean;
|
||||
isActive: boolean;
|
||||
sortOrder: number;
|
||||
image: HeroImageDto;
|
||||
}
|
||||
|
||||
export interface HeroAdminDto {
|
||||
id: string | null;
|
||||
title: string;
|
||||
tagline: string | null;
|
||||
lead: string | null;
|
||||
display: HeroDisplay;
|
||||
buttons: HeroButtonDto[];
|
||||
isActive: boolean;
|
||||
startsAt: string | null;
|
||||
endsAt: string | null;
|
||||
slides: HeroSlideAdminDto[];
|
||||
isLive: boolean;
|
||||
updatedAt: string | null;
|
||||
maxPublishedSlides: number;
|
||||
}
|
||||
|
||||
export interface HeroSlideRequest {
|
||||
id?: string | null;
|
||||
imageId: string;
|
||||
alt: string | null;
|
||||
decorative: boolean;
|
||||
isActive: boolean;
|
||||
}
|
||||
|
||||
export interface HeroSaveRequest {
|
||||
title: string;
|
||||
tagline: string | null;
|
||||
lead: string | null;
|
||||
display: HeroDisplay;
|
||||
buttons: HeroButtonDto[];
|
||||
isActive: boolean;
|
||||
startsAt: string | null;
|
||||
endsAt: string | null;
|
||||
slides: HeroSlideRequest[];
|
||||
}
|
||||
|
||||
export interface HeroFocusRequest {
|
||||
focus: FocusDto;
|
||||
wide: FocusDto | null;
|
||||
tall: FocusDto | null;
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { http, HttpResponse } from 'msw';
|
||||
export const systemHandlers = [
|
||||
http.get('*/System/capabilities', () =>
|
||||
HttpResponse.json({
|
||||
modules: ['Availability', 'Identity', 'Master', 'Offerings'],
|
||||
modules: ['Availability', 'Identity', 'Master', 'Offerings', 'Hero'],
|
||||
emailEnabled: false,
|
||||
defaultLanguage: 'nl',
|
||||
}),
|
||||
|
||||
@@ -15,7 +15,8 @@
|
||||
"profile": "Profile",
|
||||
"settings": "Settings",
|
||||
"openMenu": "Open navigation",
|
||||
"closeMenu": "Close navigation"
|
||||
"closeMenu": "Close navigation",
|
||||
"hero": "Hero"
|
||||
},
|
||||
"theme": {
|
||||
"switchToLight": "Switch to light theme",
|
||||
@@ -273,9 +274,18 @@
|
||||
"masterControlled": "This instance has been disabled by the Master CMS. Availability cannot be changed here until the Master releases it.",
|
||||
"masterControlledSaveError": "Cannot be changed: the Master CMS controls this status."
|
||||
},
|
||||
"modules": { "title": "Module Management", "comingSoon": "Coming soon" },
|
||||
"systemConfig": { "title": "System Configuration", "comingSoon": "Coming soon" },
|
||||
"branding": { "title": "Branding / Theme", "comingSoon": "Coming soon" }
|
||||
"modules": {
|
||||
"title": "Module Management",
|
||||
"comingSoon": "Coming soon"
|
||||
},
|
||||
"systemConfig": {
|
||||
"title": "System Configuration",
|
||||
"comingSoon": "Coming soon"
|
||||
},
|
||||
"branding": {
|
||||
"title": "Branding / Theme",
|
||||
"comingSoon": "Coming soon"
|
||||
}
|
||||
},
|
||||
"cms": {
|
||||
"title": "CMS Instances",
|
||||
@@ -600,5 +610,86 @@
|
||||
"none": "There is no recipient address yet: messages are kept but not mailed."
|
||||
}
|
||||
}
|
||||
},
|
||||
"hero": {
|
||||
"title": "Hero",
|
||||
"live": "Live",
|
||||
"notLive": "Not live",
|
||||
"intro": "The hero is the first thing visitors of the website see. Here you manage the texts, the buttons and the images; the website decides how they are shown. A change is visible within about a minute.",
|
||||
"savedToast": "Hero saved",
|
||||
"fields": {
|
||||
"title": "Title",
|
||||
"titleHint": "A new line in this field is a line break in the title (at most 5 lines).",
|
||||
"tagline": "Tagline (short label, optional)",
|
||||
"lead": "Introduction (optional)",
|
||||
"display": "Display"
|
||||
},
|
||||
"display": {
|
||||
"single": "Single",
|
||||
"slideshow": "Slideshow"
|
||||
},
|
||||
"buttons": {
|
||||
"title": "Buttons",
|
||||
"hint": "At most two buttons. The target is an #anchor on the page, a /path on the site or an https:// address.",
|
||||
"label": "Button {{n}}: text",
|
||||
"target": "Button {{n}}: target"
|
||||
},
|
||||
"schedule": {
|
||||
"title": "Schedule",
|
||||
"active": "Hero is switched on",
|
||||
"starts": "Visible from",
|
||||
"ends": "Visible until",
|
||||
"hint": "Outside the schedule, or switched off, the website shows its own default hero."
|
||||
},
|
||||
"slides": {
|
||||
"title": "Images",
|
||||
"add": "Add image",
|
||||
"uploading": "Uploading…",
|
||||
"hint": "Upload a photo (JPEG, PNG, WebP and other common formats, at most 10 MB). Set where the subject is with the Focus button. The first image is the first one visitors see.",
|
||||
"empty": "No images yet.",
|
||||
"alt": "Description of image {{n}} (alt text)",
|
||||
"decorative": "Decorative (no description)",
|
||||
"active": "Show",
|
||||
"up": "Move up",
|
||||
"down": "Move down",
|
||||
"focus": "Set focus",
|
||||
"remove": "Remove from the hero",
|
||||
"ceiling": "Only the first {{max}} images are shown on the website."
|
||||
},
|
||||
"focus": {
|
||||
"title": "Focus and crop",
|
||||
"intro": "Click or drag on the photo to show where the subject is. The website crops the photo for landscape (wide) and portrait (tall) screens so that the subject stays in view.",
|
||||
"targetLegend": "For which display",
|
||||
"target": {
|
||||
"general": "General",
|
||||
"wide": "Landscape (3:2)",
|
||||
"tall": "Portrait (4:5)"
|
||||
},
|
||||
"override": "Own setting for this display",
|
||||
"areaLabel": "Photo: choose the point of the subject",
|
||||
"areaHint": "The arrow keys move the point (faster with Shift).",
|
||||
"x": "Horizontal (%)",
|
||||
"y": "Vertical (%)",
|
||||
"zoom": "Zoom ({{value}}×)",
|
||||
"preview": {
|
||||
"wide": "Landscape preview",
|
||||
"tall": "Portrait preview"
|
||||
},
|
||||
"savedToast": "Focus saved"
|
||||
},
|
||||
"errors": {
|
||||
"titleRequired": "A title is required.",
|
||||
"titleTooLong": "The title can have at most 200 characters.",
|
||||
"titleTooManyLines": "The title can have at most 5 lines.",
|
||||
"taglineTooLong": "The tagline can have at most 120 characters.",
|
||||
"leadTooLong": "The introduction can have at most 600 characters.",
|
||||
"buttonLabelTooLong": "The button text can have at most 50 characters.",
|
||||
"buttonTargetTooLong": "The target can have at most 500 characters.",
|
||||
"buttonIncomplete": "Fill in both the text and the target of the button, or leave both empty.",
|
||||
"buttonTargetInvalid": "Choose an #anchor, a /path or an https:// address.",
|
||||
"altTooLong": "The description can have at most 300 characters.",
|
||||
"altRequired": "Give a description or mark the image as decorative.",
|
||||
"endAfterStart": "The end must be after the start."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,8 @@
|
||||
"profile": "Profiel",
|
||||
"settings": "Instellingen",
|
||||
"openMenu": "Navigatie openen",
|
||||
"closeMenu": "Navigatie sluiten"
|
||||
"closeMenu": "Navigatie sluiten",
|
||||
"hero": "Hero"
|
||||
},
|
||||
"theme": {
|
||||
"switchToLight": "Overschakelen naar licht thema",
|
||||
@@ -273,9 +274,18 @@
|
||||
"masterControlled": "Deze instantie is door de Master-CMS uitgeschakeld. De beschikbaarheid kan hier niet worden gewijzigd totdat de Master de status weer vrijgeeft.",
|
||||
"masterControlledSaveError": "Kan niet worden gewijzigd: de Master-CMS beheert deze status."
|
||||
},
|
||||
"modules": { "title": "Modulebeheer", "comingSoon": "Binnenkort beschikbaar" },
|
||||
"systemConfig": { "title": "Systeemconfiguratie", "comingSoon": "Binnenkort beschikbaar" },
|
||||
"branding": { "title": "Huisstijl / Thema", "comingSoon": "Binnenkort beschikbaar" }
|
||||
"modules": {
|
||||
"title": "Modulebeheer",
|
||||
"comingSoon": "Binnenkort beschikbaar"
|
||||
},
|
||||
"systemConfig": {
|
||||
"title": "Systeemconfiguratie",
|
||||
"comingSoon": "Binnenkort beschikbaar"
|
||||
},
|
||||
"branding": {
|
||||
"title": "Huisstijl / Thema",
|
||||
"comingSoon": "Binnenkort beschikbaar"
|
||||
}
|
||||
},
|
||||
"cms": {
|
||||
"title": "CMS-instanties",
|
||||
@@ -600,5 +610,86 @@
|
||||
"none": "Er is nog geen ontvangstadres: berichten worden bewaard maar niet gemaild."
|
||||
}
|
||||
}
|
||||
},
|
||||
"hero": {
|
||||
"title": "Hero",
|
||||
"live": "Live",
|
||||
"notLive": "Niet live",
|
||||
"intro": "De hero is het eerste wat bezoekers van de website zien. Hier beheer je de teksten, de knoppen en de afbeeldingen; de website bepaalt zelf hoe ze worden getoond. Een wijziging is binnen ongeveer een minuut zichtbaar.",
|
||||
"savedToast": "Hero opgeslagen",
|
||||
"fields": {
|
||||
"title": "Titel",
|
||||
"titleHint": "Een nieuwe regel in dit veld is een regelafbreking in de titel (maximaal 5 regels).",
|
||||
"tagline": "Tagline (kort label, optioneel)",
|
||||
"lead": "Introductietekst (optioneel)",
|
||||
"display": "Weergave"
|
||||
},
|
||||
"display": {
|
||||
"single": "Enkel",
|
||||
"slideshow": "Diavoorstelling"
|
||||
},
|
||||
"buttons": {
|
||||
"title": "Knoppen",
|
||||
"hint": "Maximaal twee knoppen. Het doel is een #anker op de pagina, een /pad op de site of een https://-adres.",
|
||||
"label": "Knop {{n}}: tekst",
|
||||
"target": "Knop {{n}}: doel"
|
||||
},
|
||||
"schedule": {
|
||||
"title": "Planning",
|
||||
"active": "Hero is aangezet",
|
||||
"starts": "Zichtbaar vanaf",
|
||||
"ends": "Zichtbaar tot",
|
||||
"hint": "Buiten de planning, of uitgezet, toont de website zijn eigen standaard-hero."
|
||||
},
|
||||
"slides": {
|
||||
"title": "Afbeeldingen",
|
||||
"add": "Afbeelding toevoegen",
|
||||
"uploading": "Bezig met uploaden…",
|
||||
"hint": "Upload een foto (JPEG, PNG, WebP en andere gangbare formaten, maximaal 10 MB). Zet het onderwerp goed met de knop Focus. De eerste afbeelding is de eerste die bezoekers zien.",
|
||||
"empty": "Nog geen afbeeldingen.",
|
||||
"alt": "Beschrijving van afbeelding {{n}} (alt-tekst)",
|
||||
"decorative": "Decoratief (geen beschrijving)",
|
||||
"active": "Tonen",
|
||||
"up": "Omhoog",
|
||||
"down": "Omlaag",
|
||||
"focus": "Focus instellen",
|
||||
"remove": "Verwijderen uit de hero",
|
||||
"ceiling": "Alleen de eerste {{max}} afbeeldingen worden getoond op de website."
|
||||
},
|
||||
"focus": {
|
||||
"title": "Focus en uitsnede",
|
||||
"intro": "Klik of sleep op de foto om aan te geven waar het onderwerp staat. De website snijdt de foto voor liggende (wide) en staande (tall) schermen zo uit dat het onderwerp in beeld blijft.",
|
||||
"targetLegend": "Voor welke weergave",
|
||||
"target": {
|
||||
"general": "Algemeen",
|
||||
"wide": "Liggend (3:2)",
|
||||
"tall": "Staand (4:5)"
|
||||
},
|
||||
"override": "Eigen instelling voor deze weergave",
|
||||
"areaLabel": "Foto: kies het punt van het onderwerp",
|
||||
"areaHint": "Pijltjestoetsen verplaatsen het punt (met Shift sneller).",
|
||||
"x": "Horizontaal (%)",
|
||||
"y": "Verticaal (%)",
|
||||
"zoom": "Inzoomen ({{value}}×)",
|
||||
"preview": {
|
||||
"wide": "Voorbeeld liggend",
|
||||
"tall": "Voorbeeld staand"
|
||||
},
|
||||
"savedToast": "Focus opgeslagen"
|
||||
},
|
||||
"errors": {
|
||||
"titleRequired": "Een titel is verplicht.",
|
||||
"titleTooLong": "De titel mag maximaal 200 tekens bevatten.",
|
||||
"titleTooManyLines": "De titel mag maximaal 5 regels hebben.",
|
||||
"taglineTooLong": "De tagline mag maximaal 120 tekens bevatten.",
|
||||
"leadTooLong": "De introductietekst mag maximaal 600 tekens bevatten.",
|
||||
"buttonLabelTooLong": "De knoptekst mag maximaal 50 tekens bevatten.",
|
||||
"buttonTargetTooLong": "Het doel mag maximaal 500 tekens bevatten.",
|
||||
"buttonIncomplete": "Vul zowel de tekst als het doel van de knop in, of laat beide leeg.",
|
||||
"buttonTargetInvalid": "Kies een #anker, een /pad of een https://-adres.",
|
||||
"altTooLong": "De beschrijving mag maximaal 300 tekens bevatten.",
|
||||
"altRequired": "Geef een beschrijving of markeer de afbeelding als decoratief.",
|
||||
"endAfterStart": "Het einde moet na het begin liggen."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,7 +129,9 @@ export class ApiClient {
|
||||
const { body, skipAuthRefresh: _skip, headers, ...rest } = options;
|
||||
const finalHeaders = new Headers(headers);
|
||||
|
||||
if (body !== undefined && body !== null) {
|
||||
// A FormData body (file upload) is sent as is: the browser sets the multipart content type and boundary.
|
||||
const isForm = typeof FormData !== 'undefined' && body instanceof FormData;
|
||||
if (body !== undefined && body !== null && !isForm) {
|
||||
finalHeaders.set('Content-Type', 'application/json');
|
||||
}
|
||||
if (this.accessToken !== null) {
|
||||
@@ -143,7 +145,7 @@ export class ApiClient {
|
||||
credentials: 'include',
|
||||
// A list read after a change must come from the server, never from an intermediate cache.
|
||||
...(rest.method === 'GET' ? { cache: 'no-store' as const } : {}),
|
||||
body: body !== undefined && body !== null ? JSON.stringify(body) : undefined,
|
||||
body: body !== undefined && body !== null ? (isForm ? (body as FormData) : JSON.stringify(body)) : undefined,
|
||||
});
|
||||
} catch (cause) {
|
||||
throw new NetworkError(cause instanceof Error ? cause.message : undefined);
|
||||
|
||||
@@ -7,9 +7,10 @@ import { cmsHandlers } from '@/features/cms/mocks/handlers';
|
||||
import { systemHandlers } from '@/features/system/mocks/handlers';
|
||||
import { offeringsHandlers } from '@/features/offerings/mocks/handlers';
|
||||
import { contactHandlers } from '@/features/contact/mocks/handlers';
|
||||
import { heroHandlers } from '@/features/hero/mocks/handlers';
|
||||
|
||||
/** All default MSW handlers, composed from feature folders (Q3-B). */
|
||||
export const handlers = [...authHandlers, ...userHandlers, ...setupHandlers, ...invitationHandlers, ...availabilityHandlers, ...cmsHandlers, ...systemHandlers, ...offeringsHandlers, ...contactHandlers];
|
||||
export const handlers = [...authHandlers, ...userHandlers, ...setupHandlers, ...invitationHandlers, ...availabilityHandlers, ...cmsHandlers, ...systemHandlers, ...offeringsHandlers, ...contactHandlers, ...heroHandlers];
|
||||
|
||||
export { authHandlers } from '@/features/auth/mocks/handlers';
|
||||
export { userHandlers } from '@/features/users/mocks/handlers';
|
||||
@@ -20,4 +21,5 @@ export { cmsHandlers, resetMockCmsInstances, getMockCmsInstances } from '@/featu
|
||||
export { systemHandlers } from '@/features/system/mocks/handlers';
|
||||
export { offeringsHandlers, resetMockOfferings, getMockOfferings } from '@/features/offerings/mocks/handlers';
|
||||
export { contactHandlers, resetMockContact, getMockContactMessages } from '@/features/contact/mocks/handlers';
|
||||
export { heroHandlers, resetMockHero } from '@/features/hero/mocks/handlers';
|
||||
export * from '@/features/auth/mocks/fixtures';
|
||||
|
||||
@@ -233,6 +233,18 @@ const cmsRoute = createRoute({
|
||||
),
|
||||
});
|
||||
|
||||
const heroRoute = createRoute({
|
||||
getParentRoute: () => authenticatedRoute,
|
||||
path: '/hero',
|
||||
component: () => (
|
||||
<RoleGuard allowedRoles={['Owner', 'Administrator']}>
|
||||
<ModuleGuard requiredModule="Hero">
|
||||
{lazyPage(() => import('@/features/hero/pages/HeroPage'), 'HeroPage')()}
|
||||
</ModuleGuard>
|
||||
</RoleGuard>
|
||||
),
|
||||
});
|
||||
|
||||
const offeringsRoute = createRoute({
|
||||
getParentRoute: () => authenticatedRoute,
|
||||
path: '/offerings',
|
||||
@@ -320,6 +332,7 @@ export const routeTree = rootRoute.addChildren([
|
||||
dashboardRoute,
|
||||
usersRoute,
|
||||
cmsRoute,
|
||||
heroRoute,
|
||||
offeringsRoute,
|
||||
offeringsNewRoute,
|
||||
offeringsEditRoute,
|
||||
|
||||
@@ -27,7 +27,7 @@ public class HeroGoldenTests
|
||||
// The expected files end with one newline that is not part of the HTML.
|
||||
private static string Expected(string file)
|
||||
{
|
||||
var text = File.ReadAllText(Path.Combine(Dir, file));
|
||||
var text = File.ReadAllText(Path.Combine(Dir, file)).Replace("\r\n", "\n");
|
||||
return text.EndsWith('\n') ? text[..^1] : text;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user