From 6999f5b2ba6723273a198b20c253513b20ce6c53 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 16 Nov 2026 23:26:47 +0100 Subject: [PATCH] Hero-admin: schakelaar Actief, destructieve knoppen rood, slide-kopjes, juiste voorvertoning in het focusvenster, status per foto - Schakelaar (role=switch) Actief / Niet actief bij de knoppen, gedimde rij; 'Verberg voor schermlezers'; veld 'Beschrijving' binnen een groep 'Slide N' - Alle foto's zonder complete set tonen 'Wordt verwerkt' (voortgang bij de foto die bezig is, 'in de wachtrij' bij de rest); totaal bovenaan telt ook nog niet opgeslagen foto's - Per foto 'Verwerking afgerond' (zelfde weergave voor een hergebruikte foto), foto direct bruikbaar; niet-opgeslagen foto's worden zelf ververst (GET /hero/images/{id}), ook in een achtergrondtab - Focusvenster toont de hele foto (full-preview in elke set, achtergrond-aanvulling voor oude sets) in plaats van de uitgesneden wide-variant (vervorming) - Prullenbak en 'Wijzigingen weggooien' in de destructieve stijl - upload-respons: reused (intern) Co-Authored-By: Claude Sonnet 5.5 --- .../assumptions-and-open-questions.md | 3 + .../features/hero/components/FocusDialog.tsx | 16 +- .../hero/components/ProcessingStatus.tsx | 40 +++- .../features/hero/components/SlideSwitch.tsx | 33 +++ .../hero/components/SortableSlide.tsx | 7 +- .../hero/components/UnsavedChangesGuard.tsx | 2 +- .../src/features/hero/lib/focusMath.test.ts | 46 ++++ frontend/src/features/hero/mocks/handlers.ts | 6 + .../src/features/hero/pages/HeroPage.test.tsx | 216 +++++++++++++++++- frontend/src/features/hero/pages/HeroPage.tsx | 89 ++++++-- frontend/src/features/hero/services/hooks.ts | 10 + frontend/src/features/hero/services/types.ts | 4 + frontend/src/i18n/locales/en/translation.json | 22 +- frontend/src/i18n/locales/nl/translation.json | 22 +- frontend/src/index.css | 21 ++ openapi/slpsoftware.v1.json | 68 ++++++ .../HeroAsfSiteE2ETests.cs | 16 +- .../HeroInjectionPipelineTests.cs | 16 +- .../Media/VariantPlanner.cs | 18 ++ .../HeroFocusSaveTests.cs | 108 +++++++++ .../Controllers/HeroControllers.cs | 10 + .../Models/HeroModels.cs | 4 +- .../Repositories/HeroRepository.cs | 6 + .../Services/HeroImageService.cs | 60 ++++- .../Services/HeroMapping.cs | 24 +- 25 files changed, 794 insertions(+), 73 deletions(-) create mode 100644 frontend/src/features/hero/components/SlideSwitch.tsx diff --git a/aidlc-docs/features/hero-module/assumptions-and-open-questions.md b/aidlc-docs/features/hero-module/assumptions-and-open-questions.md index aa94600..a965d50 100644 --- a/aidlc-docs/features/hero-module/assumptions-and-open-questions.md +++ b/aidlc-docs/features/hero-module/assumptions-and-open-questions.md @@ -31,3 +31,6 @@ Kept while Bryan was away (2026-11-16): no questions to him, a likely assumption | 25 | **Variants are cut in the background**, not inside the upload or save request (2026-11-16, found on the ASF test host: saving 8 photos took 60 s+ on the Pi and the proxy cut it with a 504). | Upload and save return at once; `HeroRenderService` cuts one image at a time and switches an image to its new set when it is complete (old set stays live meanwhile); an image without a set is not published; a failing image is tried 3 times, then left until the next restart. Measured on a 20-core PC: upload 3.5-8.8 s and save of 8 changed focus points 39.6 s before, 0.1 s and 0.1 s after (the 37.5 s of cutting moved to the background, 4.7 s per photo). On the Pi: about 25-30 s per photo, 4 minutes for 8. | A longer proxy time-out is then not needed; if cutting should be faster, reduce the variant set or the AVIF effort. | `HeroImageService.RenderNextPendingAsync`, `HeroRenderService`, `HeroSaveTimingTests` | | 26 | **A large photo never finished** (ASF test, 4.4 MB): every variant decoded the whole photo again and each ran under the 20 s decode limit, so on the Pi a variant timed out, the whole set was retried 3 times and the image was given up silently. | One decode for the whole set, a width is resized once for both formats and from the previous width; a job limit of 600 s for the set (the image library clock is set above it); a failing image waits for the next round instead of blocking the queue; progress per variant in the admin and the log; retry button. Measured on a 6000x4000 JPEG (3.1 MB): 21.1 s per set before, 6.4 s after, on a fast PC (thread limit made no difference). On the Pi roughly 6x: about 40 s. | Other limits via `Media__*`; skipping AVIF would save about half of the time again. | `MagickImageProcessor.RenderSet`, `HeroRenderService`, `HeroBigPhotoTimingTests` | | 27 | The admin page must have **no inline script** (CSP `script-src 'self'`). | The theme script is `/theme-init.js`; a test and the smoke test check it. | n/a | `frontend/public/theme-init.js`, `frontend/src/csp.test.ts`, `scripts/smoke-site.sh` | +| 28 | **The focus dialog showed a stretched photo** for any photo that is not 3:2: it used the published wide crop (`image.src`) as if it were the whole photo. | Every set now also holds a full-frame preview (`full-.webp`, the whole picture at its own shape, at most 1280 wide); the admin API gives it as `previewSrc`, it is not in `variants` and not published to websites. Sets made before it existed get only that file added by the background renderer (not shown as processing, no address changes). | Without a preview yet the dialog says so instead of showing a wrong picture. | `VariantPlanner.Preview`, `HeroMapping.PreviewSrc`, `FocusDialog` | +| 29 | **A photo could stay "processing" for ever** in the admin: a photo that was uploaded but not saved yet only had the state of the upload response. | The page now asks the server for those photos one by one (`GET /api/v1/hero/images/{id}`, every 5 s while processing, also in a background tab); each photo shows its own state and, when done, a short "Processing finished" note on that photo (no toast). A photo that was already in the CMS (`reused`, internal only) looks the same and is ready at once. | n/a | `heroImageQuery`, `DoneStatus` | + diff --git a/frontend/src/features/hero/components/FocusDialog.tsx b/frontend/src/features/hero/components/FocusDialog.tsx index fb3743f..fdca308 100644 --- a/frontend/src/features/hero/components/FocusDialog.tsx +++ b/frontend/src/features/hero/components/FocusDialog.tsx @@ -38,6 +38,8 @@ 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(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('general'); const [general, setGeneral] = useState(image.focus ?? CENTRE); const [wide, setWide] = useState(image.wideFocus); @@ -143,7 +145,13 @@ function FocusEditor({ image, onApply, onClose }: { image: HeroImageDto; onApply onKeyDown={onKeyDown} data-testid="focus-area" > - + {previewUrl ? ( + + ) : ( +

