Merge origin/master into feature/messages-badge
Continuous Integration / config-asf (pull_request) Successful in 7s
Continuous Integration / config-sls (pull_request) Successful in 8s
Continuous Integration / changes (pull_request) Successful in 11s
Continuous Integration / backend-build (pull_request) Successful in 1m46s
Continuous Integration / compile-sites (pull_request) Successful in 1m51s
Continuous Integration / frontend-prepare (pull_request) Successful in 1m57s
Continuous Integration / vulnerability-scan (pull_request) Successful in 2m2s
Continuous Integration / frontend-build (pull_request) Successful in 43s
Continuous Integration / frontend-test (pull_request) Successful in 2m30s
Continuous Integration / backend-test (pull_request) Successful in 2m43s
Continuous Integration / frontend-lint (pull_request) Successful in 2m28s
Continuous Integration / publish-sls-test (pull_request) Skipped
Continuous Integration / publish-sls-production (pull_request) Skipped
Continuous Integration / deploy-sls-test (pull_request) Skipped
Continuous Integration / deploy-sls-production (pull_request) Skipped
Continuous Integration / publish-asf-test (pull_request) Skipped
Continuous Integration / deploy-asf-test (pull_request) Skipped
Continuous Integration / smoke-sls-test (pull_request) Skipped
Continuous Integration / smoke-asf-test (pull_request) Skipped

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 12:58:12 +01:00
co-authored by Claude Sonnet 5.5
180 changed files with 17199 additions and 193 deletions
+9 -1
View File
@@ -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';
@@ -30,6 +30,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,82 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import i18n from '@/i18n/config';
import { ThemeToggle } from './ThemeToggle';
const media = (dark: boolean) =>
vi.spyOn(window, 'matchMedia').mockImplementation(
() => ({ matches: dark, addEventListener: () => undefined, removeEventListener: () => undefined }) as unknown as MediaQueryList,
);
beforeEach(async () => {
localStorage.clear();
document.documentElement.className = '';
vi.restoreAllMocks();
await i18n.changeLanguage('nl');
});
describe('ThemeToggle', () => {
it.each([
['light', 'Thema: licht'],
['dark', 'Thema: donker'],
])('shows the CURRENT %s theme in its name (not the action)', (mode, name) => {
localStorage.setItem('cms-theme', mode);
media(false);
render(<ThemeToggle />);
const button = screen.getByTestId('theme-toggle');
expect(button).toHaveAccessibleName(name);
expect(button).toHaveAttribute('data-mode', mode);
expect(button).toHaveAttribute('title', name);
});
it('says in words what automatic currently is', () => {
media(true);
render(<ThemeToggle />);
expect(screen.getByTestId('theme-toggle')).toHaveAccessibleName('Thema: automatisch (nu donker)');
expect(screen.getByTestId('theme-toggle')).toHaveAttribute('data-mode', 'auto');
});
it('opens a menu with three options, the current one marked, and chooses with the keyboard', async () => {
media(false);
localStorage.setItem('cms-theme', 'light');
render(<ThemeToggle />);
screen.getByTestId('theme-toggle').focus();
await userEvent.keyboard('{Enter}');
expect(await screen.findByTestId('theme-option-light')).toHaveAttribute('aria-current', 'true');
expect(screen.getByTestId('theme-option-dark')).not.toHaveAttribute('aria-current');
expect(screen.getByTestId('theme-option-auto')).toHaveTextContent('Automatisch');
await userEvent.click(screen.getByTestId('theme-option-dark'));
expect(localStorage.getItem('cms-theme')).toBe('dark');
expect(document.documentElement.classList.contains('dark')).toBe(true);
expect(screen.getByTestId('theme-toggle')).toHaveAccessibleName('Thema: donker');
});
it('works on the first click: automatic to dark flips what is shown at once', async () => {
media(false);
render(<ThemeToggle />);
await userEvent.click(screen.getByTestId('theme-toggle'));
await userEvent.click(await screen.findByTestId('theme-option-dark'));
expect(document.documentElement.classList.contains('dark')).toBe(true);
expect(document.documentElement.classList.contains('light')).toBe(false);
});
it('has English texts too', async () => {
await i18n.changeLanguage('en');
media(true);
render(<ThemeToggle />);
expect(screen.getByTestId('theme-toggle')).toHaveAccessibleName('Theme: automatic (now dark)');
});
});
+58 -12
View File
@@ -1,20 +1,66 @@
import { Sun, Moon } from 'lucide-react';
import { Monitor, Moon, Sun } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useTheme } from '@/hooks/useTheme';
import {
DropdownMenu,
DropdownMenuCheck,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useTheme, type ThemeMode } from '@/hooks/useTheme';
const MODES: { mode: ThemeMode; icon: typeof Sun }[] = [
{ mode: 'light', icon: Sun },
{ mode: 'dark', icon: Moon },
{ mode: 'auto', icon: Monitor },
];
/**
* Three states: light, dark, automatic (follow the system). The button shows the CURRENT choice (sun = light, moon =
* dark, monitor = automatic), its name says it in words ("Theme: automatic (now dark)"), and a small menu with the three
* options (the current one marked) changes it.
*/
export function ThemeToggle() {
const { t } = useTranslation();
const { isDark, toggleTheme } = useTheme();
const { mode, theme, setMode } = useTheme();
const Icon = MODES.find((m) => m.mode === mode)!.icon;
const label =
mode === 'auto'
? t('theme.labelAuto', { now: t(`theme.mode.${theme}`).toLowerCase() })
: t('theme.label', { mode: t(`theme.mode.${mode}`).toLowerCase() });
return (
<button
type="button"
onClick={toggleTheme}
aria-label={isDark ? t('theme.switchToLight') : t('theme.switchToDark')}
data-testid="theme-toggle"
className="flex items-center justify-center rounded-md p-2 text-muted-foreground hover:bg-accent hover:text-accent-foreground"
>
{isDark ? <Sun className="size-4" /> : <Moon className="size-4" />}
</button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
aria-label={label}
title={label}
data-testid="theme-toggle"
data-mode={mode}
className="flex items-center justify-center rounded-md p-2 text-muted-foreground hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<Icon className="size-4" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
<DropdownMenuLabel>{t('theme.title')}</DropdownMenuLabel>
<DropdownMenuSeparator />
{MODES.map(({ mode: option, icon: OptionIcon }) => (
<DropdownMenuItem
key={option}
onSelect={() => setMode(option)}
aria-current={mode === option ? 'true' : undefined}
data-testid={`theme-option-${option}`}
>
<OptionIcon className="size-4" />
{t(`theme.mode.${option}`)}
<DropdownMenuCheck checked={mode === option} />
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}
@@ -0,0 +1,105 @@
import { describe, expect, it } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { useForm } from 'react-hook-form';
import { Checkbox, CheckboxField } from './checkbox';
import { Radio, RadioField, RadioGroup } from './radio';
describe('Checkbox', () => {
it('is a real checkbox: Space toggles it and the label is clickable', async () => {
render(<CheckboxField label="Uitgelicht" data-testid="box" />);
const box = screen.getByRole('checkbox', { name: 'Uitgelicht' });
box.focus();
await userEvent.keyboard(' ');
expect(box).toBeChecked();
await userEvent.click(screen.getByText('Uitgelicht'));
expect(box).not.toBeChecked();
});
it('shows the in-between state and does not change its value', () => {
render(<Checkbox aria-label="alles" indeterminate />);
const box = screen.getByRole('checkbox', { name: 'alles' }) as HTMLInputElement;
expect(box.indeterminate).toBe(true);
expect(box).not.toBeChecked();
});
it('can be disabled and marked invalid', async () => {
render(<Checkbox aria-label="x" disabled invalid />);
const box = screen.getByRole('checkbox', { name: 'x' });
expect(box).toBeDisabled();
expect(box).toHaveAttribute('aria-invalid', 'true');
await userEvent.click(box);
expect(box).not.toBeChecked();
});
it('draws with the colours of the theme (accent when checked, a visible border, a focus ring)', () => {
render(<Checkbox aria-label="x" />);
const cls = screen.getByRole('checkbox').className;
expect(cls).toContain('checked:bg-primary');
expect(cls).toContain('border-muted-foreground');
expect(cls).toContain('focus-visible:ring-ring');
expect(cls).toContain('forced-colors:checked:bg-[Highlight]');
});
it('works with react-hook-form register, like the native input it replaces', async () => {
function Form({ onSubmit }: { onSubmit: (v: { on: boolean }) => void }) {
const { register, handleSubmit } = useForm<{ on: boolean }>({ defaultValues: { on: false } });
return (
<form onSubmit={handleSubmit(onSubmit)}>
<CheckboxField label="Aan" {...register('on')} />
<button type="submit">go</button>
</form>
);
}
let saved: { on: boolean } | null = null;
render(
<Form
onSubmit={(v) => {
saved = v;
}}
/>,
);
await userEvent.click(screen.getByLabelText('Aan'));
await userEvent.click(screen.getByText('go'));
await screen.findByText('go');
expect(saved).toEqual({ on: true });
});
});
describe('Radio', () => {
it('is a real radio group: the arrow keys move and select, with a name for the group', async () => {
render(
<RadioGroup label="Weergave">
<RadioField name="d" value="single" label="Enkel" defaultChecked />
<RadioField name="d" value="slideshow" label="Diavoorstelling" />
</RadioGroup>,
);
expect(screen.getByRole('radiogroup', { name: 'Weergave' })).toBeInTheDocument();
const first = screen.getByRole('radio', { name: 'Enkel' });
const second = screen.getByRole('radio', { name: 'Diavoorstelling' });
first.focus();
await userEvent.keyboard('{ArrowDown}');
expect(second).toBeChecked();
expect(first).not.toBeChecked();
expect(second).toHaveFocus();
});
it('can be disabled and marked invalid, and uses theme colours', () => {
render(<Radio aria-label="r" name="g" value="a" disabled invalid />);
const radio = screen.getByRole('radio');
expect(radio).toBeDisabled();
expect(radio).toHaveAttribute('aria-invalid', 'true');
expect(radio.className).toContain('checked:border-primary');
expect(radio.className).toContain('forced-colors:checked:border-[Highlight]');
});
});
+77
View File
@@ -0,0 +1,77 @@
import * as React from 'react';
import { Check, Minus } from 'lucide-react';
import { cn } from '@/lib/utils';
export interface CheckboxProps extends Omit<React.ComponentProps<'input'>, 'type' | 'size'> {
/** The "some of them" state of a parent checkbox. It is shown with a minus; the value of the box itself does not change. */
indeterminate?: boolean;
/** The field has an error: a red border (and aria-invalid for screen readers). */
invalid?: boolean;
}
/**
* A real checkbox (a native input: Space toggles it, it works with a label, with react-hook-form's register and in forms),
* drawn in the colours of the theme: a clear border, the accent colour with a check mark when checked, a minus for the
* in-between state, hover, a focus ring, disabled and error states. The check mark is an icon over the input in the
* "primary foreground" colour; in forced-colors (high contrast) mode the system colours take over.
*/
export const Checkbox = React.forwardRef<HTMLInputElement, CheckboxProps>(
({ className, indeterminate = false, invalid = false, ...props }, forwardedRef) => {
const inner = React.useRef<HTMLInputElement | null>(null);
const setRef = (element: HTMLInputElement | null) => {
inner.current = element;
if (typeof forwardedRef === 'function') forwardedRef(element);
else if (forwardedRef) forwardedRef.current = element;
};
React.useEffect(() => {
if (inner.current) inner.current.indeterminate = indeterminate;
}, [indeterminate]);
return (
<span className="relative inline-flex size-5 shrink-0 items-center justify-center">
<input
ref={setRef}
type="checkbox"
aria-invalid={invalid || undefined}
className={cn(
'peer size-5 shrink-0 cursor-pointer appearance-none rounded border-2 border-muted-foreground bg-background transition-colors',
'hover:border-primary checked:border-primary checked:bg-primary indeterminate:border-primary indeterminate:bg-primary',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ring-offset-background',
'disabled:cursor-not-allowed disabled:opacity-50 aria-[invalid=true]:border-destructive',
'forced-colors:checked:bg-[Highlight] forced-colors:checked:border-[Highlight]',
className,
)}
{...props}
/>
<Check
className="pointer-events-none absolute size-3.5 text-primary-foreground opacity-0 peer-checked:opacity-100 peer-indeterminate:opacity-0 peer-disabled:opacity-50 forced-colors:text-[HighlightText]"
strokeWidth={3}
aria-hidden="true"
/>
<Minus
className="pointer-events-none absolute size-3.5 text-primary-foreground opacity-0 peer-indeterminate:opacity-100 peer-disabled:opacity-50 forced-colors:text-[HighlightText]"
strokeWidth={3}
aria-hidden="true"
/>
</span>
);
},
);
Checkbox.displayName = 'Checkbox';
interface CheckboxFieldProps extends CheckboxProps {
label: React.ReactNode;
}
/** A checkbox with its label: the whole line is clickable and at least 24 px high. */
export const CheckboxField = React.forwardRef<HTMLInputElement, CheckboxFieldProps>(({ label, id, disabled, ...props }, ref) => {
const generated = React.useId();
const inputId = id ?? generated;
return (
<label htmlFor={inputId} className={cn('inline-flex min-h-6 cursor-pointer items-center gap-2 py-0.5 text-sm', disabled && 'cursor-not-allowed opacity-70')}>
<Checkbox ref={ref} id={inputId} disabled={disabled} {...props} />
<span>{label}</span>
</label>
);
});
CheckboxField.displayName = 'CheckboxField';
+61
View File
@@ -0,0 +1,61 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
export interface RadioProps extends Omit<React.ComponentProps<'input'>, 'type' | 'size'> {
invalid?: boolean;
}
/**
* A real radio button (a native input: with the same name the arrow keys move and select inside the group, Space selects),
* drawn in the colours of the theme: a clear round border, the accent colour with a dot when selected, hover, a focus
* ring, disabled and error states, and system colours in forced-colors (high contrast) mode.
*/
export const Radio = React.forwardRef<HTMLInputElement, RadioProps>(({ className, invalid = false, ...props }, ref) => (
<span className="relative inline-flex size-5 shrink-0 items-center justify-center">
<input
ref={ref}
type="radio"
aria-invalid={invalid || undefined}
className={cn(
'peer size-5 shrink-0 cursor-pointer appearance-none rounded-full border-2 border-muted-foreground bg-background transition-colors',
'hover:border-primary checked:border-primary',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ring-offset-background',
'disabled:cursor-not-allowed disabled:opacity-50 aria-[invalid=true]:border-destructive',
'forced-colors:checked:border-[Highlight]',
className,
)}
{...props}
/>
<span
className="pointer-events-none absolute size-2.5 rounded-full bg-primary opacity-0 peer-checked:opacity-100 peer-disabled:opacity-50 forced-colors:bg-[Highlight]"
aria-hidden="true"
/>
</span>
));
Radio.displayName = 'Radio';
interface RadioFieldProps extends RadioProps {
label: React.ReactNode;
}
/** A radio button with its label: the whole line is clickable and at least 24 px high. */
export const RadioField = React.forwardRef<HTMLInputElement, RadioFieldProps>(({ label, id, disabled, ...props }, ref) => {
const generated = React.useId();
const inputId = id ?? generated;
return (
<label htmlFor={inputId} className={cn('inline-flex min-h-6 cursor-pointer items-center gap-2 py-0.5 text-sm', disabled && 'cursor-not-allowed opacity-70')}>
<Radio ref={ref} id={inputId} disabled={disabled} {...props} />
<span>{label}</span>
</label>
);
});
RadioField.displayName = 'RadioField';
/** The group around related radio buttons: role radiogroup with a name, so a screen reader announces what is chosen. */
export function RadioGroup({ label, className, children, ...props }: { label: string } & Omit<React.ComponentProps<'div'>, 'aria-label'>) {
return (
<div role="radiogroup" aria-label={label} className={cn('flex flex-wrap gap-x-6 gap-y-1', className)} {...props}>
{children}
</div>
);
}
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from 'vitest';
import html from '../index.html?raw';
import themeScript from '../public/theme-init.js?raw';
// The host sends Content-Security-Policy "script-src 'self'": an inline script in the admin page is blocked there, so the
// page must have none (the theme is set by /theme-init.js, a file of its own).
describe('the admin page and the Content-Security-Policy', () => {
it('has no inline script', () => {
const inline = [...html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].filter(([, attributes]) => !/\bsrc\s*=/.test(attributes));
expect(inline).toEqual([]);
});
it('sets the theme from a file of its own, before the app', () => {
expect(html.indexOf('src="/theme-init.js"')).toBeGreaterThan(-1);
expect(html.indexOf('src="/theme-init.js"')).toBeLessThan(html.indexOf('src="/src/main.tsx"'));
expect(themeScript).toContain("localStorage.getItem('cms-theme')");
expect(themeScript).toContain('classList.add');
});
it('has no inline event handlers or javascript: links either', () => {
expect(html).not.toMatch(/\son[a-z]+\s*=/i);
expect(html).not.toMatch(/javascript:/i);
});
});
@@ -0,0 +1,74 @@
import { Crop } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { WIDE, cropFor } from '../lib/focusMath';
import { mediaUrl } from '../lib/media';
import type { HeroFocusRequest, HeroImageDto } from '../services/types';
interface CropThumbnailProps {
image: HeroImageDto;
/** The small picture of the published (saved) crop. */
savedSrc: string;
/** A focus change that was applied in the dialog and is not saved yet: the thumbnail then shows that crop already. */
edit?: HeroFocusRequest;
onClick: () => void;
testId: string;
}
/**
* The picture of a slide, and at the same time the way to change its crop: a real button (so keyboard and screen reader
* users have it too). A hint with a crop icon and "Adjust crop" shows on hover and on keyboard focus, and a small crop
* icon is always there, so it can be found on a touch screen as well. After "Apply" in the dialog the thumbnail shows
* the new crop right away (the same calculation as the host) with a clear "not saved yet" note.
*/
export function CropThumbnail({ image, savedSrc, edit, onClick, testId }: CropThumbnailProps) {
const { t } = useTranslation();
const local = edit && image.previewSrc ? localCrop(image, edit) : null;
return (
<button
type="button"
onClick={onClick}
aria-label={t('hero.slides.cropEdit')}
className={`group relative block aspect-[3/2] w-28 shrink-0 cursor-pointer overflow-hidden rounded bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${edit ? 'ring-2 ring-amber-500' : ''}`}
data-testid={testId}
>
{local && image.previewSrc ? (
<img src={mediaUrl(image.previewSrc)} alt="" draggable={false} className="absolute max-w-none" style={local} data-testid={`${testId}-local`} />
) : (
<img src={savedSrc} alt="" draggable={false} className="h-full w-full object-cover" />
)}
{/* Always there, so it is found without hovering (touch screens). */}
<span className="pointer-events-none absolute right-1 top-1 rounded bg-black/55 p-1 text-white" aria-hidden="true">
<Crop className="size-3" />
</span>
{/* The explanation on hover and keyboard focus. */}
<span
className="pointer-events-none absolute inset-0 flex items-center justify-center gap-1 bg-black/55 px-1 text-center text-[11px] font-medium leading-tight text-white opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100 motion-reduce:transition-none"
aria-hidden="true"
>
<Crop className="size-4 shrink-0" />
{t('hero.slides.cropEdit')}
</span>
{edit && (
<span
className="pointer-events-none absolute inset-x-0 bottom-0 bg-amber-500 px-1 py-0.5 text-center text-[10px] font-medium leading-tight text-black"
data-testid={`${testId}-pending`}
>
{t('hero.slides.focusPending')}
</span>
)}
</button>
);
}
/** Places the whole picture in the box so exactly the crop of the host shows (the same calculation as the dialog). */
function localCrop(image: HeroImageDto, edit: HeroFocusRequest) {
const focus = edit.wide ?? edit.focus;
const crop = cropFor(image.width, image.height, WIDE, focus);
return {
width: `${(image.width / crop.width) * 100}%`,
left: `${(-crop.x / crop.width) * 100}%`,
// top is a percentage of the box height: the box width times denominator over numerator.
top: `${(-crop.y / crop.width) * (WIDE.numerator / WIDE.denominator) * 100}%`,
};
}
@@ -0,0 +1,251 @@
import { useRef, useState, type KeyboardEvent, type PointerEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
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 type { FocusDto, HeroFocusRequest, HeroImageDto } from '../services/types';
type Target = 'general' | 'wide' | 'tall';
interface FocusDialogProps {
/** The image to edit, with a not yet saved change of its focus already applied; null = closed. */
image: HeroImageDto | null;
/** Keeps the change locally: it is sent and made live when the hero is saved, and dropped when the page is left. */
onApply: (imageId: string, request: HeroFocusRequest) => void;
onClose: () => void;
}
export function FocusDialog({ image, onApply, 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} onApply={onApply} onClose={onClose} />}
</DialogContent>
</Dialog>
);
}
const percent = (fraction: number) => Math.round(fraction * 1000) / 10;
function FocusEditor({ image, onApply, onClose }: { image: HeroImageDto; onApply: (imageId: string, request: HeroFocusRequest) => void; onClose: () => void }) {
const { t } = useTranslation();
const area = useRef<HTMLDivElement>(null);
// The whole picture: image.src is already a crop of the wide shape and would be shown stretched and out of place.
const previewUrl = image.previewSrc ? mediaUrl(image.previewSrc) : 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 = () => {
onApply(image.id, { focus: general, wide, tall });
onClose();
};
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">
<p className="text-sm text-muted-foreground">{t('hero.focus.intro')}</p>
<p className="text-sm font-medium" data-testid="focus-apply-hint">{t('hero.focus.applyHint')}</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"
>
{previewUrl ? (
<img src={previewUrl} alt="" draggable={false} className="pointer-events-none absolute inset-0 h-full w-full object-cover" />
) : (
<p className="absolute inset-0 flex items-center justify-center bg-muted p-4 text-center text-sm text-muted-foreground" role="status" data-testid="focus-preview-pending">
{t('hero.focus.previewPending')}
</p>
)}
<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}`}
>
{previewUrl && <img
src={previewUrl}
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} data-testid="focus-save">
{t('hero.focus.apply')}
</Button>
</div>
</div>
);
}
@@ -0,0 +1,106 @@
import { useRef, type KeyboardEvent, type ReactNode } from 'react';
export interface HeroTab<Id extends string> {
id: Id;
label: ReactNode;
/** Short note after the label, for example "2 busy". */
note?: string;
/** There are unsaved changes in this tab: a dot and a text for screen readers. */
changed?: boolean;
changedText?: string;
/** This tab holds a field with an error: a red mark and a text for screen readers. */
invalid?: boolean;
invalidText?: string;
}
interface HeroTabsProps<Id extends string> {
label: string;
tabs: HeroTab<Id>[];
selected: Id;
onSelect: (id: Id) => void;
idPrefix: string;
}
/**
* Accessible tabs (role tablist, tab, tabpanel): the arrow keys move between the tabs (and select, "automatic activation"),
* Home and End go to the first and the last, only the selected tab is in the tab order. The panels themselves are rendered
* by the page, with <c>id="{idPrefix}-panel-{id}"</c> and <c>aria-labelledby="{idPrefix}-tab-{id}"</c>.
*/
export function HeroTabs<Id extends string>({ label, tabs, selected, onSelect, idPrefix }: HeroTabsProps<Id>) {
const refs = useRef<Record<string, HTMLButtonElement | null>>({});
const move = (index: number) => {
const next = tabs[(index + tabs.length) % tabs.length];
onSelect(next.id);
refs.current[next.id]?.focus();
};
const onKeyDown = (event: KeyboardEvent, index: number) => {
switch (event.key) {
case 'ArrowRight':
case 'ArrowDown':
event.preventDefault();
move(index + 1);
break;
case 'ArrowLeft':
case 'ArrowUp':
event.preventDefault();
move(index - 1);
break;
case 'Home':
event.preventDefault();
move(0);
break;
case 'End':
event.preventDefault();
move(tabs.length - 1);
break;
default:
}
};
return (
<div role="tablist" aria-label={label} className="flex gap-1 border-b" data-testid="hero-tabs">
{tabs.map((tab, index) => {
const active = tab.id === selected;
return (
<button
key={tab.id}
ref={(element) => {
refs.current[tab.id] = element;
}}
type="button"
role="tab"
id={`${idPrefix}-tab-${tab.id}`}
aria-selected={active}
aria-controls={`${idPrefix}-panel-${tab.id}`}
tabIndex={active ? 0 : -1}
onClick={() => onSelect(tab.id)}
onKeyDown={(event) => onKeyDown(event, index)}
className={`-mb-px inline-flex items-center gap-2 rounded-t-md border-b-2 px-4 py-2 text-sm font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${
active ? 'border-primary text-foreground' : 'border-transparent text-muted-foreground hover:text-foreground'
}`}
data-testid={`hero-tab-${tab.id}`}
>
{tab.label}
{tab.note && <span className="text-xs font-normal text-muted-foreground">({tab.note})</span>}
{tab.changed && (
<>
<span className="size-2 rounded-full bg-amber-500" aria-hidden="true" data-testid={`hero-tab-${tab.id}-changed`} />
<span className="sr-only">{tab.changedText}</span>
</>
)}
{tab.invalid && (
<>
<span className="inline-flex size-4 items-center justify-center rounded-full bg-destructive text-[10px] font-bold text-destructive-foreground" aria-hidden="true" data-testid={`hero-tab-${tab.id}-invalid`}>
!
</span>
<span className="sr-only">{tab.invalidText}</span>
</>
)}
</button>
);
})}
</div>
);
}
@@ -0,0 +1,156 @@
import { Check, Loader2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { useRetryHeroImage } from '../services/hooks';
import type { HeroImageDto } from '../services/types';
/** A spinner that stands still for people who asked for less motion. */
export function Spinner({ className = 'size-4' }: { className?: string }) {
return <Loader2 className={`${className} animate-spin motion-reduce:animate-none`} aria-hidden="true" />;
}
/**
* Shown above the form while photos of the saved hero are still being prepared in the background: how many are ready,
* what that means for the website, and a way to try again for a photo that failed.
*/
export function ProcessingStatus({ images }: { images: HeroImageDto[] }) {
const { t } = useTranslation();
const retry = useRetryHeroImage();
const total = images.length;
const waiting = images.filter((image) => image.processing);
if (waiting.length === 0) return null;
const done = total - waiting.length;
const failed = waiting.filter((image) => image.failed);
const working = waiting.length - failed.length;
// The photo the server is busy with right now, and how far along it is (a photo that waits has no step yet).
const busy = waiting.find((image) => image.renderTotal) ?? null;
const fraction = busy && busy.renderTotal ? (busy.renderDone ?? 0) / busy.renderTotal : 0;
const percent = total === 0 ? 0 : Math.min(100, ((done + fraction) / total) * 100);
return (
<div className="space-y-3 rounded-md border bg-muted/40 p-4" data-testid="hero-processing">
{working > 0 && (
<div className="space-y-2" role="status">
<p className="flex items-center gap-2 text-sm font-medium">
<Spinner />
<span data-testid="hero-processing-count">{t('hero.processing.count', { done, total })}</span>
</p>
<div
role="progressbar"
aria-label={t('hero.processing.label')}
aria-valuemin={0}
aria-valuemax={total}
aria-valuenow={done}
aria-valuetext={t('hero.processing.count', { done, total })}
className="h-2 w-full overflow-hidden rounded bg-muted"
data-testid="hero-processing-bar"
>
<div className="h-full bg-primary transition-all" style={{ width: `${percent}%` }} />
</div>
{busy && (
<p className="text-sm" data-testid="hero-processing-current">
{t('hero.processing.current', { n: done + 1, total, step: busy.renderDone ?? 0, steps: busy.renderTotal })}
</p>
)}
<p className="text-sm text-muted-foreground">{t('hero.processing.explain')}</p>
<p className="text-sm text-muted-foreground">
{t('hero.processing.stuck')}{' '}
<button
type="button"
className="underline underline-offset-2 hover:text-foreground disabled:opacity-50"
disabled={retry.isPending}
onClick={() => waiting.forEach((image) => retry.mutate(image.id))}
data-testid="hero-processing-retry-all"
>
{t('hero.processing.retry')}
</button>
</p>
</div>
)}
{failed.length > 0 && (
<div className="space-y-2" role="alert" data-testid="hero-processing-failed">
<p className="text-sm font-medium text-destructive">{t('hero.processing.failed', { count: failed.length })}</p>
<p className="text-sm text-muted-foreground">{t('hero.processing.failedHint')}</p>
<Button
type="button"
variant="outline"
size="sm"
disabled={retry.isPending}
onClick={() => failed.forEach((image) => retry.mutate(image.id))}
data-testid="hero-processing-retry"
>
{t('hero.processing.retry')}
</Button>
</div>
)}
</div>
);
}
/**
* The place of a photo that has no pictures yet: one calm shimmer (hidden from assistive technology) and a readable
* text. It lives in the row of the slide, so it stays mounted (and the animation keeps running) while the page asks the
* server again every few seconds, and it disappears when the photo is ready.
*/
export function PhotoPlaceholder({ failed, testId, step }: { failed: boolean; testId: string; step?: { done: number; total: number } | null }) {
const { t } = useTranslation();
return (
<div
className={`flex h-20 w-28 flex-col items-center justify-center gap-1 rounded p-1 text-center text-xs ${failed ? 'bg-destructive/10 text-destructive' : 'hero-shimmer bg-muted'}`}
role="status"
aria-busy={!failed}
title={t('hero.slides.processingHint')}
data-testid={testId}
>
{failed ? null : <Spinner className="size-3.5" />}
<span>{failed ? t('hero.slides.failed') : t('hero.slides.processing')}</span>
{!failed && step ? <span className="tabular-nums opacity-80" data-testid={`${testId}-step`}>{step.done}/{step.total}</span> : null}
{!failed && !step ? <span className="opacity-70" data-testid={`${testId}-queued`}>{t('hero.slides.queued')}</span> : null}
</div>
);
}
/**
* The photo of a slide whose crop is being made again (a changed focus point): the old picture stays visible underneath,
* with the same calm shimmer and a short text, so it is clear that the change is not on the website yet.
*/
export function RecutThumbnail({ src, failed, testId, step }: { src: string; failed: boolean; testId: string; step?: { done: number; total: number } | null }) {
const { t } = useTranslation();
return (
<div
className={`relative h-20 w-28 shrink-0 overflow-hidden rounded ${failed ? 'ring-2 ring-destructive' : 'hero-shimmer'}`}
role="status"
aria-busy={!failed}
title={t('hero.slides.recutHint')}
data-testid={testId}
>
<img src={src} alt="" className="h-full w-full object-cover" />
<span className={`absolute inset-x-0 bottom-0 flex items-center justify-center gap-1 px-1 py-0.5 text-center text-[10px] leading-tight ${failed ? 'bg-destructive text-destructive-foreground' : 'bg-background/85 text-foreground'}`}>
{failed ? null : <Spinner className="size-3" />}
<span>{failed ? t('hero.slides.failed') : t('hero.slides.recut')}</span>
{!failed && step ? <span className="tabular-nums opacity-80" data-testid={`${testId}-step`}>{step.done}/{step.total}</span> : null}
</span>
</div>
);
}
/**
* Per photo: shortly after its processing is done a check mark with "Processing finished" shows on that photo itself and
* fades away. The region is always there (empty) so a screen reader announces the text when it appears; the text names
* the slide. With reduced motion it does not fade but disappears after the same time.
*/
export function DoneStatus({ done, slideNumber, testId }: { done: boolean; slideNumber: number; testId: string }) {
const { t } = useTranslation();
return (
<div role="status" aria-live="polite" className="min-h-4 text-[11px] leading-tight" data-testid={testId}>
{done && (
<span className="hero-done inline-flex items-center gap-1 font-medium text-green-700 dark:text-green-400" data-testid={`${testId}-text`}>
<Check className="size-3.5" aria-hidden="true" />
<span className="sr-only">{t('hero.slides.doneFor', { n: slideNumber })}</span>
<span aria-hidden="true">{t('hero.slides.done')}</span>
</span>
)}
</div>
);
}
@@ -0,0 +1,33 @@
import { useTranslation } from 'react-i18next';
interface SlideSwitchProps {
checked: boolean;
onChange: (checked: boolean) => void;
testId: string;
/** What a screen reader says besides the visible text, so the switch is clearly about this slide. */
slideNumber: number;
}
/** A switch (role="switch") that turns a slide on or off; the text next to it says the current state. */
export function SlideSwitch({ checked, onChange, testId, slideNumber }: SlideSwitchProps) {
const { t } = useTranslation();
return (
<button
type="button"
role="switch"
aria-checked={checked}
onClick={() => onChange(!checked)}
className="flex items-center gap-2 rounded-md px-1 py-1 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
data-testid={testId}
>
<span
aria-hidden="true"
className={`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full border transition-colors ${checked ? 'border-primary bg-primary' : 'border-input bg-muted'}`}
>
<span className={`inline-block size-4 rounded-full bg-background shadow transition-transform motion-reduce:transition-none ${checked ? 'translate-x-[1.1rem]' : 'translate-x-0.5'}`} />
</span>
<span className="min-w-[4.5rem] text-left">{checked ? t('hero.slides.activeOn') : t('hero.slides.activeOff')}</span>
<span className="sr-only">{t('hero.slides.activeFor', { n: slideNumber })}</span>
</button>
);
}
@@ -0,0 +1,48 @@
import type { ReactNode } from 'react';
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { GripVertical } from 'lucide-react';
import { useTranslation } from 'react-i18next';
interface SortableSlideProps {
/** The id of the form field of this slide (stable while the order changes). */
id: string;
index: number;
/** A slide that is switched off is shown dimmed. */
dimmed?: boolean;
children: ReactNode;
}
/**
* One row of the image list that can be dragged by its handle (mouse, touch or keyboard: focus the handle, press Space,
* use the arrow keys, press Space again). The arrow buttons of the row stay as another way to change the order. While
* dragging, the row gets a frame and a shadow and the other rows make room, so it is clear where it will land.
*/
export function SortableSlide({ id, index, dimmed = false, children }: SortableSlideProps) {
const { t } = useTranslation();
const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = useSortable({ id });
return (
<li
ref={setNodeRef}
style={{ transform: CSS.Transform.toString(transform), transition, position: 'relative', zIndex: isDragging ? 10 : undefined }}
className={`flex flex-wrap items-start gap-3 rounded-md border bg-background p-3 ${isDragging ? 'shadow-lg ring-2 ring-primary' : ''} ${dimmed ? 'opacity-60' : ''}`}
data-testid={`hero-slide-${index}`}
data-dragging={isDragging ? 'true' : undefined}
data-inactive={dimmed ? 'true' : undefined}
>
<button
type="button"
ref={setActivatorNodeRef}
className="mt-1 cursor-grab touch-none rounded p-1 text-muted-foreground hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing"
aria-label={t('hero.slides.drag', { n: index + 1 })}
data-testid={`hero-slide-${index}-drag`}
{...attributes}
{...listeners}
>
<GripVertical className="size-5" aria-hidden="true" />
</button>
{children}
</li>
);
}
@@ -0,0 +1,37 @@
import { useBlocker } from '@tanstack/react-router';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
/**
* Asks for confirmation before the administrator leaves the page through the menu or a link while the form holds changes
* that are not saved. (Closing the tab or reloading is covered by the browser warning in the page itself.)
*/
export function UnsavedChangesGuard({ dirty }: { dirty: boolean }) {
const { t } = useTranslation();
const blocker = useBlocker({
shouldBlockFn: () => dirty,
disabled: !dirty,
enableBeforeUnload: false,
withResolver: true,
});
return (
<Dialog open={blocker.status === 'blocked'} onOpenChange={(open) => { if (!open) blocker.reset?.(); }}>
<DialogContent data-testid="hero-leave-dialog">
<DialogHeader>
<DialogTitle>{t('hero.unsaved.leaveTitle')}</DialogTitle>
<DialogDescription>{t('hero.unsaved.leaveText')}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button type="button" onClick={() => blocker.reset?.()} data-testid="hero-leave-stay">
{t('hero.unsaved.stay')}
</Button>
<Button type="button" variant="destructive" onClick={() => blocker.proceed?.()} data-testid="hero-leave-discard">
{t('hero.unsaved.discard')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,54 @@
import { AlertCircle, Check, Clock } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Spinner } from './ProcessingStatus';
export interface UploadItem {
key: number;
name: string;
status: 'waiting' | 'uploading' | 'done' | 'failed';
/** Why it failed, in words for the administrator. */
message?: string;
}
/** The files of the last choice, one row each: waiting, busy (spinner), added, or failed with the reason. */
export function UploadProgress({ items, busy, onClose }: { items: UploadItem[]; busy: boolean; onClose: () => void }) {
const { t } = useTranslation();
if (items.length === 0) return null;
const finished = items.filter((i) => i.status === 'done' || i.status === 'failed').length;
const added = items.filter((i) => i.status === 'done').length;
return (
<div className="space-y-2 rounded-md border p-3" data-testid="hero-upload-list" aria-busy={busy}>
<p className="text-sm font-medium" role="status" data-testid="hero-upload-summary">
{busy ? t('hero.upload.progress', { done: finished, total: items.length }) : t('hero.upload.summary', { ok: added, total: items.length })}
</p>
<ul className="space-y-1 text-sm">
{items.map((item) => (
<li key={item.key} className="flex items-start gap-2" data-testid={`hero-upload-item-${item.key}`} data-status={item.status}>
<span className="mt-0.5 shrink-0">
{item.status === 'uploading' && <Spinner />}
{item.status === 'waiting' && <Clock className="size-4 text-muted-foreground" aria-hidden="true" />}
{item.status === 'done' && <Check className="size-4 text-green-600" aria-hidden="true" />}
{item.status === 'failed' && <AlertCircle className="size-4 text-destructive" aria-hidden="true" />}
</span>
<span className="min-w-0 flex-1 break-words">
<span className="font-medium">{item.name}</span>
{' – '}
{item.status === 'failed' ? (
<span className="text-destructive" role="alert" data-testid="hero-upload-error">{item.message}</span>
) : (
<span className="text-muted-foreground">{t(`hero.upload.${item.status}`)}</span>
)}
</span>
</li>
))}
</ul>
{!busy && (
<Button type="button" variant="outline" size="sm" onClick={onClose} data-testid="hero-upload-close">
{t('hero.upload.close')}
</Button>
)}
</div>
);
}
@@ -0,0 +1,107 @@
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);
});
});
describe('the crop of both shapes for every kind of picture', () => {
// landscape 3:2, the two common cameras, portrait, square, a panorama and a very tall strip
const sources: [string, number, number][] = [
['landscape 3:2', 3000, 2000],
['landscape 4:3', 2048, 1536],
['portrait 2:3', 2000, 3000],
['square', 1500, 1500],
['panorama 3:1', 6000, 2000],
['tall strip 1:3', 800, 2400],
];
const points = [CENTRE, { x: 0, y: 0, zoom: 1 }, { x: 1, y: 1, zoom: 1 }, { x: 0.2, y: 0.8, zoom: 2 }, { x: 0.5, y: 0.5, zoom: 4 }];
it.each(sources)('%s: both crops have exactly their shape (to the pixel), lie inside the picture and keep the point', (_name, width, height) => {
for (const ratio of [WIDE, TALL]) {
for (const focus of points) {
const crop = cropFor(width, height, ratio, focus);
// One pixel of rounding at most: the crop is never stretched to another shape.
expect(Math.abs(crop.width * ratio.denominator - crop.height * ratio.numerator)).toBeLessThanOrEqual(Math.max(ratio.numerator, ratio.denominator));
expect(crop.x).toBeGreaterThanOrEqual(0);
expect(crop.y).toBeGreaterThanOrEqual(0);
expect(crop.x + crop.width).toBeLessThanOrEqual(width);
expect(crop.y + crop.height).toBeLessThanOrEqual(height);
}
}
});
it.each(sources)('%s: the preview box shows the crop at its own shape (no stretching)', (_name, width, height) => {
// The preview places the WHOLE picture inside a box of the crop shape: scale = box width / crop width, so the
// picture keeps its own shape when its height follows from its width.
for (const ratio of [WIDE, TALL]) {
const crop = cropFor(width, height, ratio, CENTRE);
const boxWidth = 100;
const scale = boxWidth / crop.width;
const pictureWidth = width * scale;
const pictureHeight = pictureWidth * (height / width);
const boxHeight = (boxWidth * ratio.denominator) / ratio.numerator;
// What is visible of the picture in the box is exactly the crop rectangle (same shape as the box).
const visibleWidth = boxWidth / (pictureWidth / width);
const visibleHeight = boxHeight / (pictureHeight / height);
expect(visibleWidth).toBeCloseTo(crop.width, 6);
expect(visibleHeight / visibleWidth).toBeCloseTo(ratio.denominator / ratio.numerator, 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 };
}
+4
View File
@@ -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,146 @@
import { http, HttpResponse } from 'msw';
import { API_BASE } from '@/features/auth/mocks/fixtures';
import type { HeroAdminDto, 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' },
],
processing: false,
failed: false,
previewSrc: '/media/hero/0123456789abcdef/full-1280.webp',
});
export const emptyHero = (): HeroAdminDto => ({
id: null,
title: '',
tagline: null,
lead: null,
display: 'single',
buttons: [],
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;
retried = [];
recutting = new Set();
};
export const setMockHero = (next: HeroAdminDto): void => {
hero = next;
images = Object.fromEntries(next.slides.map((s) => [s.imageId, s.image]));
};
let retried: string[] = [];
let recutting = new Set<string>();
/** The background work of the mock server is done: images whose crop was being made are ready. */
export const finishMockRecut = (): void => {
recutting.forEach((id) => {
if (images[id]) images[id] = { ...images[id], processing: false };
hero = { ...hero, slides: hero.slides.map((s) => (s.imageId === id ? { ...s, image: { ...s.image, processing: false } } : s)) };
});
recutting = new Set();
};
export const getRetriedImages = (): string[] => retried;
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);
// A changed focus takes effect with the save of the hero.
for (const edit of body.imageFocus ?? []) {
const current = images[edit.imageId] ?? hero.slides.find((s) => s.imageId === edit.imageId)?.image ?? seedImage(edit.imageId);
images[edit.imageId] = { ...current, focus: edit.focus, wideFocus: edit.wide, tallFocus: edit.tall, processing: true };
recutting.add(edit.imageId);
}
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,
isLive: 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.get(`${API_BASE}/api/v1/hero/images/limits`, () =>
HttpResponse.json({ formats: ['JPEG', 'PNG', 'GIF', 'BMP', 'TIFF', 'WebP', 'AVIF'], maxUploadBytes: 10 * 1024 * 1024, maxMegapixels: 64 }),
),
http.get(`${API_BASE}/api/v1/hero/images/:id`, ({ params }) => {
const image = images[String(params.id)];
return image ? HttpResponse.json(image) : new HttpResponse(null, { status: 404 });
}),
http.post(`${API_BASE}/api/v1/hero/images/:id/retry`, ({ params }) => {
retried.push(String(params.id));
return new HttpResponse(null, { status: 204 });
}),
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 });
}),
];
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,629 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useQueries } from '@tanstack/react-query';
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, ImagePlus, Trash2 } from 'lucide-react';
import { DndContext, KeyboardSensor, PointerSensor, closestCenter, useSensor, useSensors, type DragEndEvent } from '@dnd-kit/core';
import { SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy } from '@dnd-kit/sortable';
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 { CropThumbnail } from '../components/CropThumbnail';
import { DoneStatus, PhotoPlaceholder, ProcessingStatus, RecutThumbnail, Spinner } from '../components/ProcessingStatus';
import { SlideSwitch } from '../components/SlideSwitch';
import { SortableSlide } from '../components/SortableSlide';
import { HeroTabs } from '../components/HeroTabs';
import { UnsavedChangesGuard } from '../components/UnsavedChangesGuard';
import { UploadProgress, type UploadItem } from '../components/UploadProgress';
import { mediaUrl } from '../lib/media';
import { heroFormSchema, type HeroFormData } from '../schemas/hero';
import { heroImageQuery, useHero, useHeroUploadLimits, useSaveHero, useUploadHeroImage } from '../services/hooks';
import type { HeroAdminDto, HeroFocusRequest, 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,
slides: hero.slides.map((s) => ({ id: s.id, imageId: s.imageId, alt: s.alt, decorative: s.decorative, isActive: s.isActive })),
};
}
function toRequest(values: HeroFormData, focusEdits: Record<string, HeroFocusRequest>): 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 !== ''),
slides: values.slides.map((s) => ({ id: s.id, imageId: s.imageId, alt: s.decorative ? null : s.alt, decorative: s.decorative, isActive: s.isActive })),
imageFocus: Object.entries(focusEdits).map(([imageId, edit]) => ({ imageId, ...edit })),
};
}
/** 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 most the host accepts for one image (Media:MaxUploadBytes). */
const MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
/**
* What to tell the administrator when an upload fails: the message of the host when it sent one, a clear text for a
* refusal by the proxy (413, which has no JSON body) or a rate limit, and a retry hint when the connection broke off.
*/
function uploadMessage(error: unknown, t: (key: string, options?: Record<string, unknown>) => string): string {
if (error instanceof ProblemDetailsError) {
const message = error.problem.message;
if (typeof message === 'string' && message !== '') return message;
if (error.status === 413) return t('hero.upload.tooLarge', { max: MAX_UPLOAD_BYTES / (1024 * 1024) });
if (error.status === 429) return t('hero.upload.busy');
return t('errors.generic');
}
if (error instanceof NetworkError) return t('hero.upload.interrupted');
return t('errors.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>
<details className="max-w-3xl rounded-md border p-3 text-sm" data-testid="hero-help">
<summary className="cursor-pointer font-medium">{t('hero.help.heading')}</summary>
<dl className="mt-3 space-y-2">
{(['title', 'tagline', 'lead', 'buttons', 'display', 'slides', 'focus'] as const).map((key) => (
<div key={key}>
<dt className="font-medium">{t(`hero.help.${key}.name`)}</dt>
<dd className="text-muted-foreground">{t(`hero.help.${key}.text`)}</dd>
</div>
))}
</dl>
<p className="mt-3 text-muted-foreground">{t('hero.help.save')}</p>
</details>
{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 [uploads, setUploads] = useState<UploadItem[]>([]);
const [uploading, setUploading] = useState(false);
const [draggingFiles, setDraggingFiles] = useState(false);
const nextUploadKey = useRef(0);
const limits = useHeroUploadLimits().data;
const [localImages, setLocalImages] = useState<Record<string, HeroImageDto>>({});
const [focusImageId, setFocusImageId] = useState<string | null>(null);
// Changed focus points are kept here until the hero is saved: they are sent with the save and dropped when the page is left.
const [focusEdits, setFocusEdits] = useState<Record<string, HeroFocusRequest>>({});
const fileInput = useRef<HTMLInputElement>(null);
const {
register,
setValue,
handleSubmit,
control,
formState: { errors, isDirty, dirtyFields },
setFocus,
reset,
} = useForm<HeroFormData>({ resolver: zodResolver(heroFormSchema), mode: 'onTouched', shouldFocusError: false, defaultValues: toForm(hero) });
const slides = useFieldArray({ control, name: 'slides' });
const watchedSlides = useWatch({ control, name: 'slides' }) ?? [];
// The two tabs share one form, one Save button and one "unsaved changes" state. The chosen tab is remembered for this
// browser session.
type TabId = 'content' | 'images';
const [tab, setTabState] = useState<TabId>(() => {
try {
return window.sessionStorage.getItem('cms-hero-tab') === 'images' ? 'images' : 'content';
} catch {
return 'content';
}
});
const setTab = (next: TabId) => {
setTabState(next);
try {
window.sessionStorage.setItem('cms-hero-tab', next);
} catch {
// Remembering the tab is a convenience only.
}
};
// After a failed save: go to the tab of the first field with an error and put the cursor in that field.
const pendingFocus = useRef<{ name: string; tab: TabId } | null>(null);
useEffect(() => {
if (pendingFocus.current && tab === pendingFocus.current.tab) {
setFocus(pendingFocus.current.name as never);
pendingFocus.current = null;
}
}, [tab, setFocus]);
const goToField = (name: string, target: TabId) => {
if (target === tab) {
setFocus(name as never);
return;
}
pendingFocus.current = { name, tab: target };
setTab(target);
};
// The images of the saved hero (always current: a change of focus refreshes them) plus the ones uploaded in this session.
// Photos uploaded here and not saved yet are not in the saved hero: they are asked for one by one until they are ready,
// so a photo that is finished never stays "processing" because nothing refreshed it.
const unsavedIds = useMemo(
() => Object.keys(localImages).filter((id) => !hero.slides.some((s) => s.imageId === id)),
[hero.slides, localImages],
);
const polled = useQueries({
queries: unsavedIds.map((id) => heroImageQuery(id)),
combine: (results) => results.map((r) => r.data),
});
const images = useMemo(() => {
const map: Record<string, HeroImageDto> = { ...localImages };
for (const image of polled) if (image) map[image.id] = image;
for (const s of hero.slides) map[s.imageId] = s.image;
return map;
}, [hero.slides, localImages, polled]);
// Per photo: when its processing is done it shows "Processing finished" for a few seconds, and can be worked on at once.
// A photo that was ready at once (the same photo was already in the CMS) shows the same note, without a placeholder.
const [justDone, setJustDone] = useState<Record<string, true>>({});
const wasProcessing = useRef<Record<string, boolean>>({});
const markDone = (imageId: string) => {
setJustDone((current) => ({ ...current, [imageId]: true }));
window.setTimeout(() => {
setJustDone((current) => {
const { [imageId]: _removed, ...rest } = current;
return rest;
});
}, 4500);
};
useEffect(() => {
for (const field of slides.fields) {
const image = images[field.imageId];
if (!image) continue;
if (image.processing) {
wasProcessing.current[image.id] = true;
} else if (wasProcessing.current[image.id]) {
wasProcessing.current[image.id] = false;
markDone(image.id);
}
}
}, [images, slides.fields]);
// A focus change counts as unsaved only while it differs from what is saved (applying the old point again is no change).
const samePoint = (a: unknown, b: unknown) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
const hasPendingFocus = Object.entries(focusEdits).some(([imageId, edit]) => {
const saved = images[imageId];
return !saved || !samePoint(saved.focus, edit.focus) || !samePoint(saved.wideFocus, edit.wide) || !samePoint(saved.tallFocus, edit.tall);
});
// The form is compared with the last saved state (react-hook-form keeps it), so a change that is undone no longer counts.
// Photos still being prepared on the server and the background refresh are not changes of the administrator.
const hasUnsaved = isDirty || hasPendingFocus;
const contentChanged = Object.keys(dirtyFields).some((key) => key !== 'slides');
const imagesChanged = Boolean(dirtyFields.slides?.some?.(Boolean)) || hasPendingFocus;
const contentInvalid = Object.keys(errors).some((key) => key !== 'slides');
const imagesInvalid = Boolean(errors.slides);
const busyCount = slides.fields.filter((f) => images[f.imageId]?.processing).length;
useEffect(() => {
if (!hasUnsaved) return undefined;
const warn = (event: BeforeUnloadEvent) => {
event.preventDefault();
};
window.addEventListener('beforeunload', warn);
return () => window.removeEventListener('beforeunload', warn);
}, [hasUnsaved]);
// The image as the dialog shows it: the saved one with a not yet saved change of its focus applied.
const withPendingFocus = (image: HeroImageDto | null): HeroImageDto | null => {
const edit = image ? focusEdits[image.id] : undefined;
return image && edit ? { ...image, focus: edit.focus, wideFocus: edit.wide, tallFocus: edit.tall } : image;
};
// Up to this many files go to the host at the same time; the variants are cut in the background, so an upload itself
// is quick, and two at a time keeps the memory use of a small server in check.
const UPLOAD_PARALLEL = 2;
const onFiles = async (chosen: FileList | File[] | null) => {
const files = Array.from(chosen ?? []);
if (files.length === 0 || uploading) return;
const maxBytes = limits?.maxUploadBytes ?? MAX_UPLOAD_BYTES;
const maxMb = Math.round(maxBytes / (1024 * 1024));
const items: UploadItem[] = files.map((file) => ({ key: nextUploadKey.current++, name: file.name, status: 'waiting' }));
setUploads(items);
setUploading(true);
const update = (i: number, patch: Partial<UploadItem>) =>
setUploads((current) => current.map((u) => (u.key === items[i].key ? { ...u, ...patch } : u)));
// The images are added to the list in the order they were chosen, whichever upload finishes first.
const results: (HeroImageDto | 'failed' | undefined)[] = new Array<HeroImageDto | 'failed' | undefined>(files.length).fill(undefined);
let flushed = 0;
let cursor = 0;
const flush = () => {
while (flushed < files.length && results[flushed] !== undefined) {
const result = results[flushed];
if (result && result !== 'failed') {
setLocalImages((current) => ({ ...current, [result.id]: result }));
// Ready at once (the same photo was already in the CMS): the same note as after a photo that took a while.
if (!result.processing) markDone(result.id);
slides.append({ id: null, imageId: result.id, alt: '', decorative: false, isActive: true }, { shouldFocus: false });
}
flushed += 1;
}
};
const worker = async () => {
while (cursor < files.length) {
const i = cursor++;
const file = files[i];
// Refuse what the host would refuse without sending the whole file first.
if (file.type !== '' && !file.type.startsWith('image/')) {
results[i] = 'failed';
update(i, { status: 'failed', message: t('hero.upload.notAnImage') });
} else if (file.size > maxBytes) {
results[i] = 'failed';
update(i, { status: 'failed', message: t('hero.upload.tooLarge', { max: maxMb }) });
} else {
update(i, { status: 'uploading' });
try {
const image = await upload.mutateAsync(file);
results[i] = image;
update(i, { status: 'done' });
} catch (error) {
results[i] = 'failed';
update(i, { status: 'failed', message: uploadMessage(error, t) });
}
}
flush();
}
};
try {
await Promise.all(Array.from({ length: Math.min(UPLOAD_PARALLEL, files.length) }, () => worker()));
} finally {
setUploading(false);
if (fileInput.current) fileInput.current.value = '';
}
};
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
);
// The order changes in the form only; it goes live when the hero is saved, like every other change.
const onDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
if (!over || active.id === over.id) return;
const from = slides.fields.findIndex((f) => f.id === active.id);
const to = slides.fields.findIndex((f) => f.id === over.id);
if (from !== -1 && to !== -1) slides.move(from, to);
};
const isFileDrag = (event: React.DragEvent) => Array.from(event.dataTransfer?.types ?? []).includes('Files');
const onSubmit = async (values: HeroFormData) => {
setServerError(null);
try {
const savedHero = await save.mutateAsync(toRequest(values, focusEdits));
setFocusEdits({});
// What was just saved is the new starting point: nothing is unsaved any more.
reset(toForm(savedHero));
toast.success(t('hero.savedToast'));
} catch (error) {
setServerError(serverMessage(error, t('errors.generic'), t('errors.network')));
}
};
const onInvalid = (formErrors: typeof errors) => {
const order = ['title', 'tagline', 'lead', 'display', 'buttons', 'slides'] as const;
for (const key of order) {
const entry = formErrors[key] as unknown;
if (!entry) continue;
if (Array.isArray(entry)) {
const index = entry.findIndex(Boolean);
const field = Object.keys(entry[index] ?? {})[0] ?? 'alt';
goToField(`${key}.${index}.${field}`, key === 'slides' ? 'images' : 'content');
} else {
goToField(key, 'content');
}
return;
}
};
const err = (message?: string) => (message ? t(message) : undefined);
const heroErrors = errors;
return (
<form onSubmit={(event) => void handleSubmit(onSubmit, onInvalid)(event)} className="space-y-8 pb-4" noValidate data-testid="hero-form">
<ProcessingStatus images={slides.fields.map((f) => images[f.imageId]).filter((image): image is HeroImageDto => image !== undefined)} />
<FormErrorBanner error={serverError !== null ? { message: serverError } : null} onDismiss={() => setServerError(null)} />
<HeroTabs
idPrefix="hero"
label={t('hero.tabs.label')}
selected={tab}
onSelect={setTab}
tabs={[
{ id: 'content', label: t('hero.tabs.content'), changed: contentChanged, changedText: t('hero.tabs.hasChanges'), invalid: contentInvalid, invalidText: t('hero.tabs.hasErrors') },
{
id: 'images',
label: t('hero.tabs.images'),
note: busyCount > 0 ? t('hero.tabs.busy', { count: busyCount }) : undefined,
changed: imagesChanged,
changedText: t('hero.tabs.hasChanges'),
invalid: imagesInvalid,
invalidText: t('hero.tabs.hasErrors'),
},
]}
/>
<div role="tabpanel" id="hero-panel-content" aria-labelledby="hero-tab-content" hidden={tab !== 'content'} className="space-y-8">
<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>
</div>
<div role="tabpanel" id="hero-panel-images" aria-labelledby="hero-tab-images" hidden={tab !== 'images'}>
<section
className={`space-y-3 rounded-md ${draggingFiles ? 'ring-2 ring-primary ring-offset-4' : ''}`}
onDragOver={(event) => {
if (!isFileDrag(event)) return;
event.preventDefault();
setDraggingFiles(true);
}}
onDragLeave={(event) => {
if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setDraggingFiles(false);
}}
onDrop={(event) => {
if (!isFileDrag(event)) return;
event.preventDefault();
setDraggingFiles(false);
void onFiles(event.dataTransfer.files);
}}
data-testid="hero-slides-section"
>
<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/*"
multiple
className="sr-only"
aria-label={t('hero.slides.add')}
data-testid="hero-upload"
onChange={(event) => void onFiles(event.target.files)}
/>
<Button type="button" variant="outline" disabled={uploading} onClick={() => fileInput.current?.click()} data-testid="hero-upload-button">
<ImagePlus className="mr-2 size-4" aria-hidden="true" />
{uploading ? t('hero.slides.uploading') : t('hero.slides.add')}
</Button>
</div>
</div>
<p className="text-xs text-muted-foreground">{t('hero.slides.hint')}</p>
{limits && (
<p className="text-xs text-muted-foreground" data-testid="hero-upload-limits">
{t('hero.slides.limits', { formats: limits.formats.join(', '), size: Math.round(limits.maxUploadBytes / (1024 * 1024)), megapixels: limits.maxMegapixels })}
</p>
)}
<UploadProgress items={uploads} busy={uploading} onClose={() => setUploads([])} />
{slides.fields.length === 0 && <p className="text-sm text-muted-foreground" data-testid="hero-slides-empty">{t('hero.slides.empty')}</p>}
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={onDragEnd}
accessibility={{ screenReaderInstructions: { draggable: t('hero.slides.dragInstructions') } }}
>
<SortableContext items={slides.fields.map((f) => f.id)} strategy={verticalListSortingStrategy}>
<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 (
<SortableSlide key={field.id} id={field.id} index={index} dimmed={!(watchedSlides[index]?.isActive ?? true)}>
<div className="flex shrink-0 flex-col gap-1">
{image && image.variants.length === 0 ? (
<PhotoPlaceholder failed={image.failed} testId={`hero-slide-${index}-processing`} step={image.renderTotal ? { done: image.renderDone ?? 0, total: image.renderTotal } : null} />
) : image?.processing ? (
<RecutThumbnail src={thumbnail(image)} failed={image.failed} testId={`hero-slide-${index}-recut`} step={image.renderTotal ? { done: image.renderDone ?? 0, total: image.renderTotal } : null} />
) : image ? (
<CropThumbnail
image={image}
savedSrc={thumbnail(image)}
edit={focusEdits[field.imageId]}
onClick={() => setFocusImageId(field.imageId)}
testId={`hero-slide-${index}-focus`}
/>
) : (
<div className="flex h-20 w-28 items-center justify-center rounded bg-muted text-xs">?</div>
)}
<DoneStatus done={Boolean(image && justDone[image.id] && !image.processing)} slideNumber={index + 1} testId={`hero-slide-${index}-done`} />
</div>
<div className="min-w-[12rem] flex-1 space-y-2" role="group" aria-labelledby={`hero-slide-title-${field.id}`}>
<h3 id={`hero-slide-title-${field.id}`} className="text-xs font-medium uppercase tracking-wide text-muted-foreground" data-testid={`hero-slide-${index}-title`}>
{t('hero.slides.number', { n: index + 1 })}
</h3>
<Label htmlFor={`hero-slide-${index}-alt`}>{t('hero.slides.alt')}</Label>
<Input id={`hero-slide-${index}-alt`} maxLength={300} disabled={decorative} aria-describedby={`hero-slide-${index}-alt-hint`} data-testid={`hero-slide-${index}-alt`} {...register(`slides.${index}.alt` as const)} />
<p id={`hero-slide-${index}-alt-hint`} className="text-xs text-muted-foreground">{t('hero.slides.altHint')}</p>
<FieldError message={err(heroErrors.slides?.[index]?.alt?.message)} testId={`hero-slide-${index}-alt-error`} />
<label className="flex items-center gap-2 text-sm">
<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>
</div>
<div className="flex flex-wrap items-center gap-1">
<SlideSwitch
checked={watchedSlides[index]?.isActive ?? true}
onChange={(value) => setValue(`slides.${index}.isActive` as const, value, { shouldDirty: true })}
testId={`hero-slide-${index}-active`}
slideNumber={index + 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="destructive" size="icon" aria-label={t('hero.slides.remove')} title={t('hero.slides.remove')} onClick={() => slides.remove(index)} data-testid={`hero-slide-${index}-remove`}>
<Trash2 className="size-4" aria-hidden="true" />
</Button>
</div>
</SortableSlide>
);
})}
</ol>
</SortableContext>
</DndContext>
{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>
<UnsavedChangesGuard dirty={hasUnsaved} />
{/* Full width of the content area (no gap at the sides or below), opaque, with a clear top edge and a shadow; the
bottom padding keeps clear of the home bar of a phone. */}
<div
className="sticky bottom-0 z-20 -mx-6 -mb-6 flex flex-wrap items-center justify-end gap-3 border-t bg-background px-6 pt-3 shadow-[0_-4px_8px_-4px_rgba(0,0,0,0.15)]"
style={{ paddingBottom: 'calc(0.75rem + env(safe-area-inset-bottom))' }}
data-testid="hero-save-bar"
>
<div role="status" aria-live="polite" className="min-h-5 flex-1 text-sm" data-testid="hero-unsaved-region">
{hasUnsaved && (
<span className="inline-flex items-center gap-2" data-testid="hero-unsaved">
<Badge variant="secondary">{t('hero.unsaved.badge')}</Badge>
<span className="text-muted-foreground">{t('hero.unsaved.text')}</span>
</span>
)}
</div>
<Button
type="submit"
disabled={save.isPending || !hasUnsaved}
aria-disabled={save.isPending || !hasUnsaved}
aria-busy={save.isPending}
className={hasUnsaved && !save.isPending ? 'ring-2 ring-primary ring-offset-2' : undefined}
data-testid="hero-save"
>
{save.isPending ? (
<>
<Spinner className="mr-2 size-4" />
{t('hero.saving')}
</>
) : (
t('common.save')
)}
</Button>
</div>
<FocusDialog
image={withPendingFocus(focusImageId ? images[focusImageId] ?? null : null)}
onApply={(imageId, edit) => setFocusEdits((current) => ({ ...current, [imageId]: edit }))}
onClose={() => setFocusImageId(null)}
/>
</form>
);
}
@@ -0,0 +1,48 @@
import { describe, expect, it } from 'vitest';
import { heroFormSchema, isAllowedButtonTarget } 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: '' }],
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);
});
});
@@ -0,0 +1,73 @@
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),
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' });
}
});
export type HeroFormData = z.infer<typeof heroFormSchema>;
@@ -0,0 +1,70 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api-client';
import type { HeroAdminDto, HeroImageDto, HeroSaveRequest, HeroUploadLimits } 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'),
// Images are cut in the background after an upload or a saved focus change: look again until they are all ready.
refetchInterval: (query) => (query.state.data?.slides.some((s) => s.image.processing) ? 5000 : false),
// Also while the tab is in the background or the connection came back: the state must never stay stale.
refetchIntervalInBackground: true,
});
}
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 useDeleteHeroImage() {
return useMutation<void, Error, string>({
mutationFn: (imageId) => api.delete<void>(`/api/v1/hero/images/${imageId}`),
});
}
/** Asks the server to try an image again that the background renderer gave up on. */
export function useRetryHeroImage() {
const queryClient = useQueryClient();
return useMutation<void, Error, string>({
mutationFn: (imageId) => api.post<void>(`/api/v1/hero/images/${imageId}/retry`, {}),
onSuccess: () => queryClient.invalidateQueries({ queryKey: HERO_KEY }),
});
}
/** The formats and limits an upload has to meet on this host. */
export function useHeroUploadLimits() {
return useQuery<HeroUploadLimits, Error>({
queryKey: ['hero', 'upload-limits'],
queryFn: () => api.get<HeroUploadLimits>('/api/v1/hero/images/limits'),
staleTime: 10 * 60 * 1000,
});
}
/** The query of one image: the page asks it for photos that were uploaded but not saved yet, until they are ready. */
export const heroImageQuery = (imageId: string) => ({
queryKey: ['hero', 'image', imageId],
queryFn: () => api.get<HeroImageDto>(`/api/v1/hero/images/${imageId}`),
refetchInterval: (query: { state: { data?: HeroImageDto } }) => (query.state.data?.processing ? 5000 : false),
refetchIntervalInBackground: true,
});
@@ -0,0 +1,100 @@
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[];
/** The variants of this image are still being cut in the background; it is not published yet. */
processing: boolean;
/** The background renderer gave up on this image after a few tries; it can be retried. */
failed: boolean;
/** While the image is being cut: the step it is at, out of how many (null when it is not being cut right now). */
renderDone?: number | null;
renderTotal?: number | null;
/** The whole picture (not cut around a point), for choosing the focus point; null while the server has not made it yet. */
previewSrc?: string | null;
/** The photo was already in the CMS (same bytes). For internal use: the administrator sees no difference. */
reused?: boolean;
}
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[];
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[];
slides: HeroSlideRequest[];
/** Changed focus points of images; they take effect with this save. */
imageFocus: HeroImageFocusRequest[];
}
export interface HeroImageFocusRequest extends HeroFocusRequest {
imageId: string;
}
export interface HeroFocusRequest {
focus: FocusDto;
wide: FocusDto | null;
tall: FocusDto | null;
}
export interface HeroUploadLimits {
formats: string[];
maxUploadBytes: number;
maxMegapixels: number;
}
@@ -5,6 +5,7 @@ import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { CheckboxField } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { FieldError } from '@/components/ui/FieldError';
import { FormErrorBanner } from '@/components/ui/FormErrorBanner';
@@ -211,16 +212,12 @@ function OfferingBannerForm({
</div>
<p className="text-xs text-muted-foreground">{t('offerings.banners.scheduleHint')}</p>
<div className="flex items-center gap-2">
<input
id="banner-active"
type="checkbox"
data-testid="banner-active"
className="size-4 rounded border-input"
{...register('isActive')}
/>
<Label htmlFor="banner-active">{t('offerings.banners.activeLabel')}</Label>
</div>
<CheckboxField
id="banner-active"
data-testid="banner-active"
label={t('offerings.banners.activeLabel')}
{...register('isActive')}
/>
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" onClick={onClose} data-testid="banner-cancel">
@@ -5,6 +5,7 @@ import { useTranslation } from 'react-i18next';
import { Check, Pencil, Plus, Trash2, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { CheckboxField } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { FieldError } from '@/components/ui/FieldError';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
@@ -293,28 +294,20 @@ export function OfferingForm({ initialValues, onSubmit, onCancel, isSubmitting }
{errors.ctaLabel && <FieldError message={errors.ctaLabel.message} testId="offering-cta-label-error" />}
</div>
<div className="flex items-center gap-2">
<input
id="offering-featured"
type="checkbox"
data-testid="offering-featured"
className="size-4 rounded border-input"
{...register('featured')}
/>
<Label htmlFor="offering-featured">{t('offerings.form.featuredLabel')}</Label>
</div>
<CheckboxField
id="offering-featured"
data-testid="offering-featured"
label={t('offerings.form.featuredLabel')}
{...register('featured')}
/>
<div className="space-y-3 rounded-md border p-3" data-testid="offering-schedule">
<div className="flex items-center gap-2">
<input
id="offering-active"
type="checkbox"
data-testid="offering-active"
className="size-4 rounded border-input"
{...register('isActive')}
/>
<Label htmlFor="offering-active">{t('offerings.form.activeLabel')}</Label>
</div>
<CheckboxField
id="offering-active"
data-testid="offering-active"
label={t('offerings.form.activeLabel')}
{...register('isActive')}
/>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="offering-starts">{t('offerings.form.startsLabel')}</Label>
@@ -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',
}),
+105 -62
View File
@@ -2,6 +2,33 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import { useTheme } from './useTheme';
type Listener = () => void;
/** A matchMedia that can change its answer and tell its listeners, like the system preference does. */
function system(initialDark: boolean) {
let dark = initialDark;
const listeners = new Set<Listener>();
vi.spyOn(window, 'matchMedia').mockImplementation(
() =>
({
get matches() {
return dark;
},
addEventListener: (_: string, l: Listener) => listeners.add(l),
removeEventListener: (_: string, l: Listener) => listeners.delete(l),
}) as unknown as MediaQueryList,
);
return {
change(next: boolean) {
dark = next;
listeners.forEach((l) => l());
},
listenerCount: () => listeners.size,
};
}
const shown = () => (document.documentElement.classList.contains('dark') ? 'dark' : 'light');
beforeEach(() => {
localStorage.clear();
document.documentElement.className = '';
@@ -9,96 +36,112 @@ beforeEach(() => {
});
describe('useTheme', () => {
it('defaults to light when no preference is stored and OS prefers light', () => {
vi.spyOn(window, 'matchMedia').mockReturnValue({ matches: false } as MediaQueryList);
it('is automatic when nothing is stored, and follows the system', () => {
system(true);
const { result } = renderHook(() => useTheme());
expect(result.current.theme).toBe('light');
expect(result.current.isDark).toBe(false);
});
it('defaults to dark when OS prefers dark and nothing is stored', () => {
vi.spyOn(window, 'matchMedia').mockReturnValue({ matches: true } as MediaQueryList);
const { result } = renderHook(() => useTheme());
expect(result.current.mode).toBe('auto');
expect(result.current.theme).toBe('dark');
expect(result.current.isDark).toBe(true);
expect(shown()).toBe('dark');
});
it('uses stored localStorage value over OS preference', () => {
localStorage.setItem('cms-theme', 'dark');
vi.spyOn(window, 'matchMedia').mockReturnValue({ matches: false } as MediaQueryList);
const { result } = renderHook(() => useTheme());
expect(result.current.theme).toBe('dark');
});
it('toggleTheme switches from light to dark', () => {
localStorage.setItem('cms-theme', 'light');
const { result } = renderHook(() => useTheme());
act(() => { result.current.toggleTheme(); });
expect(result.current.theme).toBe('dark');
expect(localStorage.getItem('cms-theme')).toBe('dark');
expect(document.documentElement.classList.contains('dark')).toBe(true);
});
it('toggleTheme switches from dark to light', () => {
localStorage.setItem('cms-theme', 'dark');
const { result } = renderHook(() => useTheme());
act(() => { result.current.toggleTheme(); });
expect(result.current.theme).toBe('light');
expect(localStorage.getItem('cms-theme')).toBe('light');
expect(document.documentElement.classList.contains('light')).toBe(true);
});
});
describe('first click', () => {
const media = (dark: boolean) => vi.spyOn(window, 'matchMedia').mockReturnValue({ matches: dark } as MediaQueryList);
const shown = () => (document.documentElement.classList.contains('dark') ? 'dark' : 'light');
it.each([
['light', 'dark'],
['dark', 'light'],
])('flips the shown theme straight away when the OS prefers %s and nothing is stored or applied', (os, expected) => {
media(os === 'dark');
['light', true, 'light'],
['dark', false, 'dark'],
])('a stored %s wins over the system (dark=%s)', (stored, osDark, expected) => {
localStorage.setItem('cms-theme', stored);
system(osDark);
const { result } = renderHook(() => useTheme());
expect(shown()).toBe(os);
act(() => { result.current.toggleTheme(); });
expect(shown()).toBe(expected);
expect(result.current.mode).toBe(stored);
expect(result.current.theme).toBe(expected);
expect(shown()).toBe(expected);
});
it('flips from what is shown even when the stored value is unusable', () => {
it('treats an unusable stored value as automatic', () => {
localStorage.setItem('cms-theme', 'system');
media(true);
document.documentElement.className = 'system';
system(true);
const { result } = renderHook(() => useTheme());
expect(result.current.mode).toBe('auto');
expect(shown()).toBe('dark');
act(() => { result.current.toggleTheme(); });
expect(shown()).toBe('light');
});
it('follows the shown theme when it differs from the stored one', () => {
localStorage.setItem('cms-theme', 'light');
it.each([
['light', false],
['dark', false],
['auto', true],
] as const)('setMode(%s) applies it at the very first call and stores it', (mode, osDark) => {
system(osDark);
const { result } = renderHook(() => useTheme());
act(() => result.current.setMode(mode));
expect(localStorage.getItem('cms-theme')).toBe(mode);
expect(result.current.mode).toBe(mode);
expect(shown()).toBe(mode === 'auto' ? (osDark ? 'dark' : 'light') : mode);
});
it('the first choice works at once, whatever the page carried before', () => {
system(true);
document.documentElement.className = 'dark';
const { result } = renderHook(() => useTheme());
expect(result.current.theme).toBe('dark');
act(() => { result.current.toggleTheme(); });
act(() => result.current.setMode('light'));
expect(shown()).toBe('light');
expect(localStorage.getItem('cms-theme')).toBe('light');
expect(result.current.theme).toBe('light');
});
it('keeps two toggles on the page in step', () => {
it('in automatic mode it follows a change of the system preference live, without reload', () => {
const os = system(false);
const { result } = renderHook(() => useTheme());
expect(shown()).toBe('light');
act(() => os.change(true));
expect(result.current.theme).toBe('dark');
expect(shown()).toBe('dark');
});
it('with a fixed theme a change of the system preference changes nothing', () => {
localStorage.setItem('cms-theme', 'light');
const os = system(false);
const { result } = renderHook(() => useTheme());
act(() => os.change(true));
expect(result.current.theme).toBe('light');
expect(shown()).toBe('light');
});
it('keeps two toggles on the page in step, and stops listening when they are gone', () => {
const os = system(false);
const a = renderHook(() => useTheme());
const b = renderHook(() => useTheme());
act(() => { a.result.current.toggleTheme(); });
expect(b.result.current.theme).toBe('dark');
act(() => a.result.current.setMode('dark'));
expect(b.result.current.mode).toBe('dark');
expect(os.listenerCount()).toBeGreaterThan(0);
act(() => { b.result.current.toggleTheme(); });
expect(shown()).toBe('light');
expect(a.result.current.theme).toBe('light');
a.unmount();
b.unmount();
expect(os.listenerCount()).toBe(0);
});
it('still works for this page view when the storage cannot be written', () => {
system(false);
vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
throw new Error('private mode');
});
const { result } = renderHook(() => useTheme());
act(() => result.current.setMode('dark'));
expect(result.current.mode).toBe('dark');
expect(shown()).toBe('dark');
});
});
+55 -28
View File
@@ -1,63 +1,90 @@
import { useCallback, useSyncExternalStore } from 'react';
type Theme = 'light' | 'dark';
/** What the user chose: a fixed theme, or follow the system (also the default when nothing is stored). */
export type ThemeMode = 'light' | 'dark' | 'auto';
/** The theme that is actually shown. */
export type Theme = 'light' | 'dark';
const STORAGE_KEY = 'cms-theme';
const DARK_QUERY = '(prefers-color-scheme: dark)';
const listeners = new Set<() => void>();
function isTheme(value: string | null): value is Theme {
return value === 'light' || value === 'dark';
/** Only used when storage cannot be written (private mode): the choice then lasts for this page view. */
let memoryMode: ThemeMode | null = null;
function storedMode(): ThemeMode {
if (memoryMode) return memoryMode;
try {
const stored = localStorage.getItem(STORAGE_KEY);
return stored === 'light' || stored === 'dark' ? stored : 'auto';
} catch {
return memoryMode ?? 'auto';
}
}
function preferredTheme(): Theme {
const stored = localStorage.getItem(STORAGE_KEY);
if (isTheme(stored)) return stored;
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
function systemTheme(): Theme {
return window.matchMedia(DARK_QUERY).matches ? 'dark' : 'light';
}
function apply(theme: Theme) {
document.documentElement.classList.remove('light', 'dark');
document.documentElement.classList.add(theme);
const classes = document.documentElement.classList;
if (!classes.contains(theme) || classes.contains(theme === 'dark' ? 'light' : 'dark')) {
classes.remove('light', 'dark');
classes.add(theme);
}
}
/**
* The theme that is actually shown, which is what the <html> class says: the stylesheet only
* knows that class. The stored value and the OS preference are only the way to pick a theme when
* the page carries none (or an unusable one); in that case it is applied right away, so the state
* we report and what the user sees can never differ. A first click then always flips what is shown.
*/
function currentTheme(): Theme {
const classes = document.documentElement.classList;
if (classes.contains('dark')) return 'dark';
if (classes.contains('light')) return 'light';
const theme = preferredTheme();
/** The shown theme for a mode; it is put on <html> right away, so what we report is what the user sees. */
function resolve(mode: ThemeMode): Theme {
const theme = mode === 'auto' ? systemTheme() : mode;
apply(theme);
return theme;
}
/** One primitive per state, so useSyncExternalStore sees no change while nothing changed. */
function snapshot(): string {
const mode = storedMode();
return `${mode}:${resolve(mode)}`;
}
function notifyAll() {
listeners.forEach((notify) => notify());
}
function subscribe(listener: () => void) {
listeners.add(listener);
// In automatic mode the page follows a change of the system preference live, without a reload; another tab that
// changes the choice is followed as well.
const media = typeof window.matchMedia === 'function' ? window.matchMedia(DARK_QUERY) : null;
media?.addEventListener?.('change', listener);
const onStorage = (event: StorageEvent) => {
if (event.key === STORAGE_KEY || event.key === null) listener();
};
window.addEventListener('storage', onStorage);
return () => {
listeners.delete(listener);
media?.removeEventListener?.('change', listener);
window.removeEventListener('storage', onStorage);
};
}
export function useTheme() {
// One source of truth shared by every toggle on the page (desktop sidebar, mobile overlay).
const theme = useSyncExternalStore(subscribe, currentTheme, () => 'light' as Theme);
const state = useSyncExternalStore(subscribe, snapshot, () => 'auto:light');
const [mode, theme] = state.split(':') as [ThemeMode, Theme];
const toggleTheme = useCallback(() => {
const next: Theme = currentTheme() === 'dark' ? 'light' : 'dark';
const setMode = useCallback((next: ThemeMode) => {
try {
localStorage.setItem(STORAGE_KEY, next);
memoryMode = null;
} catch {
// Storage can be unavailable (private mode); the switch itself still works.
// Storage can be unavailable (private mode); the switch itself still works for this page view.
memoryMode = next;
}
apply(next);
listeners.forEach((notify) => notify());
resolve(next);
notifyAll();
}, []);
return { theme, isDark: theme === 'dark', toggleTheme };
return { mode, theme, isDark: theme === 'dark', setMode };
}
+184 -5
View File
@@ -16,12 +16,19 @@
"settings": "Settings",
"openMenu": "Open navigation",
"closeMenu": "Close navigation",
"hero": "Hero",
"unreadMessages_one": "{{count}} new message",
"unreadMessages_other": "{{count}} new messages"
},
"theme": {
"switchToLight": "Switch to light theme",
"switchToDark": "Switch to dark theme"
"title": "Theme",
"label": "Theme: {{mode}}",
"labelAuto": "Theme: automatic (now {{now}})",
"mode": {
"light": "Light",
"dark": "Dark",
"auto": "Automatic"
}
},
"session": {
"unreachable": {
@@ -275,9 +282,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",
@@ -602,5 +618,168 @@
"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: a large heading with one or more photos. Here you manage the texts, the buttons and the photos. 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": "Short text above the title (optional)",
"lead": "Introduction (optional)",
"display": "Display"
},
"display": {
"single": "Single",
"slideshow": "Slideshow"
},
"buttons": {
"title": "Buttons",
"hint": "At most two buttons. As the target, choose a part of the page (for example #contact), a page of the site (for example /privacy) or a full web address (https://…).",
"label": "Button {{n}}: text",
"target": "Button {{n}}: target"
},
"slides": {
"title": "Images",
"add": "Add image",
"uploading": "Uploading…",
"hint": "Choose several files at once or drag them into this box. New photos are added at the bottom of the list. Drag a photo by its handle, or use the arrows, to change the order; visitors see the first photo first. With the Focus button you show where the subject is.",
"empty": "No images yet.",
"alt": "Description",
"decorative": "Hide from screen readers",
"up": "Move up",
"down": "Move down",
"remove": "Remove slide",
"ceiling": "Only the first {{max}} images are shown on the website.",
"focusPending": "Focus changed, not saved yet.",
"processing": "Processing…",
"processingHint": "The image is being prepared in the background; it appears on the website as soon as it is ready.",
"failed": "Failed",
"limits": "Allowed: {{formats}}. At most {{size}} MB per file and {{megapixels}} megapixels.",
"altHint": "Describes the photo for people who cannot see it and for search engines.",
"drag": "Move image {{n}}",
"dragInstructions": "Press space to pick up the image, use the arrow keys to move it and press space again to drop it. Escape cancels.",
"recut": "Making the new crop…",
"recutHint": "You still see the old crop. The change is only on the website when this is done.",
"activeOn": "Active",
"activeOff": "Not active",
"activeFor": "show image {{n}} on the website",
"queued": "in the queue",
"number": "Slide {{n}}",
"done": "Processing finished",
"doneFor": "Slide {{n}}: processing finished",
"cropEdit": "Adjust crop"
},
"processing": {
"count": "{{done}} of {{total}} photos processed",
"label": "Progress of processing the photos",
"explain": "The hero has been saved. The photos are prepared one by one and go live as soon as they are ready. Until the first photo is ready the website keeps its standard hero. You do not have to keep this page open.",
"failed_one": "Processing {{count}} photo failed.",
"failed_other": "Processing {{count}} photos failed.",
"failedHint": "The server tried three times. Try again, or upload the photo once more (the same photo is the same image).",
"retry": "Try again",
"current": "Working on photo {{n}} of {{total}}: step {{step}} of {{steps}}. A large photo can take a few minutes.",
"stuck": "Taking long?"
},
"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 and portrait 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"
},
"apply": "Apply",
"applyHint": "The change only takes effect when you save the hero. If you leave the page without saving it is dropped.",
"previewPending": "The preview of this photo is being prepared. Close this window and try again in a few seconds."
},
"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 short text above the title 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 a part of the page (for example #contact), a page of the site (for example /privacy) or a full web address (https://…).",
"altTooLong": "The description can have at most 300 characters.",
"altRequired": "Give a description or choose ‘Decoration only’."
},
"upload": {
"tooLarge": "The image is too large (at most {{max}} MB).",
"interrupted": "The upload was interrupted. Check the connection and try again.",
"busy": "Too many uploads in a row. Try again in a few minutes.",
"notAnImage": "This file is not an image.",
"progress": "Uploading: {{done}} of {{total}}",
"summary": "{{ok}} of {{total}} photos added",
"waiting": "waiting",
"uploading": "uploading…",
"done": "added",
"close": "Close"
},
"help": {
"heading": "Explanation of each part",
"save": "Changes only take effect after you save the hero.",
"title": {
"name": "Title",
"text": "The large heading. A new line in the field is a new line in the heading."
},
"tagline": {
"name": "Short text above the title",
"text": "A short label above or before the title. Can stay empty."
},
"lead": {
"name": "Introduction",
"text": "One or two sentences below the title. Can stay empty."
},
"buttons": {
"name": "Buttons",
"text": "At most two, each with a text and a target. As the target, choose a part of the page (for example #contact), a page of the site (for example /privacy) or a full web address (https://…)."
},
"display": {
"name": "Display",
"text": "‘Single’ shows one photo, ‘Slideshow’ switches between the photos."
},
"slides": {
"name": "Images",
"text": "Upload photos, describe what is in them and set the order (drag or use the arrows). The switch makes a photo active or not active. Choose ‘Hide from screen readers’ for a photo that adds nothing to the content."
},
"focus": {
"name": "Focus",
"text": "Show where the subject is in the photo, so a crop never cuts it off. For portrait screens, such as a phone, you can choose a separate point."
}
},
"unsaved": {
"badge": "Unsaved changes",
"text": "Save the hero to put them on the website.",
"leaveTitle": "Changes not saved",
"leaveText": "You have made changes that are not saved yet. If you leave this page they will be lost.",
"stay": "Stay",
"discard": "Discard changes"
},
"saving": "Saving…",
"tabs": {
"label": "Hero sections",
"content": "Content",
"images": "Images",
"busy": "{{count}} busy",
"hasChanges": "unsaved changes",
"hasErrors": "has errors"
}
}
}
+184 -5
View File
@@ -16,12 +16,19 @@
"settings": "Instellingen",
"openMenu": "Navigatie openen",
"closeMenu": "Navigatie sluiten",
"hero": "Hero",
"unreadMessages_one": "{{count}} nieuw bericht",
"unreadMessages_other": "{{count}} nieuwe berichten"
},
"theme": {
"switchToLight": "Overschakelen naar licht thema",
"switchToDark": "Overschakelen naar donker thema"
"title": "Thema",
"label": "Thema: {{mode}}",
"labelAuto": "Thema: automatisch (nu {{now}})",
"mode": {
"light": "Licht",
"dark": "Donker",
"auto": "Automatisch"
}
},
"session": {
"unreachable": {
@@ -275,9 +282,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",
@@ -602,5 +618,168 @@
"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: een grote kop met een of meer foto’s. Hier beheer je de teksten, de knoppen en de foto’s. 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": "Korte tekst boven de titel (optioneel)",
"lead": "Introductietekst (optioneel)",
"display": "Weergave"
},
"display": {
"single": "Enkel",
"slideshow": "Diavoorstelling"
},
"buttons": {
"title": "Knoppen",
"hint": "Maximaal twee knoppen. Als doel kies je een onderdeel van de pagina (bijvoorbeeld #contact), een pagina van de site (bijvoorbeeld /privacy) of een volledig webadres (https://…).",
"label": "Knop {{n}}: tekst",
"target": "Knop {{n}}: doel"
},
"slides": {
"title": "Afbeeldingen",
"add": "Afbeelding toevoegen",
"uploading": "Bezig met uploaden…",
"hint": "Kies meerdere bestanden tegelijk of sleep ze naar dit vak. Nieuwe foto’s komen onderaan de lijst. Sleep een foto aan het greepje, of gebruik de pijltjes, om de volgorde te wijzigen; de eerste foto zien bezoekers als eerste. Met de knop Focus geef je aan waar het onderwerp staat.",
"empty": "Nog geen afbeeldingen.",
"alt": "Beschrijving",
"decorative": "Verberg voor schermlezers",
"up": "Omhoog",
"down": "Omlaag",
"remove": "Slide verwijderen",
"ceiling": "Alleen de eerste {{max}} afbeeldingen worden getoond op de website.",
"focusPending": "Focus gewijzigd, nog niet opgeslagen.",
"processing": "Wordt verwerkt…",
"processingHint": "De afbeelding wordt klaargezet op de achtergrond; hij verschijnt op de website zodra hij klaar is.",
"failed": "Mislukt",
"limits": "Toegestaan: {{formats}}. Maximaal {{size}} MB per bestand en {{megapixels}} megapixel.",
"altHint": "Beschrijft de foto voor mensen die hem niet kunnen zien en voor zoekmachines.",
"drag": "Verplaats afbeelding {{n}}",
"dragInstructions": "Druk op spatie om de afbeelding op te pakken, gebruik de pijltjestoetsen om hem te verplaatsen en druk nogmaals op spatie om hem neer te zetten. Escape annuleert.",
"recut": "Nieuwe uitsnede wordt gemaakt…",
"recutHint": "Je ziet nog de oude uitsnede. De wijziging staat pas op de website als dit klaar is.",
"activeOn": "Actief",
"activeOff": "Niet actief",
"activeFor": "afbeelding {{n}} tonen op de website",
"queued": "in de wachtrij",
"number": "Slide {{n}}",
"done": "Verwerking afgerond",
"doneFor": "Slide {{n}}: verwerking afgerond",
"cropEdit": "Uitsnede aanpassen"
},
"processing": {
"count": "{{done}} van {{total}} foto’s verwerkt",
"label": "Voortgang van het verwerken van de foto’s",
"explain": "De hero is al opgeslagen. De foto’s worden één voor één klaargezet en gaan live zodra ze klaar zijn. Tot de eerste foto klaar is, blijft de standaard hero van de website staan. Je hoeft deze pagina niet open te houden.",
"failed_one": "Het verwerken van {{count}} foto is mislukt.",
"failed_other": "Het verwerken van {{count}} foto’s is mislukt.",
"failedHint": "De server heeft het drie keer geprobeerd. Probeer het opnieuw, of upload de foto nog een keer (dezelfde foto is dezelfde afbeelding).",
"retry": "Opnieuw proberen",
"current": "Bezig met foto {{n}} van {{total}}: stap {{step}} van {{steps}}. Een grote foto kan enkele minuten duren.",
"stuck": "Duurt het lang?"
},
"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 en staande 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"
},
"apply": "Toepassen",
"applyHint": "De wijziging geldt pas nadat je de hero opslaat. Verlaat je de pagina zonder op te slaan, dan vervalt ze.",
"previewPending": "Het voorbeeld van deze foto wordt klaargezet. Sluit dit venster en probeer het over een paar seconden opnieuw."
},
"errors": {
"titleRequired": "Een titel is verplicht.",
"titleTooLong": "De titel mag maximaal 200 tekens bevatten.",
"titleTooManyLines": "De titel mag maximaal 5 regels hebben.",
"taglineTooLong": "De korte tekst boven de titel 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 onderdeel van de pagina (bijvoorbeeld #contact), een pagina van de site (bijvoorbeeld /privacy) of een volledig webadres (https://…).",
"altTooLong": "De beschrijving mag maximaal 300 tekens bevatten.",
"altRequired": "Geef een beschrijving of kies ‘Alleen versiering’."
},
"upload": {
"tooLarge": "De afbeelding is te groot (maximaal {{max}} MB).",
"interrupted": "De upload is afgebroken. Controleer de verbinding en probeer het opnieuw.",
"busy": "Er zijn te veel uploads achter elkaar. Probeer het over een paar minuten opnieuw.",
"notAnImage": "Dit bestand is geen afbeelding.",
"progress": "Bezig met uploaden: {{done}} van {{total}}",
"summary": "{{ok}} van {{total}} foto’s toegevoegd",
"waiting": "wacht",
"uploading": "bezig…",
"done": "toegevoegd",
"close": "Sluiten"
},
"help": {
"heading": "Uitleg per onderdeel",
"save": "Wijzigingen gelden pas nadat je de hero opslaat.",
"title": {
"name": "Titel",
"text": "De grote kop. Een nieuwe regel in het veld is een nieuwe regel in de kop."
},
"tagline": {
"name": "Korte tekst boven de titel",
"text": "Een kort label dat boven of voor de titel staat. Mag leeg blijven."
},
"lead": {
"name": "Introductietekst",
"text": "Een of twee zinnen onder de titel. Mag leeg blijven."
},
"buttons": {
"name": "Knoppen",
"text": "Maximaal twee, elk met een tekst en een doel. Als doel kies je een onderdeel van de pagina (bijvoorbeeld #contact), een pagina van de site (bijvoorbeeld /privacy) of een volledig webadres (https://…)."
},
"display": {
"name": "Weergave",
"text": "‘Enkel’ toont één foto, ‘Diavoorstelling’ wisselt tussen de foto’s."
},
"slides": {
"name": "Afbeeldingen",
"text": "Upload foto’s, beschrijf wat erop staat en bepaal de volgorde (slepen of de pijltjes). Met de schakelaar zet je een foto actief of niet actief. Kies ‘Verberg voor schermlezers’ voor een foto die niets toevoegt aan de inhoud."
},
"focus": {
"name": "Focus",
"text": "Geef aan waar het onderwerp op de foto staat, zodat een uitsnede er niets van afhakt. Voor staande schermen, zoals een telefoon, kun je een apart punt kiezen."
}
},
"unsaved": {
"badge": "Niet-opgeslagen wijzigingen",
"text": "Sla de hero op om ze door te voeren op de website.",
"leaveTitle": "Wijzigingen niet opgeslagen",
"leaveText": "Je hebt wijzigingen gemaakt die nog niet zijn opgeslagen. Als je deze pagina verlaat, gaan ze verloren.",
"stay": "Blijven",
"discard": "Wijzigingen weggooien"
},
"saving": "Bezig met opslaan…",
"tabs": {
"label": "Onderdelen van de hero",
"content": "Inhoud",
"images": "Afbeeldingen",
"busy": "{{count}} bezig",
"hasChanges": "niet-opgeslagen wijzigingen",
"hasErrors": "bevat fouten"
}
}
}
+50
View File
@@ -120,3 +120,53 @@
outline-offset: 2px;
}
}
/* A calm light band that sweeps over a photo that is still being prepared. Pure CSS, follows the text colour so it suits
the light and the dark theme, and stands still for people who asked for less motion. */
@keyframes hero-shimmer {
to {
transform: translateX(100%);
}
}
.hero-shimmer {
position: relative;
overflow: hidden;
}
.hero-shimmer::after {
content: '';
position: absolute;
inset: 0;
transform: translateX(-100%);
background: linear-gradient(90deg, transparent, color-mix(in oklab, currentColor 14%, transparent), transparent);
animation: hero-shimmer 1.8s ease-in-out infinite;
}
@media (prefers-reduced-motion: reduce) {
.hero-shimmer::after {
animation: none;
display: none;
}
}
/* The "processing finished" note of a photo: visible for a few seconds, then it fades (the page removes it after that). */
@keyframes hero-done-fade {
0%,
70% {
opacity: 1;
}
100% {
opacity: 0;
}
}
.hero-done {
animation: hero-done-fade 4s ease-in forwards;
}
@media (prefers-reduced-motion: reduce) {
.hero-done {
animation: none;
}
}
+4 -2
View File
@@ -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);
+3 -1
View File
@@ -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';
+13
View File
@@ -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,