Hero: een gewijzigd focuspunt geldt pas bij het opslaan van de hero (Bryan); het focus-venster houdt de wijziging lokaal
Het eindpunt PUT /hero/images/{id}/focus is vervallen; de focus gaat mee in de opslag (imageFocus) en de varianten worden dan in nieuwe bestanden opnieuw gesneden.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -4,7 +4,7 @@ Kept while Bryan was away (2026-11-16): no questions to him, a likely assumption
|
||||
|
||||
| # | Question | Assumption made | If Bryan chooses differently | Where |
|
||||
|---|---|---|---|---|
|
||||
| 1 | Does a change of the **focus** of an image that is already live take effect at once? | Yes. Saving is publishing (Q11 = A) and the images are shared, so a new focus re-cuts the variants and the live page shows them within the cache time. | Add a draft step for images (focus applies when the hero is saved), or a confirmation in the focus dialog. | `HeroImageService.SetFocusAsync`; `FocusDialog.tsx` |
|
||||
| 1 | Does a change of the **focus** of an image that is already live take effect at once? | **Decided by Bryan (2026-11-16): no, only when the hero is saved.** The admin keeps it locally (Apply in the focus dialog), sends it with the save (`imageFocus`), the host then cuts the variants again into new files and saves hero and images together; leaving the page drops it. | n/a | `HeroSaveRequest.ImageFocus`, `HeroService.SaveAsync`, `HeroImageService.StageFocusAsync`, `FocusDialog.tsx`, `HeroPage.tsx` |
|
||||
| 2 | Is a photo uploaded but never put in a slide cleaned up, and when? | Yes, after the same 7 days as retired files (Bryan decided 7 days for old files; extended to unused uploads). | Another period, or never (then storage grows). | `HeroMediaCleanup` (step 1), `Media:RetentionDays` |
|
||||
| 3 | Should an uploaded photo that is **identical** to an existing one be a new image? | No: same bytes = same image (and a re-upload repairs lost files). | Always a new image: drop the SHA-256 unique index and the lookup. | `HeroImageService.UploadAsync`, `HeroDbContext` (unique `OriginalSha256`) |
|
||||
| 4 | Is the **alt text** per slide or per photo? | Per slide (the same photo may carry another description in another place). | Per photo: move `Alt` and `Decorative` from `HeroSlide` to `HeroImage`. | `HeroSlide`, `HeroSaveRequest`, `HeroPage.tsx` |
|
||||
@@ -16,7 +16,7 @@ Kept while Bryan was away (2026-11-16): no questions to him, a likely assumption
|
||||
| 10 | Is **AVIF** used on the page? | Only for slides 2 and up on the client; the first image and the preload are WebP only (ASF: a preload cannot say AVIF if supported). | Add `<source type="image/avif">` before the WebP source and a second preload per format (costs a double download in some browsers). | `HeroPictureRenderer` |
|
||||
| 11 | Who may use the Hero screen? | Owner and Administrator, like Offerings. | Owner only: change the route and nav roles. | `router.tsx`, `Sidebar.tsx`, `[Authorize(Policy = "AdminOnly")]` |
|
||||
| 12 | Upload limits. | 10 MB per file, 64 megapixels, at most 20 uploads per user per hour, 2 images processed at once, 2 GB in total. The proxy allows 15 MB (Bryan). | Other limits via `Media__*` and `RateLimiting__HeroUpload`; a higher file limit also needs the proxy limit. | `MediaOptions`, `ServiceCollectionExtensions` (policy `hero-upload`) |
|
||||
| 13 | Can the admin **delete an image** itself? | No button: removing it from the hero is enough; unused images go after 7 days. The API (`DELETE /hero/images/{id}`, 409 while in use) exists. | Add a media library screen with delete. | `HeroImagesController.Delete`, `HeroPage.tsx` |
|
||||
| 13 | Can the admin **delete an image** itself? | **Decided: no button**; replacing the image of a slide or removing the slide is enough; unused photos go after 7 days. The API (`DELETE /hero/images/{id}`, 409 while in use) exists. | Add a media library screen with delete. | `HeroImagesController.Delete`, `HeroPage.tsx` |
|
||||
| 14 | Wording of the **messages** (Dutch), for example the focus dialog and the validation texts. | My wording; the admin has nl and en. | Edit the texts. | `frontend/src/i18n/locales/*/translation.json` (`hero.*`), `SlpModularCms.Modules.Hero/Texts/*.json` |
|
||||
| 15 | The **button target** rules. | The CMS accepts only `#anchor` (letters, digits, `-`, `_`, starting with a letter), `/path` (no `//`, no spaces) or `https://host/...`; the page renderer is a little wider (ASF rules) because it also copes with data it did not check. | Allow `mailto:` or `tel:` (add to both validators and the renderer, and agree it with the sites). | `ButtonTargetValidator`, `schemas/hero.ts`, `HeroPictureRenderer.IsButtonTarget` |
|
||||
| 16 | Maximum **published** slides. | 50, a safety ceiling (not an administrator limit). | Another number or a hard limit shown in the admin. | `HeroOptions.MaxPublishedSlides` |
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ Admin > **Hero** (Owner en Administrator, module `Hero`):
|
||||
- Maximaal twee knoppen met tekst en doel. Een doel is een `#anker`, een `/pad` of een `https://`-adres; andere waarden worden geweigerd.
|
||||
- Planning (aan of uit, van en tot). Buiten de planning, of uitgezet, toont de website zijn eigen ingebakken hero.
|
||||
- Slides: een afbeelding met verplichte beschrijving (alt-tekst) of de markering decoratief, volgorde, aan of uit per slide. Er is geen grens op het aantal slides; technisch publiceert de host er hoogstens `Hero:MaxPublishedSlides` (50).
|
||||
- Focus: per afbeelding een algemeen punt en zoom, en optioneel een eigen punt voor de liggende (`wide`, 3:2) en de staande (`tall`, 4:5) weergave. De host snijdt de varianten daaromheen uit.
|
||||
- Focus: per afbeelding een algemeen punt en zoom, en optioneel een eigen punt voor de liggende (`wide`, 3:2) en de staande (`tall`, 4:5) weergave. De host snijdt de varianten daaromheen uit. **Een wijziging van het focuspunt geldt pas als je de hero opslaat** (Bryan, 2026-11-16): het focus-venster houdt de wijziging lokaal in de admin (knop Toepassen, een markering bij de slide); bij Opslaan gaat ze mee in dezelfde aanvraag (`imageFocus`), de host snijdt dan de varianten opnieuw in nieuwe bestanden en bewaart hero en afbeeldingen in één keer. Verlaat je de pagina zonder op te slaan, dan vervalt de wijziging en is er niets aan de server veranderd. Mislukt een opslag nadat nieuwe bestanden zijn geschreven, dan verwijst niets ernaar en ruimt de opschoning ze na 7 dagen op; de oude bestanden blijven ook 7 dagen staan voor sites die nog oude data hebben.
|
||||
|
||||
De admin toont alleen een badge Live of Niet live.
|
||||
|
||||
|
||||
@@ -1,25 +1,24 @@
|
||||
import { useRef, useState, type KeyboardEvent, type PointerEvent } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { toast } from 'sonner';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { FormErrorBanner } from '@/components/ui/FormErrorBanner';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { mediaUrl } from '../lib/media';
|
||||
import { CENTRE, MAX_ZOOM, TALL, WIDE, cropFor, normalizeFocus, type Ratio } from '../lib/focusMath';
|
||||
import { useSetImageFocus } from '../services/hooks';
|
||||
import type { FocusDto, HeroImageDto } from '../services/types';
|
||||
import type { FocusDto, HeroFocusRequest, HeroImageDto } from '../services/types';
|
||||
|
||||
type Target = 'general' | 'wide' | 'tall';
|
||||
|
||||
interface FocusDialogProps {
|
||||
/** The image to edit; null = closed. */
|
||||
/** 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, onClose }: FocusDialogProps) {
|
||||
export function FocusDialog({ image, onApply, onClose }: FocusDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Dialog open={image !== null} onOpenChange={(next) => { if (!next) onClose(); }}>
|
||||
@@ -28,7 +27,7 @@ export function FocusDialog({ image, onClose }: FocusDialogProps) {
|
||||
<DialogTitle>{t('hero.focus.title')}</DialogTitle>
|
||||
</DialogHeader>
|
||||
{/* Mounted only while open, so every opening starts from the stored values. */}
|
||||
{image && <FocusEditor image={image} onClose={onClose} />}
|
||||
{image && <FocusEditor image={image} onApply={onApply} onClose={onClose} />}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
@@ -36,11 +35,9 @@ export function FocusDialog({ image, onClose }: FocusDialogProps) {
|
||||
|
||||
const percent = (fraction: number) => Math.round(fraction * 1000) / 10;
|
||||
|
||||
function FocusEditor({ image, onClose }: { image: HeroImageDto; onClose: () => void }) {
|
||||
function FocusEditor({ image, onApply, onClose }: { image: HeroImageDto; onApply: (imageId: string, request: HeroFocusRequest) => void; onClose: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const save = useSetImageFocus();
|
||||
const area = useRef<HTMLDivElement>(null);
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
const [target, setTarget] = useState<Target>('general');
|
||||
const [general, setGeneral] = useState<FocusDto>(image.focus ?? CENTRE);
|
||||
const [wide, setWide] = useState<FocusDto | null>(image.wideFocus);
|
||||
@@ -79,16 +76,9 @@ function FocusEditor({ image, onClose }: { image: HeroImageDto; onClose: () => v
|
||||
update({ ...active, x: active.x + move[0], y: active.y + move[1] });
|
||||
};
|
||||
|
||||
const onSave = async () => {
|
||||
setServerError(null);
|
||||
try {
|
||||
await save.mutateAsync({ imageId: image.id, body: { focus: general, wide, tall } });
|
||||
toast.success(t('hero.focus.savedToast'));
|
||||
onClose();
|
||||
} catch (error) {
|
||||
const message = (error as { problem?: { message?: unknown } }).problem?.message;
|
||||
setServerError(typeof message === 'string' ? message : t('errors.generic'));
|
||||
}
|
||||
const onSave = () => {
|
||||
onApply(image.id, { focus: general, wide, tall });
|
||||
onClose();
|
||||
};
|
||||
|
||||
const outline = (ratio: Ratio, focus: FocusDto) => {
|
||||
@@ -103,8 +93,8 @@ function FocusEditor({ image, onClose }: { image: HeroImageDto; onClose: () => v
|
||||
|
||||
return (
|
||||
<div className="space-y-4" data-testid="focus-dialog">
|
||||
<FormErrorBanner error={serverError !== null ? { message: serverError } : null} onDismiss={() => setServerError(null)} />
|
||||
<p className="text-sm text-muted-foreground">{t('hero.focus.intro')}</p>
|
||||
<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>
|
||||
@@ -244,8 +234,8 @@ function FocusEditor({ image, onClose }: { image: HeroImageDto; onClose: () => v
|
||||
<Button type="button" variant="outline" onClick={onClose} data-testid="focus-cancel">
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button type="button" onClick={onSave} disabled={save.isPending} data-testid="focus-save">
|
||||
{save.isPending ? '…' : t('common.save')}
|
||||
<Button type="button" onClick={onSave} data-testid="focus-save">
|
||||
{t('hero.focus.apply')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { API_BASE } from '@/features/auth/mocks/fixtures';
|
||||
import type { FocusDto, HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest, HeroSlideAdminDto } from '@/features/hero/services/types';
|
||||
import type { HeroAdminDto, HeroImageDto, HeroSaveRequest, HeroSlideAdminDto } from '@/features/hero/services/types';
|
||||
|
||||
const seedImage = (id: string, width = 1600, height = 1067): HeroImageDto => ({
|
||||
id,
|
||||
@@ -75,6 +75,11 @@ export const heroHandlers = [
|
||||
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 };
|
||||
}
|
||||
hero = {
|
||||
...hero,
|
||||
id: hero.id ?? '99999999-9999-9999-9999-999999999999',
|
||||
@@ -112,15 +117,4 @@ export const heroHandlers = [
|
||||
images[image.id] = image;
|
||||
return HttpResponse.json(image, { status: 201 });
|
||||
}),
|
||||
|
||||
http.put(`${API_BASE}/api/v1/hero/images/:id/focus`, async ({ params, request }) => {
|
||||
const body = (await request.json()) as HeroFocusRequest;
|
||||
const id = String(params.id);
|
||||
const current = images[id] ?? hero.slides.find((s) => s.imageId === id)?.image ?? seedImage(id);
|
||||
const asDto = (f: FocusDto | null) => (f ? { ...f } : null);
|
||||
const next: HeroImageDto = { ...current, focus: body.focus, wideFocus: asDto(body.wide), tallFocus: asDto(body.tall) };
|
||||
images[id] = next;
|
||||
hero = { ...hero, slides: hero.slides.map((s) => (s.imageId === id ? { ...s, image: next } : s)) };
|
||||
return HttpResponse.json(next);
|
||||
}),
|
||||
];
|
||||
|
||||
@@ -214,13 +214,14 @@ describe('Focus dialog', () => {
|
||||
return screen.findByTestId('focus-dialog');
|
||||
};
|
||||
|
||||
it('starts with the stored point and shows both previews', async () => {
|
||||
it('starts with the stored point, shows both previews and says the change needs a save', async () => {
|
||||
await open();
|
||||
|
||||
expect(screen.getByTestId('focus-x')).toHaveValue(50);
|
||||
expect(screen.getByTestId('focus-y')).toHaveValue(50);
|
||||
expect(screen.getByTestId('focus-preview-wide')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('focus-preview-tall')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('focus-apply-hint')).toHaveTextContent(/pas nadat je de hero opslaat|only takes effect when you save the hero/);
|
||||
});
|
||||
|
||||
it('moves the point with the keyboard', async () => {
|
||||
@@ -234,7 +235,7 @@ describe('Focus dialog', () => {
|
||||
expect(screen.getByTestId('focus-y')).toHaveValue(55);
|
||||
});
|
||||
|
||||
it('saves a general point and an own setting for the tall display', async () => {
|
||||
it('keeps a change locally until the hero is saved, then sends it with the save', async () => {
|
||||
await open();
|
||||
|
||||
fireEvent.change(screen.getByTestId('focus-x'), { target: { value: '30' } });
|
||||
@@ -246,13 +247,40 @@ describe('Focus dialog', () => {
|
||||
await userEvent.click(screen.getByTestId('focus-save'));
|
||||
|
||||
await waitFor(() => expect(screen.queryByTestId('focus-dialog')).not.toBeInTheDocument());
|
||||
// The dialog closed after the server accepted it; reopening shows the stored values.
|
||||
expect(getSavedHeroRequests()).toHaveLength(0);
|
||||
expect(screen.getByTestId('hero-slide-0-focus-pending')).toBeInTheDocument();
|
||||
|
||||
// Reopening shows the pending values.
|
||||
await userEvent.click(screen.getByTestId('hero-slide-0-focus'));
|
||||
expect(screen.getByTestId('focus-x')).toHaveValue(30);
|
||||
await userEvent.click(screen.getByTestId('focus-target-tall'));
|
||||
expect(screen.getByTestId('focus-override-tall')).toBeChecked();
|
||||
expect(screen.getByTestId('focus-x')).toHaveValue(80);
|
||||
expect(screen.getByTestId('focus-zoom')).toHaveValue('2');
|
||||
await userEvent.click(screen.getByTestId('focus-cancel'));
|
||||
|
||||
await userEvent.click(screen.getByTestId('hero-save'));
|
||||
|
||||
await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1));
|
||||
expect(getSavedHeroRequests()[0].imageFocus).toEqual([
|
||||
{
|
||||
imageId: '10000000-0000-0000-0000-000000000001',
|
||||
focus: { x: 0.3, y: 0.5, zoom: 1 },
|
||||
wide: null,
|
||||
tall: { x: 0.8, y: 0.5, zoom: 2 },
|
||||
},
|
||||
]);
|
||||
await waitFor(() => expect(screen.queryByTestId('hero-slide-0-focus-pending')).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('sends no focus edits when nothing was changed', async () => {
|
||||
await open();
|
||||
await userEvent.click(screen.getByTestId('focus-cancel'));
|
||||
|
||||
await userEvent.click(screen.getByTestId('hero-save'));
|
||||
|
||||
await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1));
|
||||
expect(getSavedHeroRequests()[0].imageFocus).toEqual([]);
|
||||
});
|
||||
|
||||
it('goes back to the general point when the own setting is switched off', async () => {
|
||||
@@ -266,12 +294,14 @@ describe('Focus dialog', () => {
|
||||
expect(screen.getByTestId('focus-x')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('closes without saving', async () => {
|
||||
it('drops a change when the dialog is cancelled', async () => {
|
||||
await open();
|
||||
fireEvent.change(screen.getByTestId('focus-x'), { target: { value: '10' } });
|
||||
|
||||
await userEvent.click(screen.getByTestId('focus-cancel'));
|
||||
|
||||
await waitFor(() => expect(screen.queryByTestId('focus-dialog')).not.toBeInTheDocument());
|
||||
expect(screen.queryByTestId('hero-slide-0-focus-pending')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import { FocusDialog } from '../components/FocusDialog';
|
||||
import { mediaUrl } from '../lib/media';
|
||||
import { fromLocalInput, heroFormSchema, toLocalInput, type HeroFormData } from '../schemas/hero';
|
||||
import { useHero, useSaveHero, useUploadHeroImage } from '../services/hooks';
|
||||
import type { HeroAdminDto, HeroImageDto, HeroSaveRequest } from '../services/types';
|
||||
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';
|
||||
@@ -35,7 +35,7 @@ function toForm(hero: HeroAdminDto): HeroFormData {
|
||||
};
|
||||
}
|
||||
|
||||
function toRequest(values: HeroFormData): HeroSaveRequest {
|
||||
function toRequest(values: HeroFormData, focusEdits: Record<string, HeroFocusRequest>): HeroSaveRequest {
|
||||
return {
|
||||
title: values.title,
|
||||
tagline: values.tagline || null,
|
||||
@@ -46,6 +46,7 @@ function toRequest(values: HeroFormData): HeroSaveRequest {
|
||||
startsAt: fromLocalInput(values.startsAt),
|
||||
endsAt: fromLocalInput(values.endsAt),
|
||||
slides: values.slides.map((s) => ({ id: s.id, imageId: s.imageId, alt: s.decorative ? null : s.alt, decorative: s.decorative, isActive: s.isActive })),
|
||||
imageFocus: Object.entries(focusEdits).map(([imageId, edit]) => ({ imageId, ...edit })),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -125,6 +126,8 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
const [uploadError, setUploadError] = useState<string | null>(null);
|
||||
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 {
|
||||
@@ -143,14 +146,21 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
return map;
|
||||
}, [hero.slides, localImages]);
|
||||
|
||||
const hasPendingFocus = Object.keys(focusEdits).length > 0;
|
||||
useEffect(() => {
|
||||
if (!isDirty) return undefined;
|
||||
if (!isDirty && !hasPendingFocus) return undefined;
|
||||
const warn = (event: BeforeUnloadEvent) => {
|
||||
event.preventDefault();
|
||||
};
|
||||
window.addEventListener('beforeunload', warn);
|
||||
return () => window.removeEventListener('beforeunload', warn);
|
||||
}, [isDirty]);
|
||||
}, [isDirty, hasPendingFocus]);
|
||||
|
||||
// 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;
|
||||
};
|
||||
|
||||
const onUpload = async (files: FileList | null) => {
|
||||
const file = files?.[0];
|
||||
@@ -176,7 +186,8 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
const onSubmit = async (values: HeroFormData) => {
|
||||
setServerError(null);
|
||||
try {
|
||||
await save.mutateAsync(toRequest(values));
|
||||
await save.mutateAsync(toRequest(values, focusEdits));
|
||||
setFocusEdits({});
|
||||
toast.success(t('hero.savedToast'));
|
||||
} catch (error) {
|
||||
setServerError(serverMessage(error, t('errors.generic'), t('errors.network')));
|
||||
@@ -297,6 +308,9 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
<Label htmlFor={`hero-slide-${index}-alt`}>{t('hero.slides.alt', { n: index + 1 })}</Label>
|
||||
<Input id={`hero-slide-${index}-alt`} maxLength={300} disabled={decorative} data-testid={`hero-slide-${index}-alt`} {...register(`slides.${index}.alt` as const)} />
|
||||
<FieldError message={err(heroErrors.slides?.[index]?.alt?.message)} testId={`hero-slide-${index}-alt-error`} />
|
||||
{focusEdits[field.imageId] && (
|
||||
<p className="text-xs font-medium" data-testid={`hero-slide-${index}-focus-pending`}>{t('hero.slides.focusPending')}</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-4 text-sm">
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="checkbox" className="size-4 rounded border-input" data-testid={`hero-slide-${index}-decorative`} {...register(`slides.${index}.decorative` as const)} />
|
||||
@@ -315,7 +329,7 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
<Button type="button" variant="outline" size="icon" aria-label={t('hero.slides.down')} disabled={index === slides.fields.length - 1} onClick={() => slides.move(index, index + 1)} data-testid={`hero-slide-${index}-down`}>
|
||||
<ArrowDown className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
<Button type="button" variant="outline" size="icon" aria-label={t('hero.slides.focus')} disabled={!image} onClick={() => setFocusImageId(field.imageId)} data-testid={`hero-slide-${index}-focus`}>
|
||||
<Button type="button" variant={focusEdits[field.imageId] ? 'default' : 'outline'} size="icon" aria-label={t('hero.slides.focus')} disabled={!image} onClick={() => setFocusImageId(field.imageId)} data-testid={`hero-slide-${index}-focus`}>
|
||||
<Crosshair className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
<Button type="button" variant="outline" size="icon" aria-label={t('hero.slides.remove')} onClick={() => slides.remove(index)} data-testid={`hero-slide-${index}-remove`}>
|
||||
@@ -339,7 +353,11 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<FocusDialog image={focusImageId ? images[focusImageId] ?? null : null} onClose={() => setFocusImageId(null)} />
|
||||
<FocusDialog
|
||||
image={withPendingFocus(focusImageId ? images[focusImageId] ?? null : null)}
|
||||
onApply={(imageId, edit) => setFocusEdits((current) => ({ ...current, [imageId]: edit }))}
|
||||
onClose={() => setFocusImageId(null)}
|
||||
/>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { api } from '@/lib/api-client';
|
||||
import type { HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest } from './types';
|
||||
import type { HeroAdminDto, HeroImageDto, HeroSaveRequest } from './types';
|
||||
|
||||
export const HERO_KEY = ['hero'];
|
||||
|
||||
@@ -33,17 +33,6 @@ export function useUploadHeroImage() {
|
||||
});
|
||||
}
|
||||
|
||||
export function useSetImageFocus() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<HeroImageDto, Error, { imageId: string; body: HeroFocusRequest }>({
|
||||
mutationFn: ({ imageId, body }) => api.put<HeroImageDto>(`/api/v1/hero/images/${imageId}/focus`, body),
|
||||
onSuccess: () => {
|
||||
// The slide list shows the image variants; they have new addresses after a change of focus.
|
||||
void queryClient.invalidateQueries({ queryKey: HERO_KEY });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteHeroImage() {
|
||||
return useMutation<void, Error, string>({
|
||||
mutationFn: (imageId) => api.delete<void>(`/api/v1/hero/images/${imageId}`),
|
||||
|
||||
@@ -74,6 +74,12 @@ export interface HeroSaveRequest {
|
||||
startsAt: string | null;
|
||||
endsAt: string | null;
|
||||
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 {
|
||||
|
||||
@@ -654,7 +654,8 @@
|
||||
"down": "Move down",
|
||||
"focus": "Set focus",
|
||||
"remove": "Remove from the hero",
|
||||
"ceiling": "Only the first {{max}} images are shown on the website."
|
||||
"ceiling": "Only the first {{max}} images are shown on the website.",
|
||||
"focusPending": "Focus changed, not saved yet."
|
||||
},
|
||||
"focus": {
|
||||
"title": "Focus and crop",
|
||||
@@ -675,7 +676,8 @@
|
||||
"wide": "Landscape preview",
|
||||
"tall": "Portrait preview"
|
||||
},
|
||||
"savedToast": "Focus saved"
|
||||
"apply": "Apply",
|
||||
"applyHint": "The change only takes effect when you save the hero. If you leave the page without saving it is dropped."
|
||||
},
|
||||
"errors": {
|
||||
"titleRequired": "A title is required.",
|
||||
|
||||
@@ -654,7 +654,8 @@
|
||||
"down": "Omlaag",
|
||||
"focus": "Focus instellen",
|
||||
"remove": "Verwijderen uit de hero",
|
||||
"ceiling": "Alleen de eerste {{max}} afbeeldingen worden getoond op de website."
|
||||
"ceiling": "Alleen de eerste {{max}} afbeeldingen worden getoond op de website.",
|
||||
"focusPending": "Focus gewijzigd, nog niet opgeslagen."
|
||||
},
|
||||
"focus": {
|
||||
"title": "Focus en uitsnede",
|
||||
@@ -675,7 +676,8 @@
|
||||
"wide": "Voorbeeld liggend",
|
||||
"tall": "Voorbeeld staand"
|
||||
},
|
||||
"savedToast": "Focus opgeslagen"
|
||||
"apply": "Toepassen",
|
||||
"applyHint": "De wijziging geldt pas nadat je de hero opslaat. Verlaat je de pagina zonder op te slaan, dan vervalt ze."
|
||||
},
|
||||
"errors": {
|
||||
"titleRequired": "Een titel is verplicht.",
|
||||
|
||||
+45
-91
@@ -678,37 +678,6 @@
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"HeroFocusRequest": {
|
||||
"properties": {
|
||||
"focus": {
|
||||
"$ref": "#/components/schemas/FocusDto"
|
||||
},
|
||||
"tall": {
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "null"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/FocusDto"
|
||||
}
|
||||
]
|
||||
},
|
||||
"wide": {
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "null"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/FocusDto"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"focus"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"HeroImageDto": {
|
||||
"properties": {
|
||||
"focus": {
|
||||
@@ -775,6 +744,42 @@
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"HeroImageFocusRequest": {
|
||||
"properties": {
|
||||
"focus": {
|
||||
"$ref": "#/components/schemas/FocusDto"
|
||||
},
|
||||
"imageId": {
|
||||
"format": "uuid",
|
||||
"type": "string"
|
||||
},
|
||||
"tall": {
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "null"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/FocusDto"
|
||||
}
|
||||
]
|
||||
},
|
||||
"wide": {
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "null"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/FocusDto"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"imageId",
|
||||
"focus"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"HeroSaveRequest": {
|
||||
"properties": {
|
||||
"buttons": {
|
||||
@@ -799,6 +804,15 @@
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"imageFocus": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/HeroImageFocusRequest"
|
||||
},
|
||||
"type": [
|
||||
"null",
|
||||
"array"
|
||||
]
|
||||
},
|
||||
"isActive": {
|
||||
"type": "boolean"
|
||||
},
|
||||
@@ -3045,66 +3059,6 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/hero/images/{id}/focus": {
|
||||
"put": {
|
||||
"parameters": [
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"format": "uuid",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/*+json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroFocusRequest"
|
||||
}
|
||||
},
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroFocusRequest"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroFocusRequest"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroImageDto"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroImageDto"
|
||||
}
|
||||
},
|
||||
"text/plain": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HeroImageDto"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "OK"
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"HeroImages"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/offerings": {
|
||||
"get": {
|
||||
"responses": {
|
||||
|
||||
@@ -96,20 +96,21 @@ public class HeroAsfSiteE2ETests : IClassFixture<AsfSiteFactory>
|
||||
{
|
||||
var seed = JsonDocument.Parse(File.ReadAllText(Path.Combine(web, "contract", "host-injection", "hero", "seed.json"))).RootElement;
|
||||
var slides = new List<HeroSlideRequest>();
|
||||
var focusEdits = new List<HeroImageFocusRequest>();
|
||||
foreach (var slide in seed.GetProperty("slides").EnumerateArray())
|
||||
{
|
||||
var photo = File.ReadAllBytes(Path.Combine(web, "src", "assets", slide.GetProperty("file").GetString()!));
|
||||
var image = await InScope(sp => sp.GetRequiredService<IHeroImageService>().UploadAsync(new MemoryStream(photo), photo.Length, caller, default));
|
||||
var focus = slide.GetProperty("focus");
|
||||
await InScope(sp => sp.GetRequiredService<IHeroImageService>().SetFocusAsync(
|
||||
Guid.Parse(image.Id), new HeroFocusRequest(new FocusDto(focus.GetProperty("x").GetDouble(), focus.GetProperty("y").GetDouble(), 1)), caller, default));
|
||||
// The focus travels with the save of the hero, like the admin does it.
|
||||
focusEdits.Add(new HeroImageFocusRequest(Guid.Parse(image.Id), new FocusDto(focus.GetProperty("x").GetDouble(), focus.GetProperty("y").GetDouble(), 1)));
|
||||
slides.Add(new HeroSlideRequest(null, Guid.Parse(image.Id), slide.GetProperty("alt").GetString()));
|
||||
}
|
||||
|
||||
await InScope(sp => sp.GetRequiredService<IHeroService>().SaveAsync(
|
||||
new HeroSaveRequest(seed.GetProperty("title").GetString(), seed.GetProperty("tagline").GetString(), null, seed.GetProperty("display").GetString(),
|
||||
seed.GetProperty("buttons").EnumerateArray().Select(b => new HeroButtonRequest(b.GetProperty("label").GetString(), b.GetProperty("target").GetString())).ToList(),
|
||||
true, null, null, slides), caller, default));
|
||||
true, null, null, slides, focusEdits), caller, default));
|
||||
|
||||
var response = await client.GetAsync("/");
|
||||
var page = await response.Content.ReadAsStringAsync();
|
||||
|
||||
@@ -46,7 +46,6 @@ public class HeroOnTheMasterHostTests : IClassFixture<ApiWebApplicationFactory>
|
||||
[InlineData("PUT", "/api/v1/hero")]
|
||||
[InlineData("POST", "/api/v1/hero/images")]
|
||||
[InlineData("DELETE", "/api/v1/hero/images/11111111-2222-3333-4444-555555555555")]
|
||||
[InlineData("PUT", "/api/v1/hero/images/11111111-2222-3333-4444-555555555555/focus")]
|
||||
public async Task Management_RequiresAnAdministrator(string method, string url)
|
||||
{
|
||||
var request = new HttpRequestMessage(new HttpMethod(method), url);
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using FluentAssertions;
|
||||
using SlpModularCms.Modules.Hero.Models;
|
||||
using SlpModularCms.Modules.Hero.Services;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Tests;
|
||||
|
||||
/// <summary>A changed focus is part of saving the hero: nothing live changes before that save.</summary>
|
||||
public class HeroFocusSaveTests
|
||||
{
|
||||
private static HeroSaveRequest Save(Guid imageId, IReadOnlyList<HeroImageFocusRequest>? focus)
|
||||
=> new("Andrea Slop", null, null, "single", [], true, null, null, [new HeroSlideRequest(null, imageId, "foto")], focus);
|
||||
|
||||
[Fact]
|
||||
public async Task TheLiveHero_KeepsItsAddresses_UntilTheHeroIsSavedWithTheNewFocus()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
var id = Guid.Parse(image.Id);
|
||||
await rig.Service.SaveAsync(Save(id, null), HeroTestRig.Admin, default);
|
||||
var before = (await rig.Public.GetActiveAsync(default))!.Slides[0].Image.Src;
|
||||
|
||||
// Nothing but a save changes what is live: the focus travels with the save request.
|
||||
(await rig.Public.GetActiveAsync(default))!.Slides[0].Image.Src.Should().Be(before);
|
||||
|
||||
await rig.Service.SaveAsync(Save(id, [new HeroImageFocusRequest(id, new FocusDto(0.5, 0.5, 1), null, new FocusDto(1.0, 0.5, 1))]), HeroTestRig.Admin, default);
|
||||
var after = (await rig.Public.GetActiveAsync(default))!.Slides[0].Image;
|
||||
|
||||
var beforeSet = before.Split('/')[3];
|
||||
after.Variants.Should().OnlyContain(v => !v.Url.Contains(beforeSet), "a changed focus gives new addresses");
|
||||
after.FocusByRatio.Should().ContainKey("tall");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheOldFiles_StayOnDisk_AfterTheSave_UntilTheCleanUp()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
var id = Guid.Parse(image.Id);
|
||||
await rig.Service.SaveAsync(Save(id, null), HeroTestRig.Admin, default);
|
||||
var oldVariant = image.Variants.First();
|
||||
|
||||
await rig.Service.SaveAsync(Save(id, [new HeroImageFocusRequest(id, new FocusDto(0.1, 0.1, 1.5))]), HeroTestRig.Admin, default);
|
||||
|
||||
(await rig.Store.ExistsAsync(oldVariant.Url["/media/".Length..], default)).Should().BeTrue("a site that still holds the old data keeps working for the retention time");
|
||||
rig.Db.HeroRetiredFiles.Should().ContainSingle(f => f.Kind == "set");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task APreparedFocusThatIsNeverSaved_LeavesOnlyUnreferencedFiles_ThatTheCleanUpRemoves()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
var id = Guid.Parse(image.Id);
|
||||
await rig.Service.SaveAsync(Save(id, null), HeroTestRig.Admin, default);
|
||||
var live = rig.Db.HeroImages.Single().SetHash;
|
||||
|
||||
// The save stops after the new files were written (here: the hero refers to a slide of another hero).
|
||||
var failing = new HeroSaveRequest("Andrea Slop", null, null, "single", [], true, null, null, [new HeroSlideRequest(Guid.NewGuid(), id, "foto")],
|
||||
[new HeroImageFocusRequest(id, new FocusDto(0.9, 0.9, 2))]);
|
||||
var act = async () => await rig.Service.SaveAsync(failing, HeroTestRig.Admin, default);
|
||||
await act.Should().ThrowAsync<HeroSaveRejectedException>();
|
||||
|
||||
rig.Db.HeroImages.Single().SetHash.Should().Be(live, "the failed save did not change the stored image");
|
||||
(await rig.Public.GetActiveAsync(default))!.Slides[0].Image.Src.Should().Contain(live);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AFocusForAnUnknownImage_IsRejected()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
|
||||
var act = async () => await rig.Service.SaveAsync(Save(Guid.NewGuid(), null) with { Slides = [], ImageFocus = [new HeroImageFocusRequest(Guid.NewGuid(), new FocusDto(0.5, 0.5, 1))] }, HeroTestRig.Admin, default);
|
||||
|
||||
(await act.Should().ThrowAsync<HeroSaveRejectedException>()).Which.Field.Should().Be("ImageFocus[0].ImageId");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-0.1, 0.5, 1.0)]
|
||||
[InlineData(0.5, 1.1, 1.0)]
|
||||
[InlineData(0.5, 0.5, 0.5)]
|
||||
[InlineData(0.5, 0.5, 4.5)]
|
||||
public void AnInvalidFocusInTheRequest_IsRefusedByTheValidation(double x, double y, double zoom)
|
||||
{
|
||||
var request = Save(Guid.NewGuid(), [new HeroImageFocusRequest(Guid.NewGuid(), new FocusDto(x, y, zoom))]);
|
||||
var results = new List<ValidationResult>();
|
||||
|
||||
Validator.TryValidateObject(request, new ValidationContext(request), results, true);
|
||||
|
||||
results.SelectMany(r => r.MemberNames).Should().Contain("ImageFocus[0]");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AValidFocusEdit_PassesTheValidation()
|
||||
{
|
||||
var request = Save(Guid.NewGuid(), [new HeroImageFocusRequest(Guid.NewGuid(), new FocusDto(0.2, 0.9, 2), new FocusDto(0.1, 0.1, 1), null)]);
|
||||
var results = new List<ValidationResult>();
|
||||
|
||||
Validator.TryValidateObject(request, new ValidationContext(request), results, true);
|
||||
|
||||
results.Should().BeEmpty();
|
||||
}
|
||||
}
|
||||
@@ -97,7 +97,7 @@ public class HeroImageServiceTests
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
var oldSet = rig.Db.HeroImages.Single().SetHash;
|
||||
|
||||
var changed = await rig.Images.SetFocusAsync(Guid.Parse(image.Id), new HeroFocusRequest(new FocusDto(0.5, 0.5, 1), null, new FocusDto(1.0, 0.5, 1)), HeroTestRig.Admin, CancellationToken.None);
|
||||
var changed = await rig.SetFocus(Guid.Parse(image.Id), new HeroFocusRequest(new FocusDto(0.5, 0.5, 1), null, new FocusDto(1.0, 0.5, 1)));
|
||||
|
||||
var newSet = rig.Db.HeroImages.Single().SetHash;
|
||||
newSet.Should().NotBe(oldSet);
|
||||
@@ -123,7 +123,7 @@ public class HeroImageServiceTests
|
||||
using var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
|
||||
await rig.Images.SetFocusAsync(Guid.Parse(image.Id), new HeroFocusRequest(new FocusDto(0.5, 0.5, 1)), HeroTestRig.Admin, CancellationToken.None);
|
||||
await rig.SetFocus(Guid.Parse(image.Id), new HeroFocusRequest(new FocusDto(0.5, 0.5, 1)));
|
||||
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().HaveCount(1);
|
||||
rig.Db.HeroRetiredFiles.Should().BeEmpty();
|
||||
@@ -135,9 +135,9 @@ public class HeroImageServiceTests
|
||||
using var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
var original = rig.Db.HeroImages.Single().SetHash;
|
||||
await rig.Images.SetFocusAsync(Guid.Parse(image.Id), new HeroFocusRequest(new FocusDto(0.5, 0.5, 1), null, new FocusDto(0.9, 0.5, 1)), HeroTestRig.Admin, CancellationToken.None);
|
||||
await rig.SetFocus(Guid.Parse(image.Id), new HeroFocusRequest(new FocusDto(0.5, 0.5, 1), null, new FocusDto(0.9, 0.5, 1)));
|
||||
|
||||
await rig.Images.SetFocusAsync(Guid.Parse(image.Id), new HeroFocusRequest(new FocusDto(0.5, 0.5, 1)), HeroTestRig.Admin, CancellationToken.None);
|
||||
await rig.SetFocus(Guid.Parse(image.Id), new HeroFocusRequest(new FocusDto(0.5, 0.5, 1)));
|
||||
|
||||
rig.Db.HeroImages.Single().SetHash.Should().Be(original);
|
||||
}
|
||||
@@ -164,10 +164,10 @@ public class HeroImageServiceTests
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
|
||||
var focus = async () => await rig.Images.SetFocusAsync(Guid.NewGuid(), new HeroFocusRequest(new FocusDto(0.5, 0.5, 1)), HeroTestRig.Admin, CancellationToken.None);
|
||||
var focus = async () => await rig.SetFocus(Guid.NewGuid(), new HeroFocusRequest(new FocusDto(0.5, 0.5, 1)));
|
||||
var delete = async () => await rig.Images.DeleteAsync(Guid.NewGuid(), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
await focus.Should().ThrowAsync<HeroImageNotFoundException>();
|
||||
await focus.Should().ThrowAsync<HeroSaveRejectedException>();
|
||||
await delete.Should().ThrowAsync<HeroImageNotFoundException>();
|
||||
}
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ public sealed class HeroTestRig : IDisposable
|
||||
var gate = new MediaProcessingGate(mediaOptions);
|
||||
var guard = new MediaUploadGuard(Processor, gate, Status, mediaOptions);
|
||||
Images = new HeroImageService(guard, Processor, Store, gate, Repository, mediaOptions, NullLogger<HeroImageService>.Instance, Time, IndexCache);
|
||||
Service = new HeroService(Repository, Options.Create(HeroOptions), NullLogger<HeroService>.Instance, Time, IndexCache);
|
||||
Service = new HeroService(Repository, Images, Options.Create(HeroOptions), NullLogger<HeroService>.Instance, Time, IndexCache);
|
||||
Public = new PublicHeroService(Repository, Options.Create(HeroOptions), Time);
|
||||
Cleanup = new HeroMediaCleanup(Repository, Store, mediaOptions, NullLogger<HeroMediaCleanup>.Instance, Time);
|
||||
}
|
||||
@@ -77,6 +77,16 @@ public sealed class HeroTestRig : IDisposable
|
||||
return stream.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>Changes the focus of an image the way the admin does: with the next save of the hero (the slides of the hero are left empty here).</summary>
|
||||
public async Task<SlpModularCms.Modules.Hero.Models.HeroImageDto> SetFocus(Guid imageId, SlpModularCms.Modules.Hero.Models.HeroFocusRequest request)
|
||||
{
|
||||
await Service.SaveAsync(
|
||||
new SlpModularCms.Modules.Hero.Models.HeroSaveRequest("Titel", null, null, "single", [], true, null, null, [],
|
||||
[new SlpModularCms.Modules.Hero.Models.HeroImageFocusRequest(imageId, request.Focus, request.Wide, request.Tall)]),
|
||||
Admin, CancellationToken.None);
|
||||
return SlpModularCms.Modules.Hero.Services.HeroMapping.ToImageDto((await Repository.GetImageAsync(imageId, CancellationToken.None))!);
|
||||
}
|
||||
|
||||
public Task<SlpModularCms.Modules.Hero.Models.HeroImageDto> Upload(byte[] bytes)
|
||||
=> Images.UploadAsync(new MemoryStream(bytes), bytes.Length, Admin, CancellationToken.None);
|
||||
|
||||
|
||||
@@ -54,6 +54,12 @@ public class HeroController(IHeroService service, IPublicHeroService publicServi
|
||||
ModelState.AddModelError(exception.Field, exception.Message);
|
||||
return ValidationProblem(ModelState);
|
||||
}
|
||||
catch (ImageRejectedException rejection)
|
||||
{
|
||||
// Cutting the variants for a changed focus needs the stored original and a free processing slot.
|
||||
var status = rejection.Reason == ImageRejection.Busy ? StatusCodes.Status429TooManyRequests : StatusCodes.Status503ServiceUnavailable;
|
||||
return StatusCode(status, new { error = rejection.Code, message = HttpTexts.From(HttpContext).Get(HeroTexts.Image.For(rejection.Reason)) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,24 +95,6 @@ public class HeroImagesController(IHeroImageService service, IOptions<MediaOptio
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/focus")]
|
||||
[ProducesResponseType<HeroImageDto>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> SetFocus(Guid id, [FromBody] HeroFocusRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Ok(await service.SetFocusAsync(id, request, HeroCaller.Id(User), cancellationToken));
|
||||
}
|
||||
catch (HeroImageNotFoundException)
|
||||
{
|
||||
return NotFound(new { error = "not_found", message = Texts().Get(HeroTexts.Image.NotFound) });
|
||||
}
|
||||
catch (ImageRejectedException rejection)
|
||||
{
|
||||
return Rejected(rejection);
|
||||
}
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status409Conflict)]
|
||||
|
||||
@@ -71,6 +71,9 @@ public record HeroButtonRequest(string? Label, string? Target);
|
||||
|
||||
public record HeroSlideRequest(Guid? Id, Guid ImageId, string? Alt, bool Decorative = false, bool IsActive = true);
|
||||
|
||||
/// <summary>A changed focus of one image; it takes effect when the hero is saved (the admin keeps it locally until then).</summary>
|
||||
public record HeroImageFocusRequest(Guid ImageId, FocusDto Focus, FocusDto? Wide = null, FocusDto? Tall = null);
|
||||
|
||||
public record HeroFocusRequest(FocusDto Focus, FocusDto? Wide = null, FocusDto? Tall = null) : IValidatableObject
|
||||
{
|
||||
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
|
||||
@@ -101,7 +104,8 @@ public record HeroSaveRequest(
|
||||
bool IsActive,
|
||||
DateTimeOffset? StartsAt,
|
||||
DateTimeOffset? EndsAt,
|
||||
IReadOnlyList<HeroSlideRequest>? Slides) : IValidatableObject
|
||||
IReadOnlyList<HeroSlideRequest>? Slides,
|
||||
IReadOnlyList<HeroImageFocusRequest>? ImageFocus = null) : IValidatableObject
|
||||
{
|
||||
public const int TitleMax = 200;
|
||||
public const int TitleMaxLines = 5;
|
||||
@@ -190,6 +194,20 @@ public record HeroSaveRequest(
|
||||
yield return new ValidationResult(texts.Get(HeroTexts.Validation.EndAfterStart), [nameof(EndsAt)]);
|
||||
}
|
||||
|
||||
var focusEdits = ImageFocus ?? [];
|
||||
for (var i = 0; i < focusEdits.Count; i++)
|
||||
{
|
||||
var edit = focusEdits[i];
|
||||
var valid = edit.ImageId != Guid.Empty
|
||||
&& edit.Focus is not null && edit.Focus.ToSetting().IsValid
|
||||
&& (edit.Wide is null || edit.Wide.ToSetting().IsValid)
|
||||
&& (edit.Tall is null || edit.Tall.ToSetting().IsValid);
|
||||
if (!valid)
|
||||
{
|
||||
yield return new ValidationResult(texts.Get(HeroTexts.Validation.FocusInvalid, args: ("maxZoom", FocusSetting.MaxZoom)), [$"{nameof(ImageFocus)}[{i}]"]);
|
||||
}
|
||||
}
|
||||
|
||||
var slides = Slides ?? [];
|
||||
for (var i = 0; i < slides.Count; i++)
|
||||
{
|
||||
|
||||
@@ -23,8 +23,14 @@ public interface IHeroImageService
|
||||
/// <exception cref="ImageRejectedException">The upload is refused; see the code.</exception>
|
||||
Task<HeroImageDto> UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Changes where the subject is (general and optionally per ratio) and cuts the variants again around it.</summary>
|
||||
Task<HeroImageDto> SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken);
|
||||
/// <summary>
|
||||
/// Applies a changed focus (general and optionally per ratio) to a tracked image: when the set changes, the variants are
|
||||
/// cut again around the new point into a NEW set of files (new addresses, nothing live is touched) and the old set is
|
||||
/// noted as retired. Nothing is saved here: the caller saves it together with the hero, so a changed focus only becomes
|
||||
/// visible when the hero is saved. When the hero is not saved the new files are never referenced and the clean-up
|
||||
/// removes them after the retention time.
|
||||
/// </summary>
|
||||
Task StageFocusAsync(HeroImage image, HeroFocusRequest request, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Removes an image nothing uses; its files go after the retention time.</summary>
|
||||
Task DeleteAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken);
|
||||
@@ -110,10 +116,8 @@ public class HeroImageService(
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task<HeroImageDto> SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken)
|
||||
public async Task StageFocusAsync(HeroImage image, HeroFocusRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var image = await repository.GetImageAsync(imageId, cancellationToken) ?? throw new HeroImageNotFoundException();
|
||||
|
||||
var oldSet = image.SetHash;
|
||||
var general = request.Focus.ToSetting().Normalize();
|
||||
image.FocusX = general.X;
|
||||
@@ -140,12 +144,8 @@ public class HeroImageService(
|
||||
var files = await RenderSetAsync(image, memory.ToArray(), storedFormat, cancellationToken);
|
||||
await store.PutSetAsync(HeroMapping.Area, image.SetHash, files, cancellationToken);
|
||||
repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = oldSet, RetiredAt = _time.GetUtcNow() });
|
||||
logger.LogInformation("Hero image {ImageId}: variants cut again for a changed focus (saved with the hero)", image.Id);
|
||||
}
|
||||
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
indexCache?.Invalidate();
|
||||
logger.LogInformation("Hero image {ImageId} focus changed by user {UserId}", imageId, callerId);
|
||||
return HeroMapping.ToImageDto(image);
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken)
|
||||
|
||||
@@ -25,6 +25,7 @@ public interface IHeroService
|
||||
|
||||
public class HeroService(
|
||||
IHeroRepository repository,
|
||||
IHeroImageService imageService,
|
||||
IOptions<HeroOptions> options,
|
||||
ILogger<HeroService> logger,
|
||||
TimeProvider? time = null,
|
||||
@@ -42,8 +43,17 @@ public class HeroService(
|
||||
var now = _time.GetUtcNow();
|
||||
var slideRequests = request.Slides ?? [];
|
||||
|
||||
var imageIds = slideRequests.Select(s => s.ImageId).Distinct().ToList();
|
||||
var focusRequests = request.ImageFocus ?? [];
|
||||
var imageIds = slideRequests.Select(s => s.ImageId).Concat(focusRequests.Select(f => f.ImageId)).Distinct().ToList();
|
||||
var images = (await repository.GetImagesAsync(imageIds, cancellationToken)).ToDictionary(i => i.Id);
|
||||
for (var i = 0; i < focusRequests.Count; i++)
|
||||
{
|
||||
if (!images.ContainsKey(focusRequests[i].ImageId))
|
||||
{
|
||||
throw new HeroSaveRejectedException($"ImageFocus[{i}].ImageId", _texts.Get(HeroTexts.Validation.Slide.ImageUnknown));
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0; i < slideRequests.Count; i++)
|
||||
{
|
||||
if (!images.ContainsKey(slideRequests[i].ImageId))
|
||||
@@ -105,6 +115,13 @@ public class HeroService(
|
||||
}
|
||||
}
|
||||
|
||||
// A changed focus is applied only now, together with the hero: the new variants are cut into new files first, then
|
||||
// the hero and the images are saved in one go, so nothing live changes before the hero is saved.
|
||||
foreach (var edit in focusRequests)
|
||||
{
|
||||
await imageService.StageFocusAsync(images[edit.ImageId], new HeroFocusRequest(edit.Focus, edit.Wide, edit.Tall), cancellationToken);
|
||||
}
|
||||
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
indexCache?.Invalidate();
|
||||
|
||||
Reference in New Issue
Block a user