+ {t('hero.focus.previewPending')} +

+ )}
- + />}
); diff --git a/frontend/src/features/hero/components/ProcessingStatus.tsx b/frontend/src/features/hero/components/ProcessingStatus.tsx index 9213f55..9b0c11d 100644 --- a/frontend/src/features/hero/components/ProcessingStatus.tsx +++ b/frontend/src/features/hero/components/ProcessingStatus.tsx @@ -1,8 +1,8 @@ -import { Loader2 } from 'lucide-react'; +import { Check, Loader2 } from 'lucide-react'; import { useTranslation } from 'react-i18next'; import { Button } from '@/components/ui/button'; import { useRetryHeroImage } from '../services/hooks'; -import type { HeroAdminDto } from '../services/types'; +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 }) { @@ -13,19 +13,18 @@ export function Spinner({ className = 'size-4' }: { className?: string }) { * 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({ hero }: { hero: HeroAdminDto }) { +export function ProcessingStatus({ images }: { images: HeroImageDto[] }) { const { t } = useTranslation(); const retry = useRetryHeroImage(); - const total = hero.slides.length; - const waiting = hero.slides.filter((s) => s.image.processing); + 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((s) => s.image.failed); + 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 busyIndex = waiting.findIndex((s) => s.image.renderTotal); - const busy = busyIndex === -1 ? null : waiting[busyIndex].image; + 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); @@ -61,7 +60,7 @@ export function ProcessingStatus({ hero }: { hero: HeroAdminDto }) { type="button" className="underline underline-offset-2 hover:text-foreground disabled:opacity-50" disabled={retry.isPending} - onClick={() => waiting.forEach((s) => retry.mutate(s.imageId))} + onClick={() => waiting.forEach((image) => retry.mutate(image.id))} data-testid="hero-processing-retry-all" > {t('hero.processing.retry')} @@ -78,7 +77,7 @@ export function ProcessingStatus({ hero }: { hero: HeroAdminDto }) { variant="outline" size="sm" disabled={retry.isPending} - onClick={() => failed.forEach((s) => retry.mutate(s.imageId))} + onClick={() => failed.forEach((image) => retry.mutate(image.id))} data-testid="hero-processing-retry" > {t('hero.processing.retry')} @@ -107,6 +106,7 @@ export function PhotoPlaceholder({ failed, testId, step }: { failed: boolean; te {failed ? null : } {failed ? t('hero.slides.failed') : t('hero.slides.processing')} {!failed && step ? {step.done}/{step.total} : null} + {!failed && !step ? {t('hero.slides.queued')} : null}
); } @@ -134,3 +134,23 @@ export function RecutThumbnail({ src, failed, testId, step }: { src: string; fai ); } + +/** + * 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 ( +
+ {done && ( + + + )} +
+ ); +} diff --git a/frontend/src/features/hero/components/SlideSwitch.tsx b/frontend/src/features/hero/components/SlideSwitch.tsx new file mode 100644 index 0000000..6c49000 --- /dev/null +++ b/frontend/src/features/hero/components/SlideSwitch.tsx @@ -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 ( + + ); +} diff --git a/frontend/src/features/hero/components/SortableSlide.tsx b/frontend/src/features/hero/components/SortableSlide.tsx index 1002759..b11d935 100644 --- a/frontend/src/features/hero/components/SortableSlide.tsx +++ b/frontend/src/features/hero/components/SortableSlide.tsx @@ -8,6 +8,8 @@ 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; } @@ -16,7 +18,7 @@ interface SortableSlideProps { * 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, children }: SortableSlideProps) { +export function SortableSlide({ id, index, dimmed = false, children }: SortableSlideProps) { const { t } = useTranslation(); const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = useSortable({ id }); @@ -24,9 +26,10 @@ export function SortableSlide({ id, index, children }: SortableSlideProps) {
  • - diff --git a/frontend/src/features/hero/lib/focusMath.test.ts b/frontend/src/features/hero/lib/focusMath.test.ts index 39ba846..61c7e6b 100644 --- a/frontend/src/features/hero/lib/focusMath.test.ts +++ b/frontend/src/features/hero/lib/focusMath.test.ts @@ -59,3 +59,49 @@ describe('normalizeFocus and roundHalfUp', () => { 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); + } + }); +}); diff --git a/frontend/src/features/hero/mocks/handlers.ts b/frontend/src/features/hero/mocks/handlers.ts index 8c9824d..be1fb98 100644 --- a/frontend/src/features/hero/mocks/handlers.ts +++ b/frontend/src/features/hero/mocks/handlers.ts @@ -17,6 +17,7 @@ const seedImage = (id: string, width = 1600, height = 1067): HeroImageDto => ({ ], processing: false, failed: false, + previewSrc: '/media/hero/0123456789abcdef/full-1280.webp', }); export const emptyHero = (): HeroAdminDto => ({ @@ -127,6 +128,11 @@ export const heroHandlers = [ 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 }); diff --git a/frontend/src/features/hero/pages/HeroPage.test.tsx b/frontend/src/features/hero/pages/HeroPage.test.tsx index 17d6b23..e3dc35c 100644 --- a/frontend/src/features/hero/pages/HeroPage.test.tsx +++ b/frontend/src/features/hero/pages/HeroPage.test.tsx @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; import { fireEvent, screen, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { http, HttpResponse } from 'msw'; @@ -634,14 +634,15 @@ describe('Order by dragging, wording and calm waiting', () => { } }); - it('speaks plain language: no alt text, decoration with an explanation, and a short guide per part', async () => { - setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] }); + it('speaks plain language: a plain Description field inside a titled slide, no alt text, and a short guide per part', async () => { + setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), slide(2)] }); await openPage(); - expect(screen.getByLabelText(/Beschrijving afbeelding 1$|Description of image 1$/)).toBeInTheDocument(); - const row = within(screen.getByTestId('hero-slide-0')); - expect(row.getByText(/Alleen versiering|Decoration only/)).toBeInTheDocument(); - expect(row.getByText(/niets toevoegt aan de inhoud|adds nothing to the content/)).toBeInTheDocument(); + const first = screen.getByRole('group', { name: /^Slide 1$/ }); + expect(within(first).getByLabelText(/^(Beschrijving|Description)$/)).toBeInTheDocument(); + expect(within(first).getByText(/Verberg voor schermlezers|Hide from screen readers/)).toBeInTheDocument(); + expect(within(first).queryByText(/niets toevoegt aan de inhoud|adds nothing to the content/)).not.toBeInTheDocument(); + expect(screen.getByRole('group', { name: /^Slide 2$/ })).toBeInTheDocument(); expect(screen.queryByText(/alt-tekst|alt text/i)).not.toBeInTheDocument(); const help = screen.getByTestId('hero-help'); expect(help).toHaveTextContent(/#contact/); @@ -649,6 +650,55 @@ describe('Order by dragging, wording and calm waiting', () => { expect(help).toHaveTextContent(/Planning|Schedule/); }); + it('numbers the slides by their current order, also after the order changed', async () => { + setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), slide(2)] }); + await openPage(); + + await userEvent.click(screen.getByTestId('hero-slide-1-up')); + + expect(within(screen.getByRole('group', { name: /^Slide 1$/ })).getByTestId('hero-slide-0-alt')).toHaveValue('Foto 2'); + }); + + it('has a switch per slide: role switch, Active or Not active, keyboard, and a dimmed row when off', async () => { + setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), slide(2)] }); + await openPage(); + const toggle = screen.getByTestId('hero-slide-0-active'); + expect(toggle).toHaveAttribute('role', 'switch'); + expect(toggle).toBeChecked(); + expect(toggle).toHaveTextContent(/^(Actief|Active)/); + expect(screen.getByTestId('hero-slide-0')).not.toHaveAttribute('data-inactive'); + + toggle.focus(); + await userEvent.keyboard('{Enter}'); + + expect(toggle).not.toBeChecked(); + expect(toggle).toHaveTextContent(/^(Niet actief|Not active)/); + expect(screen.getByTestId('hero-slide-0')).toHaveAttribute('data-inactive', 'true'); + expect(screen.getByTestId('hero-slide-1')).not.toHaveAttribute('data-inactive'); + await userEvent.click(screen.getByTestId('hero-save')); + await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1)); + expect(getSavedHeroRequests()[0].slides.map((x) => x.isActive)).toEqual([false, true]); + }); + + it('marks every photo without a complete set as being processed, the one being cut with its step and the rest as queued', async () => { + const waiting = (n: number, step?: [number, number]) => ({ + ...slide(n), + image: { ...slide(n).image, variants: [], src: '', processing: true, renderDone: step?.[0] ?? null, renderTotal: step?.[1] ?? null }, + }); + setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [waiting(1, [3, 16]), waiting(2), waiting(3)] }); + await openPage(); + + for (const i of [0, 1, 2]) { + const box = await screen.findByTestId(`hero-slide-${i}-processing`, {}, T); + expect(box).toHaveClass('hero-shimmer'); + expect(box).toHaveTextContent(/Wordt verwerkt|Processing/); + } + expect(screen.getByTestId('hero-slide-0-processing-step')).toHaveTextContent('3/16'); + expect(screen.getByTestId('hero-slide-1-processing-queued')).toBeInTheDocument(); + expect(screen.getByTestId('hero-slide-2-processing-queued')).toBeInTheDocument(); + expect(screen.getByTestId('hero-processing-count')).toHaveTextContent(/0 van 3|0 of 3/); + }); + it('keeps the waiting placeholder mounted through the background refresh, so its animation keeps running', async () => { const waiting = { ...slide(1), image: { ...slide(1).image, variants: [], src: '', processing: true } }; setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [waiting, slide(2)] }); @@ -736,3 +786,155 @@ describe('A changed focus point makes a new crop in the background', () => { await waitFor(() => expect(getRetriedImages()).toEqual([waiting.imageId]), T); }); }); + + +describe('Focus dialog shows the whole picture', () => { + beforeEach(() => { + resetMockHero(); + }); + + const portraitSlide = () => { + const base = slide(1); + // A portrait photo of 2000x3000: the published crops are wide/tall, but the dialog needs the whole picture. + return { ...base, image: { ...base.image, width: 2000, height: 3000, src: '/media/hero/0123456789abcdef/wide-1600.webp', previewSrc: '/media/hero/0123456789abcdef/full-1280.webp' } }; + }; + + it('uses the full-frame preview at the shape of the original, not the wide crop', async () => { + setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [portraitSlide()] }); + await openPage(); + + await userEvent.click(screen.getByTestId('hero-slide-0-focus')); + + const area = await screen.findByTestId('focus-area', {}, T); + expect(area.style.aspectRatio.replace(/\s/g, '')).toBe('2000/3000'); + const picture = area.querySelector('img')!; + expect(picture.getAttribute('src')).toContain('full-1280.webp'); + expect(picture.getAttribute('src')).not.toContain('wide-1600'); + expect(picture).toHaveClass('object-cover'); + for (const ratio of ['wide', 'tall']) { + expect(screen.getByTestId(`focus-preview-${ratio}`).querySelector('img')!.getAttribute('src')).toContain('full-1280.webp'); + } + }); + + it('says the preview is being prepared when the server has none yet, instead of showing a wrong picture', async () => { + const base = portraitSlide(); + setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [{ ...base, image: { ...base.image, previewSrc: null } }] }); + await openPage(); + + await userEvent.click(screen.getByTestId('hero-slide-0-focus')); + + expect(await screen.findByTestId('focus-preview-pending', {}, T)).toBeInTheDocument(); + expect(screen.getByTestId('focus-area').querySelector('img')).toBeNull(); + }); +}); + +describe('Destructive actions are red', () => { + beforeEach(() => { + resetMockHero(); + }); + + it('shows the remove button of every slide in the destructive style, with a name', async () => { + setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), slide(2)] }); + await openPage(); + + for (const i of [0, 1]) { + const remove = screen.getByTestId(`hero-slide-${i}-remove`); + expect(remove).toHaveClass('bg-destructive'); + expect(remove).toHaveAccessibleName(/Slide verwijderen|Remove slide/); + } + }); + + it('shows Discard changes in the destructive style', async () => { + setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] }); + await openPage(); + await userEvent.type(screen.getByTestId('hero-title-input'), 'X'); + await screen.findByTestId('hero-unsaved'); + + await userEvent.click(screen.getByTestId('nav-dashboard')); + + expect(await screen.findByTestId('hero-leave-discard', {}, T)).toHaveClass('bg-destructive'); + expect(screen.getByTestId('hero-leave-stay')).not.toHaveClass('bg-destructive'); + }); +}); + + +describe('Each photo shows by itself when its processing is finished', () => { + beforeEach(() => { + resetMockHero(); + vi.restoreAllMocks(); + }); + + const jpg = (name: string) => new File(['x'], name, { type: 'image/jpeg' }); + const cutting = (id: string) => ({ + id, width: 5757, height: 3838, focus: { x: 0.5, y: 0.5, zoom: 1 }, wideFocus: null, tallFocus: null, + src: '', variants: [], processing: true, failed: false, previewSrc: null, + }); + const ready = (id: string) => ({ + ...cutting(id), src: '/media/hero/0123456789abcdef/wide-1600.webp', processing: false, + variants: [{ ratio: 'wide', width: 960, height: 640, type: 'image/webp', url: '/media/hero/0123456789abcdef/wide-960.webp' }], + previewSrc: '/media/hero/0123456789abcdef/full-1280.webp', + }); + + it('turns the placeholder of a photo that was not saved yet into a finished note on that photo, by itself, and the photo can be worked on at once', async () => { + const id = '70000000-0000-0000-0000-000000000001'; + let finished = false; + server.use( + http.post(`${API_BASE}/api/v1/hero/images`, () => HttpResponse.json(cutting(id), { status: 201 })), + http.get(`${API_BASE}/api/v1/hero/images/${id}`, () => HttpResponse.json(finished ? ready(id) : cutting(id))), + ); + await openPage(); + + await userEvent.upload(screen.getByTestId('hero-upload'), jpg('groot.jpg')); + expect(await screen.findByTestId('hero-slide-0-processing', {}, T)).toHaveClass('hero-shimmer'); + expect(screen.getByTestId('hero-slide-0-focus')).toBeDisabled(); + expect(screen.queryByTestId('hero-slide-0-done-text')).not.toBeInTheDocument(); + + // The server is done; nobody saves or reloads: the page asks again by itself. + finished = true; + const note = await screen.findByTestId('hero-slide-0-done-text', {}, { timeout: 12000 }); + expect(note).toHaveTextContent(/Verwerking afgerond|Processing finished/); + expect(screen.getByTestId('hero-slide-0-done')).toHaveAttribute('role', 'status'); + expect(screen.getByTestId('hero-slide-0-done')).toHaveAttribute('aria-live', 'polite'); + expect(screen.queryByTestId('hero-slide-0-processing')).not.toBeInTheDocument(); + expect(screen.getByTestId('hero-slide-0-focus')).toBeEnabled(); + // The note names the slide for a screen reader, and goes away by itself after a few seconds. + expect(note.textContent).toMatch(/Slide 1: (verwerking afgerond|processing finished)/); + await waitFor(() => expect(screen.queryByTestId('hero-slide-0-done-text')).not.toBeInTheDocument(), { timeout: 8000 }); + }, 30000); + + it('shows the same finished note, at once and without a placeholder, for a photo that was already in the CMS', async () => { + const id = '70000000-0000-0000-0000-000000000002'; + server.use(http.post(`${API_BASE}/api/v1/hero/images`, () => HttpResponse.json({ ...ready(id), reused: true }, { status: 201 }))); + await openPage(); + + await userEvent.upload(screen.getByTestId('hero-upload'), jpg('zelfde.jpg')); + + expect(await screen.findByTestId('hero-slide-0-done-text', {}, T)).toHaveTextContent(/Verwerking afgerond|Processing finished/); + expect(screen.queryByTestId('hero-slide-0-processing')).not.toBeInTheDocument(); + expect(screen.getByTestId('hero-slide-0-focus')).toBeEnabled(); + expect(screen.queryByText(/stond al|already/i)).not.toBeInTheDocument(); + }); + + it('finishes photo by photo: the first one can be worked on while the second is still busy, and the total at the top follows', async () => { + const ids = ['70000000-0000-0000-0000-000000000011', '70000000-0000-0000-0000-000000000012']; + let n = 0; + const finished = new Set(); + server.use( + http.post(`${API_BASE}/api/v1/hero/images`, () => HttpResponse.json(cutting(ids[n++]), { status: 201 })), + http.get(`${API_BASE}/api/v1/hero/images/${ids[0]}`, () => HttpResponse.json(finished.has(ids[0]) ? ready(ids[0]) : cutting(ids[0]))), + http.get(`${API_BASE}/api/v1/hero/images/${ids[1]}`, () => HttpResponse.json(finished.has(ids[1]) ? ready(ids[1]) : cutting(ids[1]))), + ); + await openPage(); + await userEvent.upload(screen.getByTestId('hero-upload'), [jpg('a.jpg'), jpg('b.jpg')]); + await screen.findByTestId('hero-slide-1-processing', {}, T); + expect(screen.getByTestId('hero-processing-count')).toHaveTextContent(/0 van 2|0 of 2/); + + finished.add(ids[0]); + await screen.findByTestId('hero-slide-0-done-text', {}, { timeout: 12000 }); + + expect(screen.getByTestId('hero-slide-0-focus')).toBeEnabled(); + expect(screen.getByTestId('hero-slide-1-processing')).toBeInTheDocument(); + expect(screen.getByTestId('hero-slide-1-focus')).toBeDisabled(); + expect(screen.getByTestId('hero-processing-count')).toHaveTextContent(/1 van 2|1 of 2/); + }, 30000); +}); diff --git a/frontend/src/features/hero/pages/HeroPage.tsx b/frontend/src/features/hero/pages/HeroPage.tsx index 364f00b..8add405 100644 --- a/frontend/src/features/hero/pages/HeroPage.tsx +++ b/frontend/src/features/hero/pages/HeroPage.tsx @@ -1,4 +1,5 @@ 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'; @@ -14,13 +15,14 @@ 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 { PhotoPlaceholder, ProcessingStatus, RecutThumbnail } from '../components/ProcessingStatus'; +import { DoneStatus, PhotoPlaceholder, ProcessingStatus, RecutThumbnail } from '../components/ProcessingStatus'; +import { SlideSwitch } from '../components/SlideSwitch'; import { SortableSlide } from '../components/SortableSlide'; import { UnsavedChangesGuard } from '../components/UnsavedChangesGuard'; import { UploadProgress, type UploadItem } from '../components/UploadProgress'; import { mediaUrl } from '../lib/media'; import { fromLocalInput, heroFormSchema, toLocalInput, type HeroFormData } from '../schemas/hero'; -import { useHero, useHeroUploadLimits, useSaveHero, useUploadHeroImage } from '../services/hooks'; +import { heroImageQuery, useHero, useHeroUploadLimits, useSaveHero, useUploadHeroImage } from '../services/hooks'; import type { HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest } from '../services/types'; const textareaClass = @@ -131,7 +133,6 @@ export function HeroPage() { )} - {hero && } {hero && } ); @@ -155,6 +156,7 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) { const { register, + setValue, handleSubmit, control, formState: { errors, isDirty }, @@ -164,11 +166,48 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) { const watchedSlides = useWatch({ control, name: 'slides' }) ?? []; // The images of the saved hero (always current: a change of focus refreshes them) plus the ones uploaded in this session. + // 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 = { ...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]); + }, [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>({}); + const wasProcessing = useRef>({}); + 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); @@ -219,6 +258,8 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) { 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; @@ -293,6 +334,7 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) { return (
    + images[f.imageId]).filter((image): image is HeroImageDto => image !== undefined)} /> setServerError(null)} />
    @@ -423,7 +465,8 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) { const image = images[field.imageId]; const decorative = watchedSlides[index]?.decorative ?? false; return ( - + +
    {image && image.variants.length === 0 ? ( ) : image?.processing ? ( @@ -433,29 +476,31 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) { ) : (
    ?
    )} -
    - + +
    +
    +

    + {t('hero.slides.number', { n: index + 1 })} +

    +

    {t('hero.slides.altHint')}

    {focusEdits[field.imageId] && (

    {t('hero.slides.focusPending')}

    )} -
    - - -
    +
    -
    +
    + setValue(`slides.${index}.isActive` as const, value, { shouldDirty: true })} + testId={`hero-slide-${index}-active`} + slideNumber={index + 1} + /> @@ -465,7 +510,7 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) { -
    diff --git a/frontend/src/features/hero/services/hooks.ts b/frontend/src/features/hero/services/hooks.ts index 0b25e07..2a8faf5 100644 --- a/frontend/src/features/hero/services/hooks.ts +++ b/frontend/src/features/hero/services/hooks.ts @@ -11,6 +11,8 @@ export function useHero() { queryFn: () => api.get('/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, }); } @@ -58,3 +60,11 @@ export function useHeroUploadLimits() { 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(`/api/v1/hero/images/${imageId}`), + refetchInterval: (query: { state: { data?: HeroImageDto } }) => (query.state.data?.processing ? 5000 : false), + refetchIntervalInBackground: true, +}); diff --git a/frontend/src/features/hero/services/types.ts b/frontend/src/features/hero/services/types.ts index 6922051..b458fbe 100644 --- a/frontend/src/features/hero/services/types.ts +++ b/frontend/src/features/hero/services/types.ts @@ -30,6 +30,10 @@ export interface HeroImageDto { /** 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 { diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index 718b1b3..0e45cc1 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -647,13 +647,12 @@ "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 of image {{n}}", - "decorative": "Decoration only (no description needed)", - "active": "Show", + "alt": "Description", + "decorative": "Hide from screen readers", "up": "Move up", "down": "Move down", "focus": "Set focus", - "remove": "Remove from the hero", + "remove": "Remove slide", "ceiling": "Only the first {{max}} images are shown on the website.", "focusPending": "Focus changed, not saved yet.", "processing": "Processing…", @@ -661,11 +660,17 @@ "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.", - "decorativeHint": "Choose this when the photo adds nothing to the content; a screen reader then skips it.", "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." + "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" }, "processing": { "count": "{{done}} of {{total}} photos processed", @@ -698,7 +703,8 @@ "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." + "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.", @@ -751,7 +757,7 @@ }, "slides": { "name": "Images", - "text": "Upload photos, describe what is in them and set the order (drag or use the arrows). ‘Show’ switches a photo on or off. Choose ‘Decoration only’ for a photo that adds nothing to the content." + "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", diff --git a/frontend/src/i18n/locales/nl/translation.json b/frontend/src/i18n/locales/nl/translation.json index fcb9733..6c6ac80 100644 --- a/frontend/src/i18n/locales/nl/translation.json +++ b/frontend/src/i18n/locales/nl/translation.json @@ -647,13 +647,12 @@ "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 afbeelding {{n}}", - "decorative": "Alleen versiering (geen beschrijving nodig)", - "active": "Tonen", + "alt": "Beschrijving", + "decorative": "Verberg voor schermlezers", "up": "Omhoog", "down": "Omlaag", "focus": "Focus instellen", - "remove": "Verwijderen uit de hero", + "remove": "Slide verwijderen", "ceiling": "Alleen de eerste {{max}} afbeeldingen worden getoond op de website.", "focusPending": "Focus gewijzigd, nog niet opgeslagen.", "processing": "Wordt verwerkt…", @@ -661,11 +660,17 @@ "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.", - "decorativeHint": "Kies dit als de foto niets toevoegt aan de inhoud; dan leest een schermlezer hem niet voor.", "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." + "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" }, "processing": { "count": "{{done}} van {{total}} foto’s verwerkt", @@ -698,7 +703,8 @@ "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." + "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.", @@ -751,7 +757,7 @@ }, "slides": { "name": "Afbeeldingen", - "text": "Upload foto’s, beschrijf wat erop staat en bepaal de volgorde (slepen of de pijltjes). Met ‘Tonen’ zet je een foto aan of uit. Kies ‘Alleen versiering’ voor een foto die niets toevoegt aan de inhoud." + "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", diff --git a/frontend/src/index.css b/frontend/src/index.css index fe4d45e..e16adab 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -149,3 +149,24 @@ 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; + } +} diff --git a/openapi/slpsoftware.v1.json b/openapi/slpsoftware.v1.json index 1e6f93e..d5dfda9 100644 --- a/openapi/slpsoftware.v1.json +++ b/openapi/slpsoftware.v1.json @@ -698,6 +698,12 @@ "id": { "type": "string" }, + "previewSrc": { + "type": [ + "null", + "string" + ] + }, "processing": { "default": false, "type": "boolean" @@ -720,6 +726,10 @@ "string" ] }, + "reused": { + "default": false, + "type": "boolean" + }, "src": { "type": "string" }, @@ -3144,6 +3154,64 @@ "tags": [ "HeroImages" ] + }, + "get": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "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" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + }, + "description": "Not Found" + } + }, + "tags": [ + "HeroImages" + ] } }, "/api/v1/hero/images/{id}/retry": { diff --git a/src/SlpModularCms.Api.Tests/HeroAsfSiteE2ETests.cs b/src/SlpModularCms.Api.Tests/HeroAsfSiteE2ETests.cs index fe10d5a..c93a3c3 100644 --- a/src/SlpModularCms.Api.Tests/HeroAsfSiteE2ETests.cs +++ b/src/SlpModularCms.Api.Tests/HeroAsfSiteE2ETests.cs @@ -115,9 +115,23 @@ public class HeroAsfSiteE2ETests : IClassFixture await InScope(async sp => { // The variants are cut by the background renderer in production; here it is run to the end at once. - while (await sp.GetRequiredService().RenderNextPendingAsync(new HashSet(), default) is not null) + // The shared test database may hold rows of earlier runs whose files are gone: those fail and are skipped, + // the way the background renderer gives up on them. + var skip = new HashSet(); + while (true) + { + try { + if (await sp.GetRequiredService().RenderNextPendingAsync(skip, default) is null) + { + break; + } } + catch (HeroImageRenderException failure) + { + skip.Add(failure.ImageId); + } + } return true; }); diff --git a/src/SlpModularCms.Api.Tests/HeroInjectionPipelineTests.cs b/src/SlpModularCms.Api.Tests/HeroInjectionPipelineTests.cs index 8c18e87..628722e 100644 --- a/src/SlpModularCms.Api.Tests/HeroInjectionPipelineTests.cs +++ b/src/SlpModularCms.Api.Tests/HeroInjectionPipelineTests.cs @@ -136,8 +136,22 @@ public class HeroInjectionPipelineTests : IClassFixture await InScope(async sp => { // The variants are cut by the background renderer in production; here it is run to the end at once. - while (await sp.GetRequiredService().RenderNextPendingAsync(new HashSet(), default) is not null) + // The shared test database may hold rows of earlier runs whose files are gone: those fail and are skipped, + // the way the background renderer gives up on them. + var skip = new HashSet(); + while (true) { + try + { + if (await sp.GetRequiredService().RenderNextPendingAsync(skip, default) is null) + { + break; + } + } + catch (HeroImageRenderException failure) + { + skip.Add(failure.ImageId); + } } return true; diff --git a/src/SlpModularCms.Core/Media/VariantPlanner.cs b/src/SlpModularCms.Core/Media/VariantPlanner.cs index 68f3d85..4cdae7d 100644 --- a/src/SlpModularCms.Core/Media/VariantPlanner.cs +++ b/src/SlpModularCms.Core/Media/VariantPlanner.cs @@ -21,6 +21,24 @@ public static class VariantPlanner /// planned in WebP, and in AVIF when contains it. WebP is required: without WebP the /// plan falls back to JPEG so a platform without a WebP encoder still publishes something. /// + /// The ratio name of the full-frame preview (the whole picture, not cut around a point). + public const string PreviewRatioName = "full"; + + /// The widest full-frame preview. + public const int PreviewMaxWidth = 1280; + + /// + /// The full-frame preview an administrator needs to choose the focus point: the WHOLE oriented picture at its own + /// shape, scaled down to at most (never up). Not published to websites. + /// + public static VariantSpec Preview(int sourceWidth, int sourceHeight, IReadOnlySet outputs) + { + var width = Math.Min(PreviewMaxWidth, sourceWidth); + var height = Math.Max(1, (int)Math.Round(width * (double)sourceHeight / sourceWidth)); + var (format, quality) = outputs.Contains(ImageFormat.WebP) ? (ImageFormat.WebP, WebPQuality) : (ImageFormat.Jpeg, JpegQuality); + return new VariantSpec(new Ratio(PreviewRatioName, sourceWidth, sourceHeight), width, height, format, quality, new CropRect(0, 0, sourceWidth, sourceHeight)); + } + public static IReadOnlyList Plan( int sourceWidth, int sourceHeight, diff --git a/src/SlpModularCms.Modules.Hero.Tests/HeroFocusSaveTests.cs b/src/SlpModularCms.Modules.Hero.Tests/HeroFocusSaveTests.cs index 9dc98ea..ac7195f 100644 --- a/src/SlpModularCms.Modules.Hero.Tests/HeroFocusSaveTests.cs +++ b/src/SlpModularCms.Modules.Hero.Tests/HeroFocusSaveTests.cs @@ -264,4 +264,112 @@ public class HeroFocusSaveTests await act.Should().ThrowAsync(); done.Should().BeLessThan(specs.Count); } + + [Fact] + public async Task EveryImageWithoutACompleteSet_IsProcessing_InTheAdminApi_AndTwoNewPhotosAreBothCut() + { + using var rig = new HeroTestRig(); + // The helper Upload cuts everything that is pending, so the finished photo is made first. + var ready = await rig.Upload(HeroTestRig.Photo(seed: 3)); + var first = await rig.UploadWithoutRendering(HeroTestRig.Photo(seed: 1)); + var second = await rig.UploadWithoutRendering(HeroTestRig.Photo(seed: 2)); + var request = new HeroSaveRequest("Titel", null, null, "slideshow", [], true, null, null, + [new HeroSlideRequest(null, Guid.Parse(first.Id), "een"), new HeroSlideRequest(null, Guid.Parse(second.Id), "twee"), new HeroSlideRequest(null, Guid.Parse(ready.Id), "drie")]); + + var saved = await rig.Service.SaveAsync(request, HeroTestRig.Admin, default); + + saved.Slides.Select(s => s.Image.Processing).Should().Equal(true, true, false); + (await rig.Service.GetAsync(default)).Slides.Select(s => s.Image.Processing).Should().Equal(true, true, false); + + (await rig.RenderPending()).Should().Be(2, "both new photos are cut, one after the other"); + + (await rig.Service.GetAsync(default)).Slides.Should().OnlyContain(s => !s.Image.Processing && s.Image.Variants.Count > 0); + } + + [Theory] + [InlineData(3000, 2000)] + [InlineData(2000, 3000)] + [InlineData(1600, 1600)] + [InlineData(3000, 1000)] + public async Task EverySet_HasAFullFramePreviewAtTheShapeOfThePicture_ThatIsNotPublishedToWebsites(int width, int height) + { + using var rig = new HeroTestRig(); + var image = await rig.Upload(HeroTestRig.Photo(width, height)); + var id = Guid.Parse(image.Id); + await rig.Service.SaveAsync(Save(id, null), HeroTestRig.Admin, default); + + var admin = (await rig.Service.GetAsync(default)).Slides[0].Image; + var stored = rig.Db.HeroImages.Single(); + + admin.PreviewSrc.Should().NotBeNull(); + var preview = stored.Variants.Single(v => v.Ratio == "full"); + (preview.Width / (double)preview.Height).Should().BeApproximately(width / (double)height, 0.01, "the preview is the whole picture, not a crop"); + preview.Width.Should().Be(Math.Min(1280, width)); + admin.Variants.Should().NotContain(v => v.Ratio == "full", "the admin lists only the variants of the website"); + (await rig.Public.GetActiveAsync(default))!.Slides[0].Image.Variants.Should().NotContain(v => v.Ratio == "full"); + (await rig.Store.ExistsAsync($"hero/{stored.SetHash}/{preview.FileName}", default)).Should().BeTrue(); + } + + [Fact] + public async Task ASetMadeBeforeThePreviewExisted_GetsOnlyThePreviewAdded_WithoutBeingProcessingOrChangingItsAddresses() + { + using var rig = new HeroTestRig(); + var image = await rig.Upload(HeroTestRig.Photo(2000, 3000)); + var id = Guid.Parse(image.Id); + await rig.Service.SaveAsync(Save(id, null), HeroTestRig.Admin, default); + var stored = rig.Db.HeroImages.Single(); + var setBefore = stored.SetHash; + var preview = stored.Variants.Single(v => v.Ratio == "full"); + stored.Variants = stored.Variants.Where(v => v.Ratio != "full").ToList(); // as an older set looked + await rig.Db.SaveChangesAsync(); + await rig.Store.DeleteAsync($"hero/{setBefore}/{preview.FileName}", default); + + var oldLook = (await rig.Service.GetAsync(default)).Slides[0].Image; + oldLook.Processing.Should().BeFalse("adding the preview is not work the administrator waits for"); + oldLook.PreviewSrc.Should().BeNull(); + + (await rig.RenderPending()).Should().Be(1); + + var after = rig.Db.HeroImages.Single(); + after.SetHash.Should().Be(setBefore, "nothing live changes"); + (await rig.Service.GetAsync(default)).Slides[0].Image.PreviewSrc.Should().NotBeNull(); + (await rig.Store.ExistsAsync($"hero/{setBefore}/{preview.FileName}", default)).Should().BeTrue(); + } + + [Fact] + public async Task APhotoThatIsAlreadyThere_ComesBackAsReused_WithItsVariants_AndNothingToWaitFor() + { + using var rig = new HeroTestRig(); + var photo = HeroTestRig.Photo(seed: 5); + var first = await rig.Upload(photo); + + var again = await rig.UploadWithoutRendering(photo); + + again.Id.Should().Be(first.Id); + again.Reused.Should().BeTrue(); + again.Processing.Should().BeFalse(); + again.Variants.Should().NotBeEmpty(); + first.Reused.Should().BeFalse(); + } + + [Fact] + public async Task TheStateOfOneImage_IsAskedForByItsId_WithTheRunningRenderersFlags() + { + using var rig = new HeroTestRig(); + var dto = await rig.UploadWithoutRendering(HeroTestRig.Photo(seed: 6)); + var id = Guid.Parse(dto.Id); + + (await rig.Images.GetImageAsync(id, default))!.Processing.Should().BeTrue(); + rig.Signal.SetProgress(id, 4, 19); + var busy = (await rig.Images.GetImageAsync(id, default))!; + (busy.RenderDone, busy.RenderTotal).Should().Be((4, 19)); + rig.Signal.ClearProgress(id); + + await rig.RenderPending(); + + var done = (await rig.Images.GetImageAsync(id, default))!; + done.Processing.Should().BeFalse(); + done.Variants.Should().NotBeEmpty(); + (await rig.Images.GetImageAsync(Guid.NewGuid(), default)).Should().BeNull(); + } } diff --git a/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs b/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs index 9aaec84..c3ee9d3 100644 --- a/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs +++ b/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs @@ -95,6 +95,16 @@ public class HeroImagesController(IHeroImageService service, IOptionsOne image as the admin sees it now; the page asks for the images it uploaded but has not saved yet. + [HttpGet("{id:guid}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task Get(Guid id, CancellationToken cancellationToken) + { + var image = await service.GetImageAsync(id, cancellationToken); + return image is null ? NotFound(new { error = "not_found", message = Texts().Get(HeroTexts.Image.NotFound) }) : Ok(image); + } + /// The formats and limits an upload has to meet on this host (what the validation uses). [HttpGet("limits")] [ProducesResponseType(StatusCodes.Status200OK)] diff --git a/src/SlpModularCms.Modules.Hero/Models/HeroModels.cs b/src/SlpModularCms.Modules.Hero/Models/HeroModels.cs index f74c5c5..3918dd2 100644 --- a/src/SlpModularCms.Modules.Hero/Models/HeroModels.cs +++ b/src/SlpModularCms.Modules.Hero/Models/HeroModels.cs @@ -27,7 +27,9 @@ public record HeroImageDto( bool Processing = false, bool Failed = false, int? RenderDone = null, - int? RenderTotal = null); + int? RenderTotal = null, + string? PreviewSrc = null, + bool Reused = false); public record HeroButtonDto(string Label, string Target); diff --git a/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs b/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs index cdd4203..e6ea79f 100644 --- a/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs +++ b/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs @@ -22,6 +22,9 @@ public interface IHeroRepository /// Images whose set is missing or does not match their focus, oldest first (tracked). Task> GetImagesNeedingRenderAsync(CancellationToken cancellationToken); + /// Images with a complete set made before the full-frame preview existed (tracked). + Task> GetImagesNeedingPreviewAsync(CancellationToken cancellationToken); + /// The image as stored right now, not tracked. Task GetImageFreshAsync(Guid id, CancellationToken cancellationToken); @@ -72,6 +75,9 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository public async Task> GetImagesNeedingRenderAsync(CancellationToken cancellationToken) => (await context.HeroImages.ToListAsync(cancellationToken)).Where(HeroMapping.NeedsRender).OrderBy(i => i.CreatedAt).ToList(); + public async Task> GetImagesNeedingPreviewAsync(CancellationToken cancellationToken) + => (await context.HeroImages.ToListAsync(cancellationToken)).Where(HeroMapping.NeedsPreview).OrderBy(i => i.CreatedAt).ToList(); + public Task GetImageFreshAsync(Guid id, CancellationToken cancellationToken) => context.HeroImages.AsNoTracking().FirstOrDefaultAsync(i => i.Id == id, cancellationToken); diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs b/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs index cda2e20..1482b36 100644 --- a/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs +++ b/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs @@ -43,6 +43,9 @@ public interface IHeroImageService /// The variant the renderer is busy with: (done, total), or null when the image is not being cut right now. (int Done, int Total)? RenderProgress(Guid imageId); + /// One image as the admin sees it now (including whether it is still being prepared). Null when there is no such image. + Task GetImageAsync(Guid imageId, CancellationToken cancellationToken); + /// True when the background renderer gave up on the image after a few failed tries (until a retry or a restart). bool IsRenderFailed(Guid imageId); @@ -90,7 +93,7 @@ public class HeroImageService( // The same photo again also gives up the failed state: the renderer tries it again when it is still pending. signal?.Reset(existing.Id); signal?.Notify(); - return HeroMapping.ToImageDto(existing); + return HeroMapping.ToImageDto(existing) with { Reused = true }; } await EnsureRoomAsync(admitted.Bytes.Length, cancellationToken); @@ -161,6 +164,19 @@ public class HeroImageService( public void NotifyPending() => signal?.Notify(); + public async Task GetImageAsync(Guid imageId, CancellationToken cancellationToken) + { + var image = await repository.GetImageFreshAsync(imageId, cancellationToken); + if (image is null) + { + return null; + } + + var failed = IsRenderFailed(imageId); + var progress = RenderProgress(imageId); + return HeroMapping.ToImageDto(image) with { Failed = failed, RenderDone = progress?.Done, RenderTotal = progress?.Total }; + } + public bool IsRenderFailed(Guid imageId) => signal?.IsGivenUp(imageId) ?? false; public (int Done, int Total)? RenderProgress(Guid imageId) => signal?.GetProgress(imageId); @@ -177,7 +193,9 @@ public class HeroImageService( var image = (await repository.GetImagesNeedingRenderAsync(cancellationToken)).FirstOrDefault(i => !skip.Contains(i.Id)); if (image is null) { - return null; + // Nothing to cut: add the full-frame preview to complete sets that were made before it existed. + var old = (await repository.GetImagesNeedingPreviewAsync(cancellationToken)).FirstOrDefault(i => !skip.Contains(i.Id)); + return old is null ? null : await AddPreviewAsync(old, cancellationToken); } try @@ -195,6 +213,40 @@ public class HeroImageService( } } + /// Makes only the preview file of a complete set (one decode, one resize) and adds it to the set where it already is. + private async Task AddPreviewAsync(HeroImage image, CancellationToken cancellationToken) + { + try + { + using (await gate.EnterAsync(cancellationToken)) + { + var file = await store.OpenReadAsync(image.OriginalKey, cancellationToken) + ?? throw new ImageRejectedException(ImageRejection.Unavailable, "The stored original is missing."); + using var memory = new MemoryStream(); + await using (file.Content) + { + await file.Content.CopyToAsync(memory, cancellationToken); + } + + var storedFormat = ImageFormatExtensions.FromExtension(Path.GetExtension(image.OriginalKey).TrimStart('.')); + var spec = VariantPlanner.Preview(image.Width, image.Height, processor.SupportedOutput); + var rendered = (await processor.RenderSetAsync(memory.ToArray(), storedFormat, [spec], null, cancellationToken))[0]; + var name = MediaPaths.FileName(spec.Ratio.Name, spec.Width, spec.Format); + await store.PutAsync($"{HeroMapping.Area}/{image.SetHash}/{name}", rendered.Bytes, cancellationToken); + image.Variants = [.. image.Variants, new HeroVariant(spec.Ratio.Name, rendered.Width, rendered.Height, spec.Format.MimeType(), name, rendered.Bytes.LongLength)]; + } + + await repository.SaveChangesAsync(cancellationToken); + logger.LogInformation("Hero image {ImageId}: the full-frame preview was added to its set.", image.Id); + return image.Id; + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + logger.LogError(exception, "Hero image {ImageId}: adding the preview failed.", image.Id); + throw new HeroImageRenderException(image.Id, exception); + } + } + private async Task RenderAsync(HeroImage image, CancellationToken cancellationToken) { @@ -283,7 +335,9 @@ public class HeroImageService( var ratios = new[] { Ratio.Wide, Ratio.Tall } .Select(r => new RatioPlan(r, image.FocusFor(r.Name), VariantPlanner.DefaultWidths(r))) .ToList(); - var specs = VariantPlanner.Plan(image.Width, image.Height, ratios, processor.SupportedOutput); + var specs = VariantPlanner.Plan(image.Width, image.Height, ratios, processor.SupportedOutput).ToList(); + // The whole picture, for the focus dialog of the admin (never published to a website). + specs.Add(VariantPlanner.Preview(image.Width, image.Height, processor.SupportedOutput)); progress?.Invoke(0, specs.Count); var rendered = await processor.RenderSetAsync(original, storedFormat, specs, progress, cancellationToken); diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroMapping.cs b/src/SlpModularCms.Modules.Hero/Services/HeroMapping.cs index 301978a..4241223 100644 --- a/src/SlpModularCms.Modules.Hero/Services/HeroMapping.cs +++ b/src/SlpModularCms.Modules.Hero/Services/HeroMapping.cs @@ -47,6 +47,19 @@ public static class HeroMapping _ => format.ToString().ToUpperInvariant(), }; + /// The variants websites and the admin lists use: everything except the full-frame preview. + public static IEnumerable Published(HeroImage image) => image.Variants.Where(v => v.Ratio != VariantPlanner.PreviewRatioName); + + /// The address of the full-frame preview for the focus dialog, or null while the set has none yet. + public static string? PreviewSrc(HeroImage image) + => image.Variants.FirstOrDefault(v => v.Ratio == VariantPlanner.PreviewRatioName) is { } preview + ? MediaPaths.Url(Area, image.SetHash, preview.FileName) + : null; + + /// A complete, current set that lacks the preview (made before it existed): only that file is added, quietly. + public static bool NeedsPreview(HeroImage image) + => !NeedsRender(image) && image.Variants.All(v => v.Ratio != VariantPlanner.PreviewRatioName); + /// The set hash the image should have at its current focus. public static string TargetSetHash(HeroImage image) => MediaPaths.SetHash(image.OriginalSha256, [("wide", image.FocusFor("wide")), ("tall", image.FocusFor("tall"))]); @@ -60,10 +73,10 @@ public static class HeroMapping /// The address the plain img uses: the largest WebP of the wide ratio, else the largest WebP, else the first variant. public static string SrcFor(HeroImage image) { - var webp = image.Variants.Where(v => v.Type == ImageFormat.WebP.MimeType()).ToList(); + var webp = Published(image).Where(v => v.Type == ImageFormat.WebP.MimeType()).ToList(); var pick = webp.Where(v => v.Ratio == "wide").OrderByDescending(v => v.Width).FirstOrDefault() ?? webp.OrderByDescending(v => v.Width).FirstOrDefault() - ?? image.Variants.FirstOrDefault(); + ?? Published(image).FirstOrDefault(); return pick is null ? string.Empty : MediaPaths.Url(Area, image.SetHash, pick.FileName); } @@ -76,8 +89,9 @@ public static class HeroMapping image.WideFocusX is null ? null : FocusDto.From(image.FocusFor("wide")), image.TallFocusX is null ? null : FocusDto.From(image.FocusFor("tall")), SrcFor(image), - image.Variants.Select(v => ToDto(image, v)).ToList(), - NeedsRender(image)); + Published(image).Select(v => ToDto(image, v)).ToList(), + NeedsRender(image), + PreviewSrc: PreviewSrc(image)); public static bool IsLive(HeroContent hero, DateTimeOffset now) => hero.IsActive @@ -137,7 +151,7 @@ public static class HeroMapping image.Height, FocusDto.From(image.General), SrcFor(image), - image.Variants.Select(v => ToDto(image, v)).ToList(), + Published(image).Select(v => ToDto(image, v)).ToList(), byRatio); }