Files
slp-modular-cms/frontend/src/features/hero/components/FocusDialog.tsx
T

258 lines
13 KiB
TypeScript

import { useRef, useState, type KeyboardEvent, type PointerEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { CheckboxField } from '@/components/ui/checkbox';
import { RadioField } from '@/components/ui/radio';
import { Label } from '@/components/ui/label';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { mediaUrl } from '../lib/media';
import { CENTRE, MAX_ZOOM, TALL, WIDE, cropFor, normalizeFocus, type Ratio } from '../lib/focusMath';
import type { FocusDto, HeroFocusRequest, HeroImageDto } from '../services/types';
type Target = 'general' | 'wide' | 'tall';
interface FocusDialogProps {
/** The image to edit, with a not yet saved change of its focus already applied; null = closed. */
image: HeroImageDto | null;
/** Keeps the change locally: it is sent and made live when the hero is saved, and dropped when the page is left. */
onApply: (imageId: string, request: HeroFocusRequest) => void;
onClose: () => void;
/** "Use the crop of the photo again": applied at once, the dialog stays open. The button is always shown. */
onReset?: () => void;
/** The slide has a crop of its own; without one there is nothing to reset and the button is disabled. */
canReset?: boolean;
}
export function FocusDialog({ image, onApply, onClose, onReset, canReset = false }: FocusDialogProps) {
const { t } = useTranslation();
return (
<Dialog open={image !== null} onOpenChange={(next) => { if (!next) onClose(); }}>
<DialogContent className="max-h-[92vh] overflow-y-auto sm:max-w-3xl">
<DialogHeader>
<DialogTitle>{t('hero.focus.title')}</DialogTitle>
</DialogHeader>
{/* Mounted only while open, so every opening starts from the stored values. */}
{/* Keyed by the crop it shows, so after a reset it shows the photo's crop. */}
{image && <FocusEditor key={JSON.stringify([image.focus, image.wideFocus, image.tallFocus])} image={image} onApply={onApply} onClose={onClose} onReset={onReset} canReset={canReset} />}
</DialogContent>
</Dialog>
);
}
const percent = (fraction: number) => Math.round(fraction * 1000) / 10;
function FocusEditor({ image, onApply, onClose, onReset, canReset }: { image: HeroImageDto; onApply: (imageId: string, request: HeroFocusRequest) => void; onClose: () => void; onReset?: () => void; canReset: boolean }) {
const { t } = useTranslation();
const area = useRef<HTMLDivElement>(null);
// The whole picture: image.src is already a crop of the wide shape and would be shown stretched and out of place.
const previewUrl = image.previewSrc ? mediaUrl(image.previewSrc) : null;
const [target, setTarget] = useState<Target>('general');
const [general, setGeneral] = useState<FocusDto>(image.focus ?? CENTRE);
const [wide, setWide] = useState<FocusDto | null>(image.wideFocus);
const [tall, setTall] = useState<FocusDto | null>(image.tallFocus);
const effective = { wide: wide ?? general, tall: tall ?? general };
const active: FocusDto = target === 'general' ? general : (target === 'wide' ? wide : tall) ?? general;
const editable = target === 'general' || (target === 'wide' ? wide : tall) !== null;
const update = (next: FocusDto) => {
const clean = normalizeFocus(next);
if (target === 'general') setGeneral(clean);
else if (target === 'wide') setWide(clean);
else setTall(clean);
};
const toggleOverride = (checked: boolean) => {
const value = checked ? { ...general } : null;
if (target === 'wide') setWide(value);
if (target === 'tall') setTall(value);
};
const moveTo = (event: PointerEvent<HTMLDivElement>) => {
const box = area.current?.getBoundingClientRect();
if (!box || box.width === 0 || box.height === 0 || !editable) return;
update({ ...active, x: (event.clientX - box.left) / box.width, y: (event.clientY - box.top) / box.height });
};
const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (!editable) return;
const step = event.shiftKey ? 0.05 : 0.01;
const moves: Record<string, [number, number]> = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] };
const move = moves[event.key];
if (!move) return;
event.preventDefault();
update({ ...active, x: active.x + move[0], y: active.y + move[1] });
};
const onSave = () => {
onApply(image.id, { focus: general, wide, tall });
onClose();
};
const outline = (ratio: Ratio, focus: FocusDto) => {
const c = cropFor(image.width, image.height, ratio, focus);
return {
left: `${(c.x / image.width) * 100}%`,
top: `${(c.y / image.height) * 100}%`,
width: `${(c.width / image.width) * 100}%`,
height: `${(c.height / image.height) * 100}%`,
};
};
return (
<div className="space-y-4" data-testid="focus-dialog">
<p className="text-sm text-muted-foreground">{t('hero.focus.intro')}</p>
<fieldset className="flex flex-wrap gap-4">
<legend className="sr-only">{t('hero.focus.targetLegend')}</legend>
{(['general', 'wide', 'tall'] as const).map((value) => (
<RadioField
key={value}
name="focus-target"
checked={target === value}
onChange={() => setTarget(value)}
data-testid={`focus-target-${value}`}
label={t(`hero.focus.target.${value}`)}
/>
))}
</fieldset>
{target !== 'general' && (
<CheckboxField
checked={editable}
onChange={(event) => toggleOverride(event.target.checked)}
data-testid={`focus-override-${target}`}
label={t('hero.focus.override')}
/>
)}
<div className="grid gap-4 md:grid-cols-[2fr_1fr]">
<div>
<div
ref={area}
role="group"
tabIndex={0}
aria-label={t('hero.focus.areaLabel')}
className="relative touch-none select-none overflow-hidden rounded-md border"
style={{ aspectRatio: `${image.width} / ${image.height}` }}
onPointerDown={(event) => {
event.currentTarget.setPointerCapture?.(event.pointerId);
moveTo(event);
}}
onPointerMove={(event) => {
if (event.buttons === 1) moveTo(event);
}}
onKeyDown={onKeyDown}
data-testid="focus-area"
>
{previewUrl ? (
<img src={previewUrl} alt="" draggable={false} className="pointer-events-none absolute inset-0 h-full w-full object-cover" />
) : (
<p className="absolute inset-0 flex items-center justify-center bg-muted p-4 text-center text-sm text-muted-foreground" role="status" data-testid="focus-preview-pending">
{t('hero.focus.previewPending')}
</p>
)}
<div className="pointer-events-none absolute border-2 border-sky-400" style={outline(WIDE, effective.wide)} data-testid="focus-outline-wide" />
<div className="pointer-events-none absolute border-2 border-amber-400" style={outline(TALL, effective.tall)} data-testid="focus-outline-tall" />
<div
className="pointer-events-none absolute size-5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white bg-red-500/80 shadow"
style={{ left: `${active.x * 100}%`, top: `${active.y * 100}%` }}
data-testid="focus-marker"
/>
</div>
<p className="mt-1 text-xs text-muted-foreground">{t('hero.focus.areaHint')}</p>
</div>
<div className="space-y-3">
<div className="grid grid-cols-2 gap-2">
<div className="space-y-1">
<Label htmlFor="focus-x">{t('hero.focus.x')}</Label>
<Input
id="focus-x"
type="number"
min={0}
max={100}
step={0.5}
disabled={!editable}
value={percent(active.x)}
onChange={(event) => update({ ...active, x: Number(event.target.value) / 100 })}
data-testid="focus-x"
/>
</div>
<div className="space-y-1">
<Label htmlFor="focus-y">{t('hero.focus.y')}</Label>
<Input
id="focus-y"
type="number"
min={0}
max={100}
step={0.5}
disabled={!editable}
value={percent(active.y)}
onChange={(event) => update({ ...active, y: Number(event.target.value) / 100 })}
data-testid="focus-y"
/>
</div>
</div>
<div className="space-y-1">
<Label htmlFor="focus-zoom">{t('hero.focus.zoom', { value: active.zoom.toFixed(2) })}</Label>
<input
id="focus-zoom"
type="range"
min={1}
max={MAX_ZOOM}
step={0.05}
disabled={!editable}
value={active.zoom}
onChange={(event) => update({ ...active, zoom: Number(event.target.value) })}
className="w-full accent-primary disabled:cursor-not-allowed disabled:opacity-50"
data-testid="focus-zoom"
/>
</div>
{([WIDE, TALL] as const).map((ratio) => {
const crop = cropFor(image.width, image.height, ratio, effective[ratio.name]);
return (
<div key={ratio.name}>
<p className="mb-1 text-xs font-medium">{t(`hero.focus.preview.${ratio.name}`)}</p>
<div
className="relative overflow-hidden rounded border bg-muted"
style={{ aspectRatio: `${ratio.numerator} / ${ratio.denominator}`, maxWidth: ratio.name === 'tall' ? '8rem' : '12rem' }}
data-testid={`focus-preview-${ratio.name}`}
>
{previewUrl && <img
src={previewUrl}
alt=""
className="absolute max-w-none"
style={{
width: `${(image.width / crop.width) * 100}%`,
left: `${(-crop.x / crop.width) * 100}%`,
// top is a percentage of the box height, which is the box width times denominator over numerator.
top: `${(-crop.y / crop.width) * (ratio.numerator / ratio.denominator) * 100}%`,
}}
/>}
</div>
</div>
);
})}
</div>
</div>
<div className="flex flex-wrap justify-end gap-2">
{onReset && (
<Button type="button" variant="outline" className="mr-auto" disabled={!canReset} onClick={onReset} data-testid="focus-reset">
{t('hero.focus.reset')}
</Button>
)}
<Button type="button" variant="outline" onClick={onClose} data-testid="focus-cancel">
{t('common.cancel')}
</Button>
<Button type="button" onClick={onSave} data-testid="focus-save">
{t('hero.focus.apply')}
</Button>
</div>
</div>
);
}