Fase 2 stap B (frontend): uitsnede per slide in het scherm, herstelpunt in het plan

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 21:51:21 +01:00
co-authored by Claude Sonnet 5.5
parent e30d885d64
commit e44ca80d1d
11 changed files with 195 additions and 54 deletions
@@ -75,3 +75,4 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu
| 44 | **Tiles or list in the library** (Bryan, 2026-11-17). | The library and the trash show the photos as tiles (grid of thumbnails, selectable, same usage and links) by default, with a switch Tiles / List next to the filters. The choice is remembered in the browser (`localStorage`, guarded; it falls back to tiles). The clean-up dialog keeps its list. The picker already is a grid. | Remember the choice on the server per user: needs a user-settings store. | `PhotoSelectionList` (`layout`), `lib/layoutPreference.ts`, `MediaLibraryPage` | | 44 | **Tiles or list in the library** (Bryan, 2026-11-17). | The library and the trash show the photos as tiles (grid of thumbnails, selectable, same usage and links) by default, with a switch Tiles / List next to the filters. The choice is remembered in the browser (`localStorage`, guarded; it falls back to tiles). The clean-up dialog keeps its list. The picker already is a grid. | Remember the choice on the server per user: needs a user-settings store. | `PhotoSelectionList` (`layout`), `lib/layoutPreference.ts`, `MediaLibraryPage` |
| 45 | **Media screen details** (Bryan, 2026-11-17): bulk bar keeps its height; the whole tile selects; smaller tiles; 0 days in the clean-up; no time-basis choice. | The bar is an invisible placeholder of the same height (h-9) while nothing is selected. A click on a tile selects it (shift for a range); links, buttons and the box itself do their own thing. One more tile per row at every width. The clean-up slider goes from 0: 0 days means every photo that is not in use right now qualifies at the next clean-up (preview and confirmation unchanged, with a note at 0). The period always counts from the last use (assumption 29); there was no separate checkbox for the time basis in the clean-up (the only checkbox is "Alleen ongebruikte foto's", a filter, which stays because it protects photos in use), so nothing was removed. | If Bryan meant "Alleen ongebruikte foto's": removing it would put photos in use in the clean-up (counted from their upload date). | `BulkActionBar`, `PhotoSelectionList`, `CleanupDialog`, `CleanupSelection.MinDays` | | 45 | **Media screen details** (Bryan, 2026-11-17): bulk bar keeps its height; the whole tile selects; smaller tiles; 0 days in the clean-up; no time-basis choice. | The bar is an invisible placeholder of the same height (h-9) while nothing is selected. A click on a tile selects it (shift for a range); links, buttons and the box itself do their own thing. One more tile per row at every width. The clean-up slider goes from 0: 0 days means every photo that is not in use right now qualifies at the next clean-up (preview and confirmation unchanged, with a note at 0). The period always counts from the last use (assumption 29); there was no separate checkbox for the time basis in the clean-up (the only checkbox is "Alleen ongebruikte foto's", a filter, which stays because it protects photos in use), so nothing was removed. | If Bryan meant "Alleen ongebruikte foto's": removing it would put photos in use in the clean-up (counted from their upload date). | `BulkActionBar`, `PhotoSelectionList`, `CleanupDialog`, `CleanupSelection.MinDays` |
| 46 | **Phase 2 is built in three switchable steps; the Hero tables stay the truth until phase 3** (2026-11-17, design on `feature/media-library-phase2`). | A write-through to the library tables (`Media:Library:DualWrite`), a nullable crop and set per slide (additive; null = today's behaviour and addresses), and a read switch with a compare mode (`Media:Library:ReadFromLibrary`). All switches off by default, test only, rollback by switching off. Details and back-up/rollback plan: `inception/application-design/phase2-design.md`. | Replace the Hero tables in one go: cannot be rolled back by a switch. | `phase2-design.md` | | 46 | **Phase 2 is built in three switchable steps; the Hero tables stay the truth until phase 3** (2026-11-17, design on `feature/media-library-phase2`). | A write-through to the library tables (`Media:Library:DualWrite`), a nullable crop and set per slide (additive; null = today's behaviour and addresses), and a read switch with a compare mode (`Media:Library:ReadFromLibrary`). All switches off by default, test only, rollback by switching off. Details and back-up/rollback plan: `inception/application-design/phase2-design.md`. | Replace the Hero tables in one go: cannot be rolled back by a switch. | `phase2-design.md` |
| 47 | **Crop per slide (step B), built 2026-11-17.** | A slide can have its own crop (nullable columns on `HeroSlides`, migration `AddSlideCrop`, additive); null = the slide uses its photo's crop and set, so no existing address changes. The crop is edited per slide (`PUT/DELETE hero/slides/{id}/focus`, applied at once); a crop equal to the photo's shares the photo's set; equal crops share one set. A slide that is not saved yet cannot be cropped (the button says so): its crop would have no slide to belong to. The "crop is shared" hint of assumption 36 is gone. The photo's own crop stays the default and is no longer edited from the screen (the endpoint remains). | Let an unsaved slide carry its crop in the save request: more code on both sides. | `HeroSlide`, `HeroMapping.Effective`, `HeroImageService.RenderSlideAsync`, `HeroPage` |
@@ -1,6 +1,6 @@
# Phase 2: the Hero works through the library, and a crop per use # Phase 2: the Hero works through the library, and a crop per use
Status: design and rollback plan, **not built yet** (2026-11-17). Branch `feature/media-library-phase2` (no PR until #22 is merged). Test only; every switch is OFF by default; SLS-Main is told before every test deploy; phase 3 (dropping the old tables) only after phase 2 is verified on test and never on production without a separate go from Bryan. Status (2026-11-17): step B (crop per slide) is built on this branch (backend, frontend, tests); steps A and C and phase 3 are not built. Branch `feature/media-library-phase2` (no PR until #22 is merged). Test only; every switch is OFF by default; SLS-Main is told before every test deploy; phase 3 (dropping the old tables) only after phase 2 is verified on test and never on production without a separate go from Bryan.
## What Bryan wants ## What Bryan wants
@@ -68,7 +68,7 @@ Behaviour:
Before the first deploy of each step (A, B, C) on a test host: Before the first deploy of each step (A, B, C) on a test host:
1. **Database dump** if it can be taken (`mysqldump --single-transaction`, dated file outside the deploy directory). SLS-Main cannot make one on the Raspberry Pi today (see migration plan): then the assumption stays that the test data can be rebuilt and that every change is additive (new nullable columns, new tables); Bryan has been told. 1. **Restore point of the test sites (made by Bryan, 2026-11-17 21:37, confirmed by Pi-Main):** `/mnt/storage1/backups/test-herstelpunt/2026-11-17-213757/` (readable by root only) with `db-SlpSoftwareTest.sql.gz`, `db-AndreaSlopFotografieTest.sql.gz`, `media.tar.gz` (both media directories) and `SHA256SUMS`. Made with `sudo bash /home/claude/server-ops/drafts/2026-11-17-test-herstelpunt/test-herstelpunt.sh`. Restoring is step 22b in `drafts/2026-11-17-test-herstelpunt/README.md` on the Pi, done by Bryan (not tested yet). Take a new one before the next step if a lot changed.
2. **Row counts** noted: `HeroImages`, `HeroSlides`, `HeroRetiredFiles`, `MediaAssets`, `MediaUses`. 2. **Row counts** noted: `HeroImages`, `HeroSlides`, `HeroRetiredFiles`, `MediaAssets`, `MediaUses`.
3. **Sample of public addresses** (ten `/media/hero/<setHash>/...` URLs and the hero markers) requested before and after; same bytes. 3. **Sample of public addresses** (ten `/media/hero/<setHash>/...` URLs and the hero markers) requested before and after; same bytes.
@@ -91,5 +91,5 @@ Switches are set through the existing deploy workflow input path (the same way a
## Assumptions made here (also in assumptions-and-open-questions.md) ## Assumptions made here (also in assumptions-and-open-questions.md)
- The Hero tables stay authoritative until phase 3; "reads and writes through the library" is reached in steps A and C behind switches, not by replacing the tables in one go (a one-go replacement cannot be rolled back by a switch). - Test data is no longer assumed to be rebuildable: there is a recorded restore point (above). The Hero tables stay authoritative until phase 3; "reads and writes through the library" is reached in steps A and C behind switches, not by replacing the tables in one go (a one-go replacement cannot be rolled back by a switch).
- The crop per slide lives in the slide (nullable) in the Hero until phase 3 and is mirrored to `MediaUses.Crops`; moving the authority to `MediaUses` is part of phase 3. - The crop per slide lives in the slide (nullable) in the Hero until phase 3 and is mirrored to `MediaUses.Crops`; moving the authority to `MediaUses` is part of phase 3.
@@ -12,6 +12,9 @@ interface CropThumbnailProps {
edit?: HeroFocusRequest; edit?: HeroFocusRequest;
onClick: () => void; onClick: () => void;
testId: string; testId: string;
/** The crop cannot be changed now (for example the slide is not saved yet); `hint` says why. */
disabled?: boolean;
hint?: string;
} }
/** /**
@@ -20,7 +23,7 @@ interface CropThumbnailProps {
* icon is always there, so it can be found on a touch screen as well. After "Apply" in the dialog the thumbnail shows * icon is always there, so it can be found on a touch screen as well. After "Apply" in the dialog the thumbnail shows
* the new crop right away (the same calculation as the host) with a clear "not saved yet" note. * the new crop right away (the same calculation as the host) with a clear "not saved yet" note.
*/ */
export function CropThumbnail({ image, savedSrc, edit, onClick, testId }: CropThumbnailProps) { export function CropThumbnail({ image, savedSrc, edit, onClick, testId, disabled = false, hint }: CropThumbnailProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const local = edit && image.previewSrc ? localCrop(image, edit) : null; const local = edit && image.previewSrc ? localCrop(image, edit) : null;
@@ -28,8 +31,10 @@ export function CropThumbnail({ image, savedSrc, edit, onClick, testId }: CropTh
<button <button
type="button" type="button"
onClick={onClick} onClick={onClick}
disabled={disabled}
title={disabled ? hint : undefined}
aria-label={t('hero.slides.cropEdit')} aria-label={t('hero.slides.cropEdit')}
className={`group relative block aspect-[3/2] w-28 shrink-0 cursor-pointer overflow-hidden rounded bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${edit ? 'ring-2 ring-amber-500' : ''}`} className={`group relative block aspect-[3/2] w-28 shrink-0 ${disabled ? 'cursor-not-allowed opacity-70' : 'cursor-pointer'} overflow-hidden rounded bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${edit ? 'ring-2 ring-amber-500' : ''}`}
data-testid={testId} data-testid={testId}
> >
{local && image.previewSrc ? ( {local && image.previewSrc ? (
@@ -18,9 +18,11 @@ interface FocusDialogProps {
/** Keeps the change locally: it is sent and made live when the hero is saved, and dropped when the page is left. */ /** 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; onApply: (imageId: string, request: HeroFocusRequest) => void;
onClose: () => void; onClose: () => void;
/** The slide has a crop of its own: offers "use the crop of the photo again". */
onReset?: () => void;
} }
export function FocusDialog({ image, onApply, onClose }: FocusDialogProps) { export function FocusDialog({ image, onApply, onClose, onReset }: FocusDialogProps) {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
<Dialog open={image !== null} onOpenChange={(next) => { if (!next) onClose(); }}> <Dialog open={image !== null} onOpenChange={(next) => { if (!next) onClose(); }}>
@@ -29,7 +31,7 @@ export function FocusDialog({ image, onApply, onClose }: FocusDialogProps) {
<DialogTitle>{t('hero.focus.title')}</DialogTitle> <DialogTitle>{t('hero.focus.title')}</DialogTitle>
</DialogHeader> </DialogHeader>
{/* Mounted only while open, so every opening starts from the stored values. */} {/* Mounted only while open, so every opening starts from the stored values. */}
{image && <FocusEditor image={image} onApply={onApply} onClose={onClose} />} {image && <FocusEditor image={image} onApply={onApply} onClose={onClose} onReset={onReset} />}
</DialogContent> </DialogContent>
</Dialog> </Dialog>
); );
@@ -37,7 +39,7 @@ export function FocusDialog({ image, onApply, onClose }: FocusDialogProps) {
const percent = (fraction: number) => Math.round(fraction * 1000) / 10; const percent = (fraction: number) => Math.round(fraction * 1000) / 10;
function FocusEditor({ image, onApply, onClose }: { image: HeroImageDto; onApply: (imageId: string, request: HeroFocusRequest) => void; onClose: () => void }) { function FocusEditor({ image, onApply, onClose, onReset }: { image: HeroImageDto; onApply: (imageId: string, request: HeroFocusRequest) => void; onClose: () => void; onReset?: () => void }) {
const { t } = useTranslation(); const { t } = useTranslation();
const area = useRef<HTMLDivElement>(null); const area = useRef<HTMLDivElement>(null);
// The whole picture: image.src is already a crop of the wide shape and would be shown stretched and out of place. // The whole picture: image.src is already a crop of the wide shape and would be shown stretched and out of place.
@@ -235,7 +237,21 @@ function FocusEditor({ image, onApply, onClose }: { image: HeroImageDto; onApply
</div> </div>
</div> </div>
<div className="flex justify-end gap-2"> <div className="flex flex-wrap justify-end gap-2">
{onReset && (
<Button
type="button"
variant="ghost"
className="mr-auto"
onClick={() => {
onReset();
onClose();
}}
data-testid="focus-reset"
>
{t('hero.focus.reset')}
</Button>
)}
<Button type="button" variant="outline" onClick={onClose} data-testid="focus-cancel"> <Button type="button" variant="outline" onClick={onClose} data-testid="focus-cancel">
{t('common.cancel')} {t('common.cancel')}
</Button> </Button>
+28 -2
View File
@@ -58,6 +58,7 @@ export const resetMockHero = (): void => {
uploadFailure = null; uploadFailure = null;
retried = []; retried = [];
focusRequests = []; focusRequests = [];
resetSlideRequests = [];
recutting = new Set(); recutting = new Set();
}; };
@@ -80,9 +81,11 @@ export const getRetriedImages = (): string[] => retried;
export const getSavedHeroRequests = (): HeroSaveRequest[] => saved; export const getSavedHeroRequests = (): HeroSaveRequest[] => saved;
let focusRequests: { imageId: string; body: HeroFocusRequest }[] = []; let focusRequests: { imageId: string; slideId?: string; body: HeroFocusRequest }[] = [];
let resetSlideRequests: string[] = [];
export const getResetSlideRequests = (): string[] => resetSlideRequests;
/** The crops sent at once with PUT hero/images/{id}/focus (no save of the hero involved). */ /** The crops sent at once with PUT hero/images/{id}/focus (no save of the hero involved). */
export const getFocusRequests = (): { imageId: string; body: HeroFocusRequest }[] => focusRequests; export const getFocusRequests = (): { imageId: string; slideId?: string; body: HeroFocusRequest }[] => focusRequests;
export const failNextUpload = (failure: { status: number; error: string; message: string } | null): void => { export const failNextUpload = (failure: { status: number; error: string; message: string } | null): void => {
uploadFailure = failure; uploadFailure = failure;
@@ -123,6 +126,29 @@ export const heroHandlers = [
return HttpResponse.json(hero); return HttpResponse.json(hero);
}), }),
// A crop for one slide (crop per use): the slide gets its own crop and shows the photo as processing.
http.put(`${API_BASE}/api/v1/hero/slides/:id/focus`, async ({ params, request }) => {
const slideId = String(params.id);
const body = (await request.json()) as HeroFocusRequest;
const slide = hero.slides.find((s) => s.id === slideId);
if (!slide) return new HttpResponse(null, { status: 404 });
focusRequests.push({ imageId: slide.imageId, slideId, body });
const updated = { ...slide, ownCrop: true, image: { ...slide.image, focus: body.focus, wideFocus: body.wide ?? null, tallFocus: body.tall ?? null, processing: true } };
recutting.add(slide.imageId);
hero = { ...hero, slides: hero.slides.map((s) => (s.id === slideId ? updated : s)) };
return HttpResponse.json(updated);
}),
http.delete(`${API_BASE}/api/v1/hero/slides/:id/focus`, ({ params }) => {
const slideId = String(params.id);
const slide = hero.slides.find((s) => s.id === slideId);
if (!slide) return new HttpResponse(null, { status: 404 });
resetSlideRequests.push(slideId);
const updated = { ...slide, ownCrop: false, image: { ...slide.image, processing: false } };
hero = { ...hero, slides: hero.slides.map((s) => (s.id === slideId ? updated : s)) };
return HttpResponse.json(updated);
}),
http.put(`${API_BASE}/api/v1/hero/images/:id/focus`, async ({ params, request }) => { http.put(`${API_BASE}/api/v1/hero/images/:id/focus`, async ({ params, request }) => {
const id = String(params.id); const id = String(params.id);
const body = (await request.json()) as HeroFocusRequest; const body = (await request.json()) as HeroFocusRequest;
@@ -5,7 +5,7 @@ import { http, HttpResponse } from 'msw';
import { server } from '@/mocks/server'; import { server } from '@/mocks/server';
import { API_BASE } from '@/features/auth/mocks/fixtures'; import { API_BASE } from '@/features/auth/mocks/fixtures';
import { renderApp, mockAuthenticated } from '@/test/utils'; import { renderApp, mockAuthenticated } from '@/test/utils';
import { emptyHero, failNextUpload, finishMockRecut, getRetriedImages, getFocusRequests, import { emptyHero, failNextUpload, finishMockRecut, getRetriedImages, getFocusRequests, getResetSlideRequests,
getSavedHeroRequests, resetMockHero, setMockHero, slide } from '@/features/hero/mocks/handlers'; getSavedHeroRequests, resetMockHero, setMockHero, slide } from '@/features/hero/mocks/handlers';
import { _resetSetupStatusCache } from '@/router'; import { _resetSetupStatusCache } from '@/router';
@@ -308,7 +308,7 @@ describe('Focus dialog', () => {
await waitFor(() => expect(screen.queryByTestId('focus-dialog')).not.toBeInTheDocument()); await waitFor(() => expect(screen.queryByTestId('focus-dialog')).not.toBeInTheDocument());
await waitFor(() => expect(getFocusRequests()).toHaveLength(1)); await waitFor(() => expect(getFocusRequests()).toHaveLength(1));
expect(getFocusRequests()[0]).toEqual({ expect(getFocusRequests()[0]).toMatchObject({
imageId: '10000000-0000-0000-0000-000000000001', imageId: '10000000-0000-0000-0000-000000000001',
body: { focus: { x: 0.3, y: 0.5, zoom: 1 }, wide: null, tall: { x: 0.8, y: 0.5, zoom: 2 } }, body: { focus: { x: 0.3, y: 0.5, zoom: 1 }, wide: null, tall: { x: 0.8, y: 0.5, zoom: 2 } },
}); });
@@ -908,7 +908,7 @@ describe('Each photo shows by itself when its processing is finished', () => {
expect(screen.getByTestId('hero-slide-0-done')).toHaveAttribute('role', 'status'); expect(screen.getByTestId('hero-slide-0-done')).toHaveAttribute('role', 'status');
expect(screen.getByTestId('hero-slide-0-done')).toHaveAttribute('aria-live', 'polite'); expect(screen.getByTestId('hero-slide-0-done')).toHaveAttribute('aria-live', 'polite');
expect(screen.queryByTestId('hero-slide-0-processing')).not.toBeInTheDocument(); expect(screen.queryByTestId('hero-slide-0-processing')).not.toBeInTheDocument();
expect(screen.getByTestId('hero-slide-0-focus')).toBeEnabled(); expect(screen.getByTestId('hero-slide-0-focus')).toBeInTheDocument(); // the crop button is there (disabled until the slide is saved)
// The note names the slide for a screen reader, and goes away by itself after a few seconds. // 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)/); expect(note.textContent).toMatch(/Slide 1: (verwerking afgerond|processing finished)/);
await waitFor(() => expect(screen.queryByTestId('hero-slide-0-done-text')).not.toBeInTheDocument(), { timeout: 8000 }); await waitFor(() => expect(screen.queryByTestId('hero-slide-0-done-text')).not.toBeInTheDocument(), { timeout: 8000 });
@@ -923,7 +923,7 @@ describe('Each photo shows by itself when its processing is finished', () => {
expect(await screen.findByTestId('hero-slide-0-done-text', {}, T)).toHaveTextContent(/Verwerking afgerond|Processing finished/); 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.queryByTestId('hero-slide-0-processing')).not.toBeInTheDocument();
expect(screen.getByTestId('hero-slide-0-focus')).toBeEnabled(); expect(screen.getByTestId('hero-slide-0-focus')).toBeInTheDocument(); // the crop button is there (disabled until the slide is saved)
expect(screen.queryByText(/stond al|already/i)).not.toBeInTheDocument(); expect(screen.queryByText(/stond al|already/i)).not.toBeInTheDocument();
}); });
@@ -981,7 +981,7 @@ describe('Each photo shows by itself when its processing is finished', () => {
finished.add(ids[0]); finished.add(ids[0]);
await screen.findByTestId('hero-slide-0-done-text', {}, { timeout: 12000 }); await screen.findByTestId('hero-slide-0-done-text', {}, { timeout: 12000 });
expect(screen.getByTestId('hero-slide-0-focus')).toBeEnabled(); expect(screen.getByTestId('hero-slide-0-focus')).toBeInTheDocument(); // the crop button is there (disabled until the slide is saved)
expect(screen.getByTestId('hero-slide-1-processing')).toBeInTheDocument(); expect(screen.getByTestId('hero-slide-1-processing')).toBeInTheDocument();
expect(screen.queryByTestId('hero-slide-1-focus')).not.toBeInTheDocument(); expect(screen.queryByTestId('hero-slide-1-focus')).not.toBeInTheDocument();
expect(screen.getByTestId('hero-processing-count')).toHaveTextContent(/1 van 2|1 of 2/); expect(screen.getByTestId('hero-processing-count')).toHaveTextContent(/1 van 2|1 of 2/);
@@ -1296,15 +1296,57 @@ describe('Add a slide with a photo from the library or an upload', () => {
expect(getSavedHeroRequests()[0].slides.map((x) => x.imageId)).toEqual(['10000000-0000-0000-0000-000000000001', '10000000-0000-0000-0000-000000000002', '10000000-0000-0000-0000-000000000002']); expect(getSavedHeroRequests()[0].slides.map((x) => x.imageId)).toEqual(['10000000-0000-0000-0000-000000000001', '10000000-0000-0000-0000-000000000002', '10000000-0000-0000-0000-000000000002']);
}); });
it('tells that the crop is shared when the same photo is in more than one slide', async () => { it('gives every slide its own crop: the same photo on two slides is cropped per slide', async () => {
const one = slide(1); const one = slide(1);
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [one, { ...slide(2), imageId: one.imageId, image: one.image }, slide(3)] }); setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [one, { ...slide(2), imageId: one.imageId, image: one.image }] });
await openPage(); await openPage();
expect(screen.getByTestId('hero-slide-0-shared-crop')).toBeInTheDocument(); await userEvent.click(screen.getByTestId('hero-slide-1-focus'));
expect(screen.getByTestId('hero-slide-1-shared-crop')).toBeInTheDocument(); await screen.findByTestId('focus-dialog');
expect(screen.queryByTestId('hero-slide-2-shared-crop')).not.toBeInTheDocument(); fireEvent.change(screen.getByTestId('focus-x'), { target: { value: '20' } });
await userEvent.click(screen.getByTestId('focus-save'));
await waitFor(() => expect(getFocusRequests()).toHaveLength(1));
expect(getFocusRequests()[0].slideId).toBe(slide(2).id);
expect(await screen.findByTestId('hero-slide-1-recut', {}, T)).toBeInTheDocument();
expect(screen.getByTestId('hero-slide-0-focus')).toBeInTheDocument();
expect(screen.queryByTestId('hero-slide-0-recut')).not.toBeInTheDocument();
expect(screen.queryByTestId('hero-slide-0-shared-crop')).not.toBeInTheDocument();
});
it('offers to go back to the crop of the photo for a slide with a crop of its own', async () => {
const one = slide(1);
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [{ ...one, ownCrop: true }, slide(2)] });
await openPage();
await userEvent.click(screen.getByTestId('hero-slide-0-focus'));
await screen.findByTestId('focus-dialog');
await userEvent.click(screen.getByTestId('focus-reset'));
await waitFor(() => expect(getResetSlideRequests()).toEqual([one.id]));
});
it('does not offer the reset for a slide that uses the crop of its photo', async () => {
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] });
await openPage();
await userEvent.click(screen.getByTestId('hero-slide-0-focus'));
await screen.findByTestId('focus-dialog');
expect(screen.queryByTestId('focus-reset')).not.toBeInTheDocument();
});
it('asks to save a new slide first before its crop can be changed', async () => {
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] });
server.use(http.get('*/media-library/photos', () => HttpResponse.json({ photos: [], modules: ['hero'] })));
await openPage();
await userEvent.click(screen.getByTestId('hero-upload-button'));
const dialog = await screen.findByTestId('library-picker', {}, T);
await userEvent.upload(within(dialog).getByTestId('picker-file'), new File([new Uint8Array(100)], 'nieuw.jpg', { type: 'image/jpeg' }));
await waitFor(() => expect(screen.queryByTestId('library-picker')).not.toBeInTheDocument());
expect(await screen.findByTestId('hero-slide-1-save-first')).toBeInTheDocument();
expect(screen.queryByTestId('hero-slide-0-save-first')).not.toBeInTheDocument();
}); });
it('uploads a new photo on the spot with the hero upload and puts it in the slide', async () => { it('uploads a new photo on the spot with the hero upload and puts it in the slide', async () => {
+52 -23
View File
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useRef, useState } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useQueries, useQueryClient } from '@tanstack/react-query'; import { useQueries, useQueryClient } from '@tanstack/react-query';
import { useFieldArray, useForm, useWatch } from 'react-hook-form'; import { useFieldArray, useForm, useWatch } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod'; import { zodResolver } from '@hookform/resolvers/zod';
@@ -27,7 +27,7 @@ import { UnsavedChangesGuard } from '../components/UnsavedChangesGuard';
import { UploadProgress, type UploadItem } from '../components/UploadProgress'; import { UploadProgress, type UploadItem } from '../components/UploadProgress';
import { mediaUrl } from '../lib/media'; import { mediaUrl } from '../lib/media';
import { heroFormSchema, type HeroFormData } from '../schemas/hero'; import { heroFormSchema, type HeroFormData } from '../schemas/hero';
import { heroImageQuery, useHero, useHeroUploadLimits, useSaveHero, useSetHeroImageFocus, useUploadHeroImage } from '../services/hooks'; import { heroImageQuery, useHero, useHeroUploadLimits, useResetSlideFocus, useSaveHero, useSetSlideFocus, useUploadHeroImage } from '../services/hooks';
import type { HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest } from '../services/types'; import type { HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest } from '../services/types';
const textareaClass = const textareaClass =
@@ -147,9 +147,11 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
const nextUploadKey = useRef(0); const nextUploadKey = useRef(0);
const limits = useHeroUploadLimits().data; const limits = useHeroUploadLimits().data;
const [localImages, setLocalImages] = useState<Record<string, HeroImageDto>>({}); const [localImages, setLocalImages] = useState<Record<string, HeroImageDto>>({});
const [focusImageId, setFocusImageId] = useState<string | null>(null); // The slide whose crop is being edited (a crop belongs to the slide, not to the photo).
const [focusSlideIndex, setFocusSlideIndex] = useState<number | null>(null);
// A new crop is applied at once (no save needed): the server cuts the new variants in the background. // A new crop is applied at once (no save needed): the server cuts the new variants in the background.
const setImageFocus = useSetHeroImageFocus(); const setSlideFocus = useSetSlideFocus();
const resetSlideFocus = useResetSlideFocus();
// The photos of the current upload batch, for the counter "x of y processed": only the photos uploaded together, not // The photos of the current upload batch, for the counter "x of y processed": only the photos uploaded together, not
// every photo of the hero. A new batch starts when the previous one is finished. // every photo of the hero. A new batch starts when the previous one is finished.
const [batch, setBatch] = useState<string[]>([]); const [batch, setBatch] = useState<string[]>([]);
@@ -168,7 +170,8 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
reset, reset,
} = useForm<HeroFormData>({ resolver: zodResolver(heroFormSchema), mode: 'onTouched', shouldFocusError: false, defaultValues: toForm(hero) }); } = useForm<HeroFormData>({ resolver: zodResolver(heroFormSchema), mode: 'onTouched', shouldFocusError: false, defaultValues: toForm(hero) });
const slides = useFieldArray({ control, name: 'slides' }); const slides = useFieldArray({ control, name: 'slides' });
const watchedSlides = useWatch({ control, name: 'slides' }) ?? []; const watchedSlidesRaw = useWatch({ control, name: 'slides' });
const watchedSlides = useMemo(() => watchedSlidesRaw ?? [], [watchedSlidesRaw]);
// The two tabs share one form, one Save button and one "unsaved changes" state. The chosen tab is remembered for this // The two tabs share one form, one Save button and one "unsaved changes" state. The chosen tab is remembered for this
// browser session. // browser session.
@@ -219,10 +222,24 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
const images = useMemo(() => { const images = useMemo(() => {
const map: Record<string, HeroImageDto> = { ...localImages }; const map: Record<string, HeroImageDto> = { ...localImages };
for (const image of polled) if (image) map[image.id] = image; for (const image of polled) if (image) map[image.id] = image;
for (const s of hero.slides) map[s.imageId] = s.image; // A slide with a crop of its own shows another version of the photo: it never replaces the photo's own entry.
for (const s of hero.slides) if (!s.ownCrop || !(s.imageId in map)) map[s.imageId] = s.image;
return map; return map;
}, [hero.slides, localImages, polled]); }, [hero.slides, localImages, polled]);
// The photo as a slide shows it: for a saved slide the server's version (its own crop and set), else the photo itself.
const savedSlideOf = useCallback(
(index: number) => {
const id = watchedSlides[index]?.id;
return id ? hero.slides.find((s) => s.id === id && s.imageId === watchedSlides[index]?.imageId) : undefined;
},
[watchedSlides, hero.slides],
);
const imageOfSlide = useCallback(
(index: number): HeroImageDto | undefined => savedSlideOf(index)?.image ?? images[watchedSlides[index]?.imageId ?? slides.fields[index]?.imageId ?? ''],
[savedSlideOf, images, watchedSlides, slides.fields],
);
// Per photo: when its processing is done it shows "Processing finished" for a few seconds, and can be worked on at once. // 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. // A photo that was ready at once (the same photo was already in the CMS) shows the same note, without a placeholder.
const [justDone, setJustDone] = useState<Record<string, true>>({}); const [justDone, setJustDone] = useState<Record<string, true>>({});
@@ -238,7 +255,7 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
}; };
useEffect(() => { useEffect(() => {
for (const field of slides.fields) { for (const field of slides.fields) {
const image = images[field.imageId]; const image = imageOfSlide(slides.fields.indexOf(field));
if (!image) continue; if (!image) continue;
if (image.processing) { if (image.processing) {
wasProcessing.current[image.id] = true; wasProcessing.current[image.id] = true;
@@ -247,7 +264,7 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
markDone(image.id); markDone(image.id);
} }
} }
}, [images, slides.fields]); }, [images, slides.fields, imageOfSlide]);
// The form is compared with the last saved state (react-hook-form keeps it), so a change that is undone no longer counts. // The form is compared with the last saved state (react-hook-form keeps it), so a change that is undone no longer counts.
// Photos still being prepared on the server and the background refresh are not changes of the administrator. // Photos still being prepared on the server and the background refresh are not changes of the administrator.
@@ -286,15 +303,16 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
} }
}; };
// A new crop goes to the server at once; the page then shows the photo as processing until the new variants are ready. // A new crop for ONE slide goes to the server at once; the slide then shows its photo as processing until its own variants are ready.
const applyFocus = (imageId: string, request: HeroFocusRequest) => { const applyFocus = (slideIndex: number, request: HeroFocusRequest) => {
const slideId = watchedSlides[slideIndex]?.id;
if (!slideId) return;
setServerError(null); setServerError(null);
setImageFocus.mutate( setSlideFocus.mutate(
{ imageId, request }, { slideId, request },
{ {
onSuccess: (image) => { onSuccess: (slide) => {
setLocalImages((current) => ({ ...current, [image.id]: image })); setRecutIds((current) => [...new Set([...current, slide.imageId])]);
setRecutIds((current) => [...new Set([...current, image.id])]);
}, },
onError: (error) => setServerError(serverMessage(error, t('errors.generic'), t('errors.network'))), onError: (error) => setServerError(serverMessage(error, t('errors.generic'), t('errors.network'))),
}, },
@@ -552,7 +570,8 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
<SortableContext items={slides.fields.map((f) => f.id)} strategy={verticalListSortingStrategy}> <SortableContext items={slides.fields.map((f) => f.id)} strategy={verticalListSortingStrategy}>
<ol className="space-y-3" data-testid="hero-slides"> <ol className="space-y-3" data-testid="hero-slides">
{slides.fields.map((field, index) => { {slides.fields.map((field, index) => {
const image = images[field.imageId]; const image = imageOfSlide(index);
const savedSlide = savedSlideOf(index);
const decorative = watchedSlides[index]?.decorative ?? false; const decorative = watchedSlides[index]?.decorative ?? false;
return ( return (
<SortableSlide key={field.id} id={field.id} index={index} dimmed={!(watchedSlides[index]?.isActive ?? true)}> <SortableSlide key={field.id} id={field.id} index={index} dimmed={!(watchedSlides[index]?.isActive ?? true)}>
@@ -565,16 +584,18 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
<CropThumbnail <CropThumbnail
image={image} image={image}
savedSrc={thumbnail(image)} savedSrc={thumbnail(image)}
onClick={() => setFocusImageId(field.imageId)} onClick={() => setFocusSlideIndex(index)}
testId={`hero-slide-${index}-focus`} testId={`hero-slide-${index}-focus`}
disabled={!savedSlide}
hint={t('hero.slides.saveFirst')}
/> />
) : ( ) : (
<div className="flex h-20 w-28 items-center justify-center rounded bg-muted text-xs">?</div> <div className="flex h-20 w-28 items-center justify-center rounded bg-muted text-xs">?</div>
)} )}
<DoneStatus done={Boolean(image && justDone[image.id] && !image.processing)} slideNumber={index + 1} testId={`hero-slide-${index}-done`} /> <DoneStatus done={Boolean(image && justDone[image.id] && !image.processing)} slideNumber={index + 1} testId={`hero-slide-${index}-done`} />
{watchedSlides.some((other, otherIndex) => otherIndex !== index && other?.imageId === field.imageId) && ( {!savedSlide && (
<p className="max-w-28 text-xs text-muted-foreground" data-testid={`hero-slide-${index}-shared-crop`}> <p className="max-w-28 text-xs text-muted-foreground" data-testid={`hero-slide-${index}-save-first`}>
{t('hero.library.sharedCrop')} {t('hero.slides.saveFirst')}
</p> </p>
)} )}
</div> </div>
@@ -666,9 +687,17 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
limitsText={limits ? t('hero.slides.limits', { formats: limits.formats.join(', '), size: Math.round(limits.maxUploadBytes / (1024 * 1024)), megapixels: limits.maxMegapixels }) : undefined} limitsText={limits ? t('hero.slides.limits', { formats: limits.formats.join(', '), size: Math.round(limits.maxUploadBytes / (1024 * 1024)), megapixels: limits.maxMegapixels }) : undefined}
/> />
<FocusDialog <FocusDialog
image={focusImageId ? images[focusImageId] ?? null : null} image={focusSlideIndex !== null ? imageOfSlide(focusSlideIndex) ?? null : null}
onApply={applyFocus} onApply={(_imageId, request) => focusSlideIndex !== null && applyFocus(focusSlideIndex, request)}
onClose={() => setFocusImageId(null)} onClose={() => setFocusSlideIndex(null)}
onReset={
focusSlideIndex !== null && savedSlideOf(focusSlideIndex)?.ownCrop
? () => {
const slideId = watchedSlides[focusSlideIndex]?.id;
if (slideId) resetSlideFocus.mutate(slideId, { onError: (error) => setServerError(serverMessage(error, t('errors.generic'), t('errors.network'))) });
}
: undefined
}
/> />
</form> </form>
); );
+18 -1
View File
@@ -1,6 +1,6 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api-client'; import { api } from '@/lib/api-client';
import type { HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest, HeroUploadLimits } from './types'; import type { HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest, HeroSlideAdminDto, HeroUploadLimits } from './types';
export const HERO_KEY = ['hero']; export const HERO_KEY = ['hero'];
@@ -73,6 +73,23 @@ export const heroImageQuery = (imageId: string) => ({
* A new crop for an image, applied at once without saving the hero (Bryan, 2026-11-17): the server cuts the new variants * A new crop for an image, applied at once without saving the hero (Bryan, 2026-11-17): the server cuts the new variants
* in the background and the image switches to them when they are complete. The answer is the image, now processing. * in the background and the image switches to them when they are complete. The answer is the image, now processing.
*/ */
export function useSetSlideFocus() {
const queryClient = useQueryClient();
return useMutation<HeroSlideAdminDto, Error, { slideId: string; request: HeroFocusRequest }>({
mutationFn: ({ slideId, request }) => api.put<HeroSlideAdminDto>(`/api/v1/hero/slides/${slideId}/focus`, request),
onSuccess: () => queryClient.invalidateQueries({ queryKey: HERO_KEY }),
});
}
/** Takes the slide's own crop away: it uses the crop of its photo again. */
export function useResetSlideFocus() {
const queryClient = useQueryClient();
return useMutation<HeroSlideAdminDto, Error, string>({
mutationFn: (slideId) => api.delete<HeroSlideAdminDto>(`/api/v1/hero/slides/${slideId}/focus`),
onSuccess: () => queryClient.invalidateQueries({ queryKey: HERO_KEY }),
});
}
export function useSetHeroImageFocus() { export function useSetHeroImageFocus() {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
return useMutation<HeroImageDto, Error, { imageId: string; request: HeroFocusRequest }>({ return useMutation<HeroImageDto, Error, { imageId: string; request: HeroFocusRequest }>({
@@ -48,7 +48,10 @@ export interface HeroSlideAdminDto {
decorative: boolean; decorative: boolean;
isActive: boolean; isActive: boolean;
sortOrder: number; sortOrder: number;
/** The photo as THIS slide shows it (its own crop and set when `ownCrop`); its id is always the photo's id. */
image: HeroImageDto; image: HeroImageDto;
/** The slide has a crop of its own (crop per use); otherwise it uses its photo's crop. */
ownCrop?: boolean;
} }
export interface HeroAdminDto { export interface HeroAdminDto {
@@ -645,8 +645,7 @@
"library": { "library": {
"title": "Add slide", "title": "Add slide",
"description": "Choose a photo from the media library or upload a new one; it then lands in the library too. Every slide has one photo. A slide's photo is not changed: remove the slide and add a new one.", "description": "Choose a photo from the media library or upload a new one; it then lands in the library too. Every slide has one photo. A slide's photo is not changed: remove the slide and add a new one.",
"group": "Photo for the new slide", "group": "Photo for the new slide"
"sharedCrop": "This photo is in more slides; the crop applies to all of them."
}, },
"slides": { "slides": {
"title": "Images", "title": "Images",
@@ -676,7 +675,8 @@
"number": "Slide {{n}}", "number": "Slide {{n}}",
"done": "Processing finished", "done": "Processing finished",
"doneFor": "Slide {{n}}: processing finished", "doneFor": "Slide {{n}}: processing finished",
"cropEdit": "Adjust crop" "cropEdit": "Adjust crop",
"saveFirst": "Save the slide first to change its crop."
}, },
"processing": { "processing": {
"count": "{{done}} of {{total}} photos processed", "count": "{{done}} of {{total}} photos processed",
@@ -710,7 +710,8 @@
}, },
"apply": "Apply", "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." "previewPending": "The preview of this photo is being prepared. Close this window and try again in a few seconds.",
"reset": "Use the photo’s crop again"
}, },
"errors": { "errors": {
"titleRequired": "A title is required.", "titleRequired": "A title is required.",
@@ -645,8 +645,7 @@
"library": { "library": {
"title": "Slide toevoegen", "title": "Slide toevoegen",
"description": "Kies een foto uit de mediabibliotheek of upload een nieuwe foto; die komt dan ook in de bibliotheek. Elke slide heeft één foto. Een foto wijzig je niet op een slide: verwijder de slide en voeg een nieuwe toe.", "description": "Kies een foto uit de mediabibliotheek of upload een nieuwe foto; die komt dan ook in de bibliotheek. Elke slide heeft één foto. Een foto wijzig je niet op een slide: verwijder de slide en voeg een nieuwe toe.",
"group": "Foto voor de nieuwe slide", "group": "Foto voor de nieuwe slide"
"sharedCrop": "Deze foto staat in meer slides; de uitsnede geldt voor allemaal."
}, },
"slides": { "slides": {
"title": "Afbeeldingen", "title": "Afbeeldingen",
@@ -676,7 +675,8 @@
"number": "Slide {{n}}", "number": "Slide {{n}}",
"done": "Verwerking afgerond", "done": "Verwerking afgerond",
"doneFor": "Slide {{n}}: verwerking afgerond", "doneFor": "Slide {{n}}: verwerking afgerond",
"cropEdit": "Uitsnede aanpassen" "cropEdit": "Uitsnede aanpassen",
"saveFirst": "Sla de slide eerst op om de uitsnede aan te passen."
}, },
"processing": { "processing": {
"count": "{{done}} van {{total}} foto’s verwerkt", "count": "{{done}} van {{total}} foto’s verwerkt",
@@ -710,7 +710,8 @@
}, },
"apply": "Toepassen", "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." "previewPending": "Het voorbeeld van deze foto wordt klaargezet. Sluit dit venster en probeer het over een paar seconden opnieuw.",
"reset": "Terug naar de uitsnede van de foto"
}, },
"errors": { "errors": {
"titleRequired": "Een titel is verplicht.", "titleRequired": "Een titel is verplicht.",