Hero: grote foto's in de achtergrond robuust en sneller, voortgang en opnieuw proberen; admin zonder inline script
- Een decode voor de hele set, per breedte eenmaal geschaald voor WebP en AVIF (6000x4000: 21,1 s -> 6,4 s per set) - Eigen limiet per set (Media:RenderSetTimeoutSeconds 600), harde limiet rond een foto, de renderer stopt nooit door een uitzondering, een mislukte foto wacht tot de volgende ronde en houdt de rij niet op - Logging per foto (start, per variant, einde, fout); voortgang per variant in de admin; nieuwe uitsnede na focuswijziging zichtbaar (oude afbeelding blijft, shimmer); knop Opnieuw proberen - Thema-script als /theme-init.js (CSP script-src 'self'), test en smoke-controle op inline scripts Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
+2
-7
@@ -5,13 +5,8 @@
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>SlpModularCms</title>
|
||||
<script>
|
||||
(function () {
|
||||
var s = localStorage.getItem('cms-theme');
|
||||
var t = s === 'light' || s === 'dark' ? s : (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
|
||||
document.documentElement.classList.add(t);
|
||||
})();
|
||||
</script>
|
||||
<!-- A file of its own, loaded before the app: the host only allows scripts from its own origin (no inline scripts). -->
|
||||
<script src="/theme-init.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
// Sets the light or dark theme before the first paint, so the page does not flash in the wrong theme. A file of its own
|
||||
// (not an inline script) because the host allows scripts from its own origin only (Content-Security-Policy script-src 'self').
|
||||
(function () {
|
||||
var stored = null;
|
||||
try {
|
||||
stored = localStorage.getItem('cms-theme');
|
||||
} catch (e) {
|
||||
stored = null;
|
||||
}
|
||||
var theme = stored === 'light' || stored === 'dark' ? stored : (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
|
||||
document.documentElement.classList.add(theme);
|
||||
})();
|
||||
@@ -0,0 +1,28 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
// The host sends Content-Security-Policy "script-src 'self'": an inline script in the admin page is blocked there, so the
|
||||
// page must have none (the theme is set by /theme-init.js, a file of its own).
|
||||
describe('the admin page and the Content-Security-Policy', () => {
|
||||
const html = readFileSync(resolve(__dirname, '../index.html'), 'utf-8');
|
||||
|
||||
it('has no inline script', () => {
|
||||
const inline = [...html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].filter(([, attributes]) => !/\bsrc\s*=/.test(attributes));
|
||||
|
||||
expect(inline).toEqual([]);
|
||||
});
|
||||
|
||||
it('sets the theme from a file of its own, before the app', () => {
|
||||
expect(html.indexOf('src="/theme-init.js"')).toBeGreaterThan(-1);
|
||||
expect(html.indexOf('src="/theme-init.js"')).toBeLessThan(html.indexOf('src="/src/main.tsx"'));
|
||||
const script = readFileSync(resolve(__dirname, '../public/theme-init.js'), 'utf-8');
|
||||
expect(script).toContain("localStorage.getItem('cms-theme')");
|
||||
expect(script).toContain('classList.add');
|
||||
});
|
||||
|
||||
it('has no inline event handlers or javascript: links either', () => {
|
||||
expect(html).not.toMatch(/\son[a-z]+\s*=/i);
|
||||
expect(html).not.toMatch(/javascript:/i);
|
||||
});
|
||||
});
|
||||
@@ -23,6 +23,11 @@ export function ProcessingStatus({ hero }: { hero: HeroAdminDto }) {
|
||||
const done = total - waiting.length;
|
||||
const failed = waiting.filter((s) => s.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 fraction = busy && busy.renderTotal ? (busy.renderDone ?? 0) / busy.renderTotal : 0;
|
||||
const percent = total === 0 ? 0 : Math.min(100, ((done + fraction) / total) * 100);
|
||||
|
||||
return (
|
||||
<div className="space-y-3 rounded-md border bg-muted/40 p-4" data-testid="hero-processing">
|
||||
@@ -42,9 +47,26 @@ export function ProcessingStatus({ hero }: { hero: HeroAdminDto }) {
|
||||
className="h-2 w-full overflow-hidden rounded bg-muted"
|
||||
data-testid="hero-processing-bar"
|
||||
>
|
||||
<div className="h-full bg-primary transition-all" style={{ width: `${total === 0 ? 0 : (done / total) * 100}%` }} />
|
||||
<div className="h-full bg-primary transition-all" style={{ width: `${percent}%` }} />
|
||||
</div>
|
||||
{busy && (
|
||||
<p className="text-sm" data-testid="hero-processing-current">
|
||||
{t('hero.processing.current', { n: done + 1, total, step: busy.renderDone ?? 0, steps: busy.renderTotal })}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm text-muted-foreground">{t('hero.processing.explain')}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('hero.processing.stuck')}{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="underline underline-offset-2 hover:text-foreground disabled:opacity-50"
|
||||
disabled={retry.isPending}
|
||||
onClick={() => waiting.forEach((s) => retry.mutate(s.imageId))}
|
||||
data-testid="hero-processing-retry-all"
|
||||
>
|
||||
{t('hero.processing.retry')}
|
||||
</button>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{failed.length > 0 && (
|
||||
@@ -72,7 +94,7 @@ export function ProcessingStatus({ hero }: { hero: HeroAdminDto }) {
|
||||
* text. It lives in the row of the slide, so it stays mounted (and the animation keeps running) while the page asks the
|
||||
* server again every few seconds, and it disappears when the photo is ready.
|
||||
*/
|
||||
export function PhotoPlaceholder({ failed, testId }: { failed: boolean; testId: string }) {
|
||||
export function PhotoPlaceholder({ failed, testId, step }: { failed: boolean; testId: string; step?: { done: number; total: number } | null }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div
|
||||
@@ -84,6 +106,31 @@ export function PhotoPlaceholder({ failed, testId }: { failed: boolean; testId:
|
||||
>
|
||||
{failed ? null : <Spinner className="size-3.5" />}
|
||||
<span>{failed ? t('hero.slides.failed') : t('hero.slides.processing')}</span>
|
||||
{!failed && step ? <span className="tabular-nums opacity-80" data-testid={`${testId}-step`}>{step.done}/{step.total}</span> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The photo of a slide whose crop is being made again (a changed focus point): the old picture stays visible underneath,
|
||||
* with the same calm shimmer and a short text, so it is clear that the change is not on the website yet.
|
||||
*/
|
||||
export function RecutThumbnail({ src, failed, testId, step }: { src: string; failed: boolean; testId: string; step?: { done: number; total: number } | null }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div
|
||||
className={`relative h-20 w-28 shrink-0 overflow-hidden rounded ${failed ? 'ring-2 ring-destructive' : 'hero-shimmer'}`}
|
||||
role="status"
|
||||
aria-busy={!failed}
|
||||
title={t('hero.slides.recutHint')}
|
||||
data-testid={testId}
|
||||
>
|
||||
<img src={src} alt="" className="h-full w-full object-cover" />
|
||||
<span className={`absolute inset-x-0 bottom-0 flex items-center justify-center gap-1 px-1 py-0.5 text-center text-[10px] leading-tight ${failed ? 'bg-destructive text-destructive-foreground' : 'bg-background/85 text-foreground'}`}>
|
||||
{failed ? null : <Spinner className="size-3" />}
|
||||
<span>{failed ? t('hero.slides.failed') : t('hero.slides.recut')}</span>
|
||||
{!failed && step ? <span className="tabular-nums opacity-80" data-testid={`${testId}-step`}>{step.done}/{step.total}</span> : null}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -59,6 +59,7 @@ export const resetMockHero = (): void => {
|
||||
uploads = 0;
|
||||
uploadFailure = null;
|
||||
retried = [];
|
||||
recutting = new Set();
|
||||
};
|
||||
|
||||
export const setMockHero = (next: HeroAdminDto): void => {
|
||||
@@ -67,6 +68,15 @@ export const setMockHero = (next: HeroAdminDto): void => {
|
||||
};
|
||||
|
||||
let retried: string[] = [];
|
||||
let recutting = new Set<string>();
|
||||
/** The background work of the mock server is done: images whose crop was being made are ready. */
|
||||
export const finishMockRecut = (): void => {
|
||||
recutting.forEach((id) => {
|
||||
if (images[id]) images[id] = { ...images[id], processing: false };
|
||||
hero = { ...hero, slides: hero.slides.map((s) => (s.imageId === id ? { ...s, image: { ...s.image, processing: false } } : s)) };
|
||||
});
|
||||
recutting = new Set();
|
||||
};
|
||||
export const getRetriedImages = (): string[] => retried;
|
||||
|
||||
export const getSavedHeroRequests = (): HeroSaveRequest[] => saved;
|
||||
@@ -84,7 +94,8 @@ export const heroHandlers = [
|
||||
// A changed focus takes effect with the save of the hero.
|
||||
for (const edit of body.imageFocus ?? []) {
|
||||
const current = images[edit.imageId] ?? hero.slides.find((s) => s.imageId === edit.imageId)?.image ?? seedImage(edit.imageId);
|
||||
images[edit.imageId] = { ...current, focus: edit.focus, wideFocus: edit.wide, tallFocus: edit.tall };
|
||||
images[edit.imageId] = { ...current, focus: edit.focus, wideFocus: edit.wide, tallFocus: edit.tall, processing: true };
|
||||
recutting.add(edit.imageId);
|
||||
}
|
||||
hero = {
|
||||
...hero,
|
||||
|
||||
@@ -5,7 +5,7 @@ import { http, HttpResponse } from 'msw';
|
||||
import { server } from '@/mocks/server';
|
||||
import { API_BASE } from '@/features/auth/mocks/fixtures';
|
||||
import { renderApp, mockAuthenticated } from '@/test/utils';
|
||||
import { emptyHero, failNextUpload, getRetriedImages, getSavedHeroRequests, resetMockHero, setMockHero, slide } from '@/features/hero/mocks/handlers';
|
||||
import { emptyHero, failNextUpload, finishMockRecut, getRetriedImages, getSavedHeroRequests, resetMockHero, setMockHero, slide } from '@/features/hero/mocks/handlers';
|
||||
import { _resetSetupStatusCache } from '@/router';
|
||||
|
||||
const T = { timeout: 10000 };
|
||||
@@ -665,3 +665,74 @@ describe('Order by dragging, wording and calm waiting', () => {
|
||||
expect(screen.getByTestId('hero-slide-0-processing')).toBe(before);
|
||||
}, 20000);
|
||||
});
|
||||
|
||||
|
||||
describe('Progress of a photo that is being prepared', () => {
|
||||
beforeEach(() => {
|
||||
resetMockHero();
|
||||
});
|
||||
|
||||
it('shows which photo is being worked on and at which step', 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: [slide(1), waiting(2, [7, 16]), waiting(3)] });
|
||||
|
||||
await openPage();
|
||||
|
||||
expect(await screen.findByTestId('hero-processing-current', {}, T)).toHaveTextContent(/foto 2 van 3.*stap 7 van 16|photo 2 of 3.*step 7 of 16/);
|
||||
expect(screen.getByTestId('hero-slide-1-processing-step')).toHaveTextContent('7/16');
|
||||
expect(screen.queryByTestId('hero-slide-2-processing-step')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe('A changed focus point makes a new crop in the background', () => {
|
||||
beforeEach(() => {
|
||||
resetMockHero();
|
||||
});
|
||||
|
||||
it('shows that the new crop is not live yet (old picture underneath), counts it in the total, and clears it when done', async () => {
|
||||
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), slide(2)] });
|
||||
await openPage();
|
||||
await userEvent.click(screen.getByTestId('hero-slide-0-focus'));
|
||||
fireEvent.change(await screen.findByTestId('focus-x', {}, T), { target: { value: '25' } });
|
||||
await userEvent.click(screen.getByTestId('focus-save'));
|
||||
await userEvent.click(screen.getByTestId('hero-save'));
|
||||
|
||||
const recut = await screen.findByTestId('hero-slide-0-recut', {}, T);
|
||||
expect(recut).toHaveClass('hero-shimmer');
|
||||
expect(recut.querySelector('img')).not.toBeNull();
|
||||
expect(recut).toHaveTextContent(/Nieuwe uitsnede|new crop/);
|
||||
expect(screen.getByTestId('hero-processing-count')).toHaveTextContent(/1 van 2|1 of 2/);
|
||||
expect(screen.queryByTestId('hero-slide-1-recut')).not.toBeInTheDocument();
|
||||
|
||||
// The server finishes the new crop; the page asks again by itself.
|
||||
finishMockRecut();
|
||||
await waitFor(() => expect(screen.queryByTestId('hero-slide-0-recut')).not.toBeInTheDocument(), { timeout: 12000 });
|
||||
expect(screen.queryByTestId('hero-processing')).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('hero-slide-0-focus')).toBeEnabled();
|
||||
}, 25000);
|
||||
|
||||
it('shows a failed new crop with the retry', async () => {
|
||||
const failed = { ...slide(1), image: { ...slide(1).image, processing: true, failed: true } };
|
||||
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [failed] });
|
||||
|
||||
await openPage();
|
||||
|
||||
expect(await screen.findByTestId('hero-slide-0-recut', {}, T)).toHaveTextContent(/Mislukt|Failed/);
|
||||
await userEvent.click(screen.getByTestId('hero-processing-retry'));
|
||||
await waitFor(() => expect(getRetriedImages()).toEqual([failed.imageId]), T);
|
||||
});
|
||||
|
||||
it('offers to try again for a photo that takes long', async () => {
|
||||
const waiting = { ...slide(1), image: { ...slide(1).image, variants: [], src: '', processing: true } };
|
||||
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [waiting] });
|
||||
await openPage();
|
||||
|
||||
await userEvent.click(await screen.findByTestId('hero-processing-retry-all', {}, T));
|
||||
|
||||
await waitFor(() => expect(getRetriedImages()).toEqual([waiting.imageId]), T);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,7 +14,7 @@ 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 } from '../components/ProcessingStatus';
|
||||
import { PhotoPlaceholder, ProcessingStatus, RecutThumbnail } from '../components/ProcessingStatus';
|
||||
import { SortableSlide } from '../components/SortableSlide';
|
||||
import { UnsavedChangesGuard } from '../components/UnsavedChangesGuard';
|
||||
import { UploadProgress, type UploadItem } from '../components/UploadProgress';
|
||||
@@ -425,7 +425,9 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
return (
|
||||
<SortableSlide key={field.id} id={field.id} index={index}>
|
||||
{image && image.variants.length === 0 ? (
|
||||
<PhotoPlaceholder failed={image.failed} testId={`hero-slide-${index}-processing`} />
|
||||
<PhotoPlaceholder failed={image.failed} testId={`hero-slide-${index}-processing`} step={image.renderTotal ? { done: image.renderDone ?? 0, total: image.renderTotal } : null} />
|
||||
) : image?.processing ? (
|
||||
<RecutThumbnail src={thumbnail(image)} failed={image.failed} testId={`hero-slide-${index}-recut`} step={image.renderTotal ? { done: image.renderDone ?? 0, total: image.renderTotal } : null} />
|
||||
) : image ? (
|
||||
<img src={thumbnail(image)} alt="" className="h-20 w-28 rounded object-cover" />
|
||||
) : (
|
||||
|
||||
@@ -27,6 +27,9 @@ export interface HeroImageDto {
|
||||
processing: boolean;
|
||||
/** The background renderer gave up on this image after a few tries; it can be retried. */
|
||||
failed: boolean;
|
||||
/** While the image is being cut: the step it is at, out of how many (null when it is not being cut right now). */
|
||||
renderDone?: number | null;
|
||||
renderTotal?: number | null;
|
||||
}
|
||||
|
||||
export interface HeroButtonDto {
|
||||
|
||||
@@ -663,7 +663,9 @@
|
||||
"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."
|
||||
"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."
|
||||
},
|
||||
"processing": {
|
||||
"count": "{{done}} of {{total}} photos processed",
|
||||
@@ -672,7 +674,9 @@
|
||||
"failed_one": "Processing {{count}} photo failed.",
|
||||
"failed_other": "Processing {{count}} photos failed.",
|
||||
"failedHint": "The server tried three times. Try again, or upload the photo once more (the same photo is the same image).",
|
||||
"retry": "Try again"
|
||||
"retry": "Try again",
|
||||
"current": "Working on photo {{n}} of {{total}}: step {{step}} of {{steps}}. A large photo can take a few minutes.",
|
||||
"stuck": "Taking long?"
|
||||
},
|
||||
"focus": {
|
||||
"title": "Focus and crop",
|
||||
|
||||
@@ -663,7 +663,9 @@
|
||||
"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."
|
||||
"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."
|
||||
},
|
||||
"processing": {
|
||||
"count": "{{done}} van {{total}} foto’s verwerkt",
|
||||
@@ -672,7 +674,9 @@
|
||||
"failed_one": "Het verwerken van {{count}} foto is mislukt.",
|
||||
"failed_other": "Het verwerken van {{count}} foto’s is mislukt.",
|
||||
"failedHint": "De server heeft het drie keer geprobeerd. Probeer het opnieuw, of upload de foto nog een keer (dezelfde foto is dezelfde afbeelding).",
|
||||
"retry": "Opnieuw proberen"
|
||||
"retry": "Opnieuw proberen",
|
||||
"current": "Bezig met foto {{n}} van {{total}}: stap {{step}} van {{steps}}. Een grote foto kan enkele minuten duren.",
|
||||
"stuck": "Duurt het lang?"
|
||||
},
|
||||
"focus": {
|
||||
"title": "Focus en uitsnede",
|
||||
|
||||
Reference in New Issue
Block a user