mirror of
https://github.com/IliesAllali/parenthese.git
synced 2026-11-18 08:52:11 +00:00
Merge remote-tracking branch 'origin/main' into feat/fiche-glisser-fermer
This commit is contained in:
commit
a88d06c513
14 files changed
+238
-47
No files matched your search
@@ -1,9 +1,10 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
// Cadrage d'un portrait : centre (proportions de l'image) et zoom. Zoom 1 = l'image entière recouvre le cadre.
|
||||
// Les bornes qui empêchent le vide sont appliquées à l'affichage (frontend, portraitCrop.js), le serveur
|
||||
// vérifie seulement la forme et les plages.
|
||||
export type AvatarCrop = { x: number; y: number; zoom: number }
|
||||
// Cadrage d'un portrait : centre (proportions de l'image), zoom, et forme du cadre si on l'a choisie.
|
||||
// Zoom 1 = l'image entière recouvre le cadre. Les bornes qui empêchent le vide sont appliquées à
|
||||
// l'affichage (frontend, portraitCrop.js), le serveur vérifie seulement la forme et les plages.
|
||||
export const FRAME_SHAPES = ['round', 'square', 'polaroid', 'portrait', 'landscape'] as const
|
||||
export type AvatarCrop = { x: number; y: number; zoom: number; shape?: (typeof FRAME_SHAPES)[number] }
|
||||
|
||||
export const AVATAR_CROP_MAX_ZOOM = 4
|
||||
|
||||
@@ -13,16 +14,18 @@ export const avatarCropInputSchema = z.object({
|
||||
x: z.number().min(0).max(1),
|
||||
y: z.number().min(0).max(1),
|
||||
zoom: z.number().min(1).max(AVATAR_CROP_MAX_ZOOM),
|
||||
shape: z.enum(FRAME_SHAPES).optional(),
|
||||
})
|
||||
.nullable(),
|
||||
})
|
||||
|
||||
const round4 = (value: number) => Math.round(value * 10000) / 10000
|
||||
|
||||
// Forme à écrire en base. Le cadrage par défaut se stocke comme absence de cadrage (null).
|
||||
// Forme à écrire en base. Le cadrage par défaut, sans forme choisie, se stocke comme absence de cadrage (null).
|
||||
export function toStoredAvatarCrop(crop: AvatarCrop | null): AvatarCrop | null {
|
||||
if (!crop) return null
|
||||
const normalized = { x: round4(crop.x), y: round4(crop.y), zoom: round4(crop.zoom) }
|
||||
if (crop.shape) return { ...normalized, shape: crop.shape }
|
||||
if (normalized.x === 0.5 && normalized.y === 0.5 && normalized.zoom === 1) return null
|
||||
return normalized
|
||||
}
|
||||
|
||||
@@ -166,6 +166,19 @@ describe('PUT /trees/:id/persons/:personId/avatar/crop', () => {
|
||||
expect(prismaMock.person.updateMany.mock.calls[0][0].data.avatarCrop).toBe(Prisma.DbNull)
|
||||
})
|
||||
|
||||
it('garde la forme choisie, même avec un cadrage centré, et refuse une forme inconnue', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
const put = (crop: unknown) => app.inject({ method: 'PUT', url, headers: { authorization: `Bearer ${token}` }, payload: { crop } })
|
||||
|
||||
const saved = await put({ x: 0.5, y: 0.5, zoom: 1, shape: 'round' })
|
||||
expect(saved.statusCode).toBe(200)
|
||||
expect(saved.json()).toEqual({ ok: true, avatarCrop: { x: 0.5, y: 0.5, zoom: 1, shape: 'round' } })
|
||||
expect(prismaMock.person.updateMany.mock.calls[0][0].data.avatarCrop).toEqual({ x: 0.5, y: 0.5, zoom: 1, shape: 'round' })
|
||||
|
||||
expect((await put({ x: 0.5, y: 0.5, zoom: 1, shape: 'hexagone' })).statusCode).toBe(400)
|
||||
})
|
||||
|
||||
it('répond 404 sans portrait, et 409 pour un portrait venu d Immich', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
|
||||
+54
-1
@@ -51,7 +51,7 @@ import {
|
||||
reorderSiblings,
|
||||
uploadPersonMedia,
|
||||
} from './api/treeApi'
|
||||
import { getImmichErrorMessage, unassignImmichPerson } from './api/immichApi.js'
|
||||
import { fetchImmichConfig, getImmichErrorMessage, unassignImmichPerson } from './api/immichApi.js'
|
||||
import { useAuth } from './hooks/useAuth'
|
||||
import { useTreeAccess, getTreeTokenStorageKey, getSlugFromPathname, readTreeAccessRole, TREE_ID_FROM_ENV } from './hooks/useTreeAccess'
|
||||
import { useMediaManager } from './hooks/useMediaManager'
|
||||
@@ -1686,6 +1686,51 @@ function App() {
|
||||
}
|
||||
}, [auth.userAuth.token, tree.treeContext.accessToken, tree.treeContext.treeId, refreshTreeAndKeepSelection])
|
||||
|
||||
// « + photo » dans l'arbre : le sélecteur part dans le clic (Safari iOS refuse un input file ouvert hors geste),
|
||||
// puis la fenêtre de recadrage s'ouvre dans la fiche de la personne
|
||||
const portraitInputRef = useRef(null)
|
||||
const portraitPickerPersonIdRef = useRef(null)
|
||||
const [pendingPortraitCrop, setPendingPortraitCrop] = useState(null)
|
||||
const [photoSourceRequest, setPhotoSourceRequest] = useState(null)
|
||||
const [immichSourceReady, setImmichSourceReady] = useState(false)
|
||||
|
||||
// Administrateur : Immich proposé dans le menu des sources seulement s'il est configuré
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
const treeId = tree.treeContext.treeId
|
||||
const token = tree.treeContext.accessToken || auth.userAuth.token
|
||||
if (!userRole.isAdmin || !tree.canEditCurrentTree || !treeId || !token) {
|
||||
setImmichSourceReady(false)
|
||||
return undefined
|
||||
}
|
||||
fetchImmichConfig(treeId, token)
|
||||
.then(({ config }) => { if (!cancelled) setImmichSourceReady(Boolean(config?.configured)) })
|
||||
.catch(() => { if (!cancelled) setImmichSourceReady(false) })
|
||||
return () => { cancelled = true }
|
||||
}, [userRole.isAdmin, tree.canEditCurrentTree, tree.treeContext.treeId, tree.treeContext.accessToken, auth.userAuth.token])
|
||||
|
||||
const handlePhotoPlaceholderClick = useCallback((personId) => {
|
||||
// En modification avec Immich : le menu des sources s'ouvre dans la fiche (le badge en est l'ancre)
|
||||
if (editMode.isActive && immichSourceReady) {
|
||||
setPhotoSourceRequest({ personId })
|
||||
} else {
|
||||
// Sans menu : le sélecteur de fichiers part tout de suite, dans le clic
|
||||
portraitPickerPersonIdRef.current = personId
|
||||
portraitInputRef.current?.click()
|
||||
}
|
||||
handlePersonSelect(personId)
|
||||
}, [editMode.isActive, immichSourceReady, handlePersonSelect])
|
||||
|
||||
const handlePortraitPicked = useCallback(async (event) => {
|
||||
const file = event.target.files?.[0]
|
||||
event.target.value = ''
|
||||
const personId = portraitPickerPersonIdRef.current
|
||||
portraitPickerPersonIdRef.current = null
|
||||
if (!file || personId === null) return
|
||||
const result = await handlePersonAvatarUpload(personId, file)
|
||||
if (result?.previewUrl) setPendingPortraitCrop({ personId, src: result.previewUrl })
|
||||
}, [handlePersonAvatarUpload])
|
||||
|
||||
// Visage venu d'Immich : recharger l'arbre pour montrer le nouveau portrait (ou le portrait restant)
|
||||
const handleImmichChange = useCallback(async (personId) => {
|
||||
await refreshTreeAndKeepSelection(personId, { relayout: false, avatarCacheBust: Date.now() })
|
||||
@@ -3135,10 +3180,14 @@ function App() {
|
||||
focusPersonId={tree.treeContext.rootPersonId}
|
||||
assetRevision={tree.assetRevision}
|
||||
photoHint={tree.canEditCurrentTree}
|
||||
onPhotoPlaceholderClick={tree.canEditCurrentTree ? handlePhotoPlaceholderClick : null}
|
||||
reorderEnabled={canReorderSiblings}
|
||||
onReorderSiblings={handleReorderSiblings}
|
||||
/>
|
||||
<ZoomControl zoomApiRef={galaxyZoomApiRef} />
|
||||
{tree.canEditCurrentTree && (
|
||||
<input ref={portraitInputRef} type="file" accept="image/*" className="pc-hidden-input" onChange={handlePortraitPicked} />
|
||||
)}
|
||||
{tree.selectedPerson && (
|
||||
<PersonCard
|
||||
person={tree.selectedPerson}
|
||||
@@ -3151,6 +3200,10 @@ function App() {
|
||||
onAvatarUpload={tree.canEditCurrentTree ? handlePersonAvatarUpload : undefined}
|
||||
onAvatarDelete={tree.canEditCurrentTree ? handlePersonAvatarDelete : undefined}
|
||||
onAvatarCrop={tree.canEditCurrentTree ? handlePersonAvatarCrop : undefined}
|
||||
pendingPortraitCrop={pendingPortraitCrop}
|
||||
onPendingPortraitCropDone={() => setPendingPortraitCrop(null)}
|
||||
photoSourceRequest={photoSourceRequest}
|
||||
onPhotoSourceRequestDone={() => setPhotoSourceRequest(null)}
|
||||
treeId={tree.treeContext.treeId || null}
|
||||
immichToken={tree.treeContext.accessToken || auth.userAuth.token}
|
||||
onImmichChange={tree.canEditCurrentTree ? handleImmichChange : undefined}
|
||||
|
||||
@@ -40,7 +40,7 @@ const DROP_SPRING = { stiffness: 480, dampingRatio: 0.72 }
|
||||
const centerX = (node) => node.x + node.width / 2
|
||||
const prefersReducedMotion = () => typeof window !== 'undefined' && window.matchMedia?.('(prefers-reduced-motion: reduce)').matches
|
||||
|
||||
const Galaxy = ({ onPersonSelect, onMediaSelect, selectedPersonId, searchHighlightIds = [], graphRevision = 0, annotationHandlers = null, transformReadRef = null, zoomApiRef = null, focusPersonId = null, assetRevision = 0, photoHint = false, reorderEnabled = false, onReorderSiblings = null }) => {
|
||||
const Galaxy = ({ onPersonSelect, onMediaSelect, selectedPersonId, searchHighlightIds = [], graphRevision = 0, annotationHandlers = null, transformReadRef = null, zoomApiRef = null, focusPersonId = null, assetRevision = 0, photoHint = false, onPhotoPlaceholderClick = null, reorderEnabled = false, onReorderSiblings = null }) => {
|
||||
const canvasRef = useRef(null)
|
||||
// Lu au calcul du cadrage seulement : changer de personne de départ ne recadre pas une vue en cours
|
||||
const focusPersonIdRef = useRef(focusPersonId)
|
||||
@@ -139,7 +139,7 @@ const Galaxy = ({ onPersonSelect, onMediaSelect, selectedPersonId, searchHighlig
|
||||
canvasRef, transformRef, targetTransformRef,
|
||||
layoutDataRef, nodeRandomDataRef, entranceRef,
|
||||
hoveredNodeIdRef: hoveredNodeId, hoveredMediaKeyRef: hoveredMediaKey, mouseWorldPosRef: mouseWorldPos,
|
||||
getAnimatedPos, onPersonSelect, onMediaSelect,
|
||||
getAnimatedPos, onPersonSelect, onMediaSelect, onPhotoPlaceholderClick,
|
||||
annotationHandlers,
|
||||
minScale: MIN_SCALE,
|
||||
maxScale: MAX_SCALE,
|
||||
|
||||
@@ -53,6 +53,10 @@ const PersonCard = ({
|
||||
onAvatarUpload,
|
||||
onAvatarDelete,
|
||||
onAvatarCrop,
|
||||
pendingPortraitCrop = null,
|
||||
onPendingPortraitCropDone = null,
|
||||
photoSourceRequest = null,
|
||||
onPhotoSourceRequestDone = null,
|
||||
treeId = null,
|
||||
immichToken = null,
|
||||
onImmichChange,
|
||||
@@ -180,16 +184,19 @@ const PersonCard = ({
|
||||
// Connexion Immich de l'arbre : métadonnées sans clé. Une erreur (rôle périmé, réseau) se
|
||||
// traduit par « non configuré » : la fiche reste utilisable, simplement sans choix de source.
|
||||
// Seul un administrateur de l'arbre voit l'option Immich, comme côté serveur.
|
||||
// Dépend de la présence de onImmichChange, pas de sa valeur : App le recrée à chaque rendu, ce qui
|
||||
// relançait la lecture de la config et refermait le menu des sources juste après son ouverture
|
||||
const canChangeImmich = Boolean(onImmichChange)
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
setImmichConfigured(null)
|
||||
setShowSourceMenu(false)
|
||||
if (!editMode || !isAdmin || !treeId || !onImmichChange || !immichToken) return undefined
|
||||
if (!editMode || !isAdmin || !treeId || !canChangeImmich || !immichToken) return undefined
|
||||
fetchImmichConfig(treeId, immichToken)
|
||||
.then(({ config }) => { if (!cancelled) setImmichConfigured(Boolean(config?.configured)) })
|
||||
.catch(() => { if (!cancelled) setImmichConfigured(false) })
|
||||
return () => { cancelled = true }
|
||||
}, [editMode, isAdmin, treeId, immichToken, onImmichChange])
|
||||
}, [editMode, isAdmin, treeId, immichToken, canChangeImmich])
|
||||
|
||||
useEffect(() => {
|
||||
if (!showSourceMenu) return undefined
|
||||
@@ -250,6 +257,21 @@ const PersonCard = ({
|
||||
const chooseFileSource = () => { setShowSourceMenu(false); avatarInputRef.current?.click() }
|
||||
const chooseImmichSource = () => { setShowSourceMenu(false); setShowImmichPanel(true) }
|
||||
|
||||
// Clic sur « + photo » dans l'arbre : la photo vient d'être envoyée, le recadrage s'ouvre tout de suite
|
||||
useEffect(() => {
|
||||
if (!pendingPortraitCrop || String(pendingPortraitCrop.personId) !== String(person.id)) return
|
||||
setCropState({ src: pendingPortraitCrop.src, mode: 'new', ownsUrl: true })
|
||||
onPendingPortraitCropDone?.()
|
||||
}, [pendingPortraitCrop, person.id, onPendingPortraitCropDone])
|
||||
|
||||
// Clic sur « + photo » dans l'arbre, en modification avec Immich : même menu que le badge, sans clic de plus
|
||||
useEffect(() => {
|
||||
if (!photoSourceRequest || String(photoSourceRequest.personId) !== String(person.id)) return
|
||||
if (immichConfigured === null) return
|
||||
onPhotoSourceRequestDone?.()
|
||||
if (immichUsable) openAvatarPicker()
|
||||
}, [photoSourceRequest, person.id, immichConfigured, immichUsable, onPhotoSourceRequestDone]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Focus search input when relation search opens
|
||||
useEffect(() => {
|
||||
if (activeRelationSearch) {
|
||||
|
||||
@@ -55,3 +55,16 @@
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.pcrop-img { transition: none; }
|
||||
}
|
||||
|
||||
/* Forme du cadre : chaque choix montre sa forme, son nom est dans aria-label et title */
|
||||
.pcrop-shapes { width: min(100%, 300px); margin: 0 auto; }
|
||||
.pcrop-shapes .pz-tab { display: grid; place-items: center; min-height: 40px; padding: 0; color: var(--pz-muted); }
|
||||
.pcrop-shapes .pz-tab.is-active { color: var(--pz-a700, #93402A); }
|
||||
.pcrop-shapes .pz-tab:disabled { cursor: default; opacity: .5; }
|
||||
.pcrop-ico { display: block; border: 1.75px solid currentColor; }
|
||||
.pcrop-ico--round { width: 20px; height: 20px; border-radius: 50%; }
|
||||
.pcrop-ico--square { width: 20px; height: 20px; border-radius: 3px; }
|
||||
/* Polaroïd : la marge du bas plus large que les côtés */
|
||||
.pcrop-ico--polaroid { width: 20px; height: 22px; border-radius: 2px; border-bottom-width: 5px; }
|
||||
.pcrop-ico--portrait { width: 16px; height: 22px; border-radius: 3px; }
|
||||
.pcrop-ico--landscape { width: 26px; height: 16px; border-radius: 3px; }
|
||||
@@ -8,11 +8,13 @@ import {
|
||||
DEFAULT_CROP,
|
||||
clampCrop,
|
||||
cropForSave,
|
||||
cropShape,
|
||||
cropViewport,
|
||||
frameAspect,
|
||||
imagePlacement,
|
||||
normalizeCrop,
|
||||
resolveFrameKind,
|
||||
shapeOfKind,
|
||||
} from '../utils/portraitCrop.js'
|
||||
import './PortraitCropModal.css'
|
||||
|
||||
@@ -23,8 +25,11 @@ const KEY_STEP = 0.04
|
||||
const KEY_STEP_LARGE = 0.16
|
||||
const KEY_ZOOM_STEP = 0.2
|
||||
|
||||
const SHAPE_LABELS = { round: t('Rond'), square: t('Carré'), polaroid: t('Polaroïd'), portrait: t('Vertical'), landscape: t('Horizontal') }
|
||||
|
||||
// Recadrage d'un portrait. Le masque garde la forme du cadre de la personne dans l'arbre ; la photo
|
||||
// glisse dessous. `mode` : 'recrop' (depuis le menu) ou 'new' (juste après le choix d'une photo).
|
||||
// glisse dessous. La forme se choisit aussi ici : sans choix, elle suit la photo ou le tirage de la personne.
|
||||
// `mode` : 'recrop' (depuis le menu) ou 'new' (juste après le choix d'une photo).
|
||||
const PortraitCropModal = ({ src, frameType, name, mode = 'recrop', initialCrop = null, saving = false, error = '', onSave, onClose }) => {
|
||||
const stageRef = useRef(null)
|
||||
const dragRef = useRef(null)
|
||||
@@ -33,11 +38,13 @@ const PortraitCropModal = ({ src, frameType, name, mode = 'recrop', initialCrop
|
||||
const [size, setSize] = useState(null)
|
||||
const [loadFailed, setLoadFailed] = useState(false)
|
||||
const [crop, setCrop] = useState(() => normalizeCrop(initialCrop))
|
||||
const [shape, setShape] = useState(() => cropShape(initialCrop))
|
||||
const [dragging, setDragging] = useState(false)
|
||||
|
||||
const imageRatio = size ? size.w / size.h : 1
|
||||
const frameKind = resolveFrameKind(frameType, imageRatio)
|
||||
const aspect = frameAspect(frameKind, imageRatio)
|
||||
const frameKind = resolveFrameKind(frameType, imageRatio, shape)
|
||||
const aspect = frameAspect(frameKind, imageRatio, shape)
|
||||
const shownShape = shape ?? shapeOfKind(frameKind, imageRatio)
|
||||
const winW = aspect >= 1 ? WINDOW_SIZE : WINDOW_SIZE * aspect
|
||||
const winH = aspect >= 1 ? WINDOW_SIZE / aspect : WINDOW_SIZE
|
||||
|
||||
@@ -159,7 +166,7 @@ const PortraitCropModal = ({ src, frameType, name, mode = 'recrop', initialCrop
|
||||
const setZoom = (zoom) => apply({ ...current, zoom: Number(zoom) })
|
||||
const save = () => {
|
||||
if (!size || saving) return
|
||||
onSave?.(cropForSave(size.w, size.h, aspect, current))
|
||||
onSave?.(cropForSave(size.w, size.h, aspect, current, shape))
|
||||
}
|
||||
|
||||
const isNew = mode === 'new'
|
||||
@@ -208,6 +215,24 @@ const PortraitCropModal = ({ src, frameType, name, mode = 'recrop', initialCrop
|
||||
{!size && !loadFailed && <div className="pcrop-loading"><PzBusy busy busyLabel={t('Chargement de la photo')} /></div>}
|
||||
</div>
|
||||
|
||||
<div className="pz-tabs pcrop-shapes" role="radiogroup" aria-label={t('Forme du cadre')}>
|
||||
{Object.entries(SHAPE_LABELS).map(([value, label]) => (
|
||||
<button
|
||||
key={value}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={shownShape === value}
|
||||
className={`pz-tab ${shownShape === value ? 'is-active' : ''}`}
|
||||
onClick={() => setShape(value)}
|
||||
disabled={!size || saving}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
>
|
||||
<span className={`pcrop-ico pcrop-ico--${value}`} aria-hidden="true" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<p id="pcropHint" className="pz-small pcrop-hint">
|
||||
{t('Glissez la photo, ou utilisez les flèches. Molette, pincement ou curseur pour zoomer.')}
|
||||
</p>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { t } from '../../i18n/index.js'
|
||||
import { getPersonById, getPersonMedias } from '../../data/mockData'
|
||||
import { cropViewport } from '../../utils/portraitCrop.js'
|
||||
import { cropShape, cropViewport, isLandscapeRect, resolveFrameKind } from '../../utils/portraitCrop.js'
|
||||
// Tracés Lucide dessinés sur le canvas : données publiques de @lucide/icons (Map renommé, il masquerait
|
||||
// le Map global utilisé plus bas)
|
||||
import { Map as mapIcon, MapPin as mapPinIcon, Route as routeIcon } from '@lucide/icons'
|
||||
@@ -201,6 +201,8 @@ export function drawCoupleLinks(ctx, coupleBarMeta, posMap, nodeMap, nodeRandomD
|
||||
// useGalaxyInteractions.
|
||||
// ============================================================
|
||||
export const renvoiHitAreas = []
|
||||
// Zones « + photo » : portraits vides, chez le propriétaire (cercle du nœud, rempli au dessin)
|
||||
export const photoPlaceholderHitAreas = []
|
||||
const renvoiPills = []
|
||||
const RENVOI_FONT = '500 11px "DM Sans", system-ui, sans-serif'
|
||||
// Pastilles collées aux personnes : juste sous le couple, juste au-dessus du portrait de l'enfant
|
||||
@@ -450,6 +452,10 @@ function drawPersonNode(ctx, node, pos, nodeProgress, {
|
||||
const { cx, cy } = pos
|
||||
const person = getPersonById(node._data.id) || node._data
|
||||
const rd = nodeRandomData.get(node.id)
|
||||
// Zone « + photo » : seulement là où le cadre invite à poser une photo (même condition que le dessin)
|
||||
if (photoHint && !person.photo && nodeProgress >= 0.5) {
|
||||
photoPlaceholderHitAreas.push({ personId: node._data.id, cx, cy, r: nodeRadius(node) })
|
||||
}
|
||||
const img = person.photo ? imageCache.get(person.photo) : null
|
||||
const frameType = resolveFrameType(person, img)
|
||||
const frameRot = rd?.frameRotation || 0
|
||||
@@ -891,26 +897,12 @@ function drawMediaContent(ctx, media, ms, imageCache) {
|
||||
// ============================================================
|
||||
// Dessiner le cadre photo (polaroid, rect, round)
|
||||
// ============================================================
|
||||
// Forme choisie au recadrage d'abord ; sinon une photo très large ou très haute impose la sienne, et une photo
|
||||
// carrée ou presque garde la forme tirée au hasard pour la personne (pickFrameType), pour que l'arbre ne soit
|
||||
// pas uniforme. Même règle que la fenêtre de recadrage (portraitCrop.js).
|
||||
function resolveFrameType(person, img) {
|
||||
const fallback = person.frameType || 'round'
|
||||
|
||||
if (!img || !img.naturalWidth || !img.naturalHeight) {
|
||||
return fallback
|
||||
}
|
||||
|
||||
const ratio = img.naturalWidth / img.naturalHeight
|
||||
|
||||
if (ratio >= 1.28) {
|
||||
return 'rect'
|
||||
}
|
||||
|
||||
if (ratio <= 0.78) {
|
||||
return 'polaroid'
|
||||
}
|
||||
|
||||
// Photo carrée ou presque : chaque personne garde sa forme tirée au hasard
|
||||
// (person.frameType, voir pickFrameType), pour que l'arbre ne soit pas uniforme
|
||||
return fallback
|
||||
const ratio = img?.naturalWidth && img?.naturalHeight ? img.naturalWidth / img.naturalHeight : 1
|
||||
return resolveFrameKind(person.frameType || 'round', ratio, cropShape(person.avatarCrop))
|
||||
}
|
||||
|
||||
function drawFrame(ctx, frameType, person, img, hint = 0) {
|
||||
@@ -952,8 +944,8 @@ function drawFrame(ctx, frameType, person, img, hint = 0) {
|
||||
const ratio = img?.naturalWidth && img?.naturalHeight
|
||||
? img.naturalWidth / img.naturalHeight
|
||||
: 1
|
||||
// Photo carrée : cadre vertical, qui garde le visage entier
|
||||
const isLandscape = ratio > 1.05
|
||||
// Couché ou debout selon la forme choisie, sinon selon la photo (carrée : debout, le visage reste entier)
|
||||
const isLandscape = isLandscapeRect(ratio, cropShape(person.avatarCrop))
|
||||
const rw = isLandscape ? PERSON_R + 12 : PERSON_R + 2
|
||||
const rh = isLandscape ? PERSON_R - 8 : PERSON_R + 6
|
||||
const pad = 3
|
||||
@@ -1043,6 +1035,7 @@ function drawImageCover(ctx, img, x, y, w, h, crop = null) {
|
||||
// ============================================================
|
||||
export function drawNodes(ctx, layoutData, posMap, entrance, entranceActive, elapsed, renderState) {
|
||||
const view = renderState.view || null
|
||||
photoPlaceholderHitAreas.length = 0
|
||||
layoutData.children.forEach(node => {
|
||||
const pos = posMap.get(node.id)
|
||||
if (!pos) return
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { useRef, useCallback } from 'react'
|
||||
import { getPersonMedias } from '../../data/mockData'
|
||||
import { MAX_ORBIT_MEDIAS, ORBIT_MEDIA_SIZE } from './constants'
|
||||
import { nodeRadius, renvoiHitAreas } from './renderers'
|
||||
import { nodeRadius, renvoiHitAreas, photoPlaceholderHitAreas } from './renderers'
|
||||
|
||||
const hitRenvoi = (x, y) => renvoiHitAreas.find(a => x >= a.x0 && x <= a.x1 && y >= a.y0 && y <= a.y1)
|
||||
const hitPhotoPlaceholder = (x, y) => photoPlaceholderHitAreas.find(a => Math.hypot(x - a.cx, y - a.cy) < a.r)
|
||||
import { getEntranceProgress } from './utils'
|
||||
|
||||
const CURSOR_GRAB = 'default'
|
||||
@@ -21,7 +22,7 @@ export function useGalaxyInteractions({
|
||||
canvasRef, transformRef, targetTransformRef,
|
||||
layoutDataRef, nodeRandomDataRef, entranceRef,
|
||||
hoveredNodeIdRef, hoveredMediaKeyRef, mouseWorldPosRef,
|
||||
getAnimatedPos, onPersonSelect, onMediaSelect,
|
||||
getAnimatedPos, onPersonSelect, onMediaSelect, onPhotoPlaceholderClick = null,
|
||||
annotationHandlers,
|
||||
minScale = 0.2,
|
||||
maxScale = 4,
|
||||
@@ -138,6 +139,7 @@ export function useGalaxyInteractions({
|
||||
}
|
||||
}
|
||||
if (!isOverClickable && hitRenvoi(mouseWorldPosRef.current.x, mouseWorldPosRef.current.y)) isOverClickable = true
|
||||
if (!isOverClickable && hitPhotoPlaceholder(mouseWorldPosRef.current.x, mouseWorldPosRef.current.y)) isOverClickable = true
|
||||
hoveredNodeIdRef.current = newHoveredNode
|
||||
hoveredMediaKeyRef.current = newHoveredMedia
|
||||
|
||||
@@ -262,6 +264,13 @@ export function useGalaxyInteractions({
|
||||
}
|
||||
}
|
||||
|
||||
// « + photo » : le clic lance directement la photo (la fiche s'ouvre aussi, côté App)
|
||||
const photoZone = hitPhotoPlaceholder(clickX, clickY)
|
||||
if (photoZone && onPhotoPlaceholderClick) {
|
||||
onPhotoPlaceholderClick(photoZone.personId)
|
||||
return
|
||||
}
|
||||
|
||||
for (const node of layoutData.children) {
|
||||
if (node._type !== 'person') continue
|
||||
if (ent && !ent.finished) {
|
||||
@@ -286,7 +295,7 @@ export function useGalaxyInteractions({
|
||||
y: rect2.height / 2 - renvoi.targetY * scale,
|
||||
}
|
||||
}
|
||||
}, [canvasRef, transformRef, targetTransformRef, layoutDataRef, nodeRandomDataRef, entranceRef, getAnimatedPos, onPersonSelect, onMediaSelect, annotationHandlers])
|
||||
}, [canvasRef, transformRef, targetTransformRef, layoutDataRef, nodeRandomDataRef, entranceRef, getAnimatedPos, onPersonSelect, onMediaSelect, onPhotoPlaceholderClick, annotationHandlers])
|
||||
|
||||
return {
|
||||
isDragging, isZooming, zoomTimeoutRef, hasDragged,
|
||||
|
||||
@@ -45,3 +45,5 @@
|
||||
.navm-check { color: var(--pz-a700); }
|
||||
.navm-current { cursor: default; }
|
||||
.navm-current:hover { background: transparent !important; }
|
||||
/* Arbre en cours : désactivé pour le clavier et le clic, mais texte à sa couleur normale (pas la mise en retrait de .navm-item:disabled) */
|
||||
.navm-item.navm-current:disabled { opacity: 1; cursor: default; color: var(--pz-ink); }
|
||||
@@ -86,13 +86,16 @@ function AvatarMenu({
|
||||
<NavMenuSep />
|
||||
<NavMenuGroup label={t('Mes arbres')}>
|
||||
{trees.length > 1 ? trees.map((tree) => {
|
||||
// L'arbre en cours : affiché comme courant (coche terracotta), non cliquable, pas grisé
|
||||
const isActive = String(tree.id) === String(activeTreeId)
|
||||
return (
|
||||
<NavMenuItem
|
||||
key={tree.id}
|
||||
icon={<span className="navm-tree-mono" aria-hidden="true">{(tree.name || '?').trim().charAt(0).toUpperCase()}</span>}
|
||||
label={tree.name}
|
||||
onSelect={() => { onClose(); onSelectTree?.(tree.id) }}
|
||||
onSelect={isActive ? undefined : () => { onClose(); onSelectTree?.(tree.id) }}
|
||||
disabled={isActive}
|
||||
className={isActive ? 'navm-current' : undefined}
|
||||
right={isActive ? <Check size={16} aria-hidden="true" className="navm-check" /> : null}
|
||||
/>
|
||||
)
|
||||
@@ -102,6 +105,7 @@ function AvatarMenu({
|
||||
label={currentTreeName}
|
||||
disabled
|
||||
className="navm-current"
|
||||
right={<Check size={16} aria-hidden="true" className="navm-check" />}
|
||||
/>
|
||||
)}
|
||||
<NavMenuItem icon={<Plus {...ICON} />} label={t('Créer un nouvel arbre')} onSelect={() => { onClose(); onCreateTree?.() }} />
|
||||
|
||||
@@ -418,6 +418,12 @@ export default {
|
||||
'Il faut au moins un nom si le prénom est inconnu.': 'A last name is required when the first name is unknown.',
|
||||
// Recadrage du portrait (PortraitCropModal, menu du badge, App)
|
||||
'Recadrer la photo': 'Crop photo',
|
||||
'Forme du cadre': 'Frame shape',
|
||||
'Rond': 'Round',
|
||||
'Carré': 'Square',
|
||||
'Polaroïd': 'Polaroid',
|
||||
'Vertical': 'Vertical',
|
||||
'Horizontal': 'Horizontal',
|
||||
'Recadrer': 'Crop',
|
||||
'Options du portrait': 'Portrait options',
|
||||
'Zone de recadrage': 'Crop area',
|
||||
|
||||
@@ -7,19 +7,37 @@ export const DEFAULT_CROP = { x: 0.5, y: 0.5, zoom: 1 }
|
||||
|
||||
const clamp = (value, min, max) => Math.min(max, Math.max(min, value))
|
||||
|
||||
// Formes qu'on choisit au recadrage, gardées dans le cadrage (crop.shape). Sans choix, la forme suit la photo
|
||||
// (très large ou très haute) ou le cadre tiré au hasard pour la personne.
|
||||
export const FRAME_SHAPES = ['round', 'square', 'polaroid', 'portrait', 'landscape']
|
||||
export const cropShape = (crop) => (FRAME_SHAPES.includes(crop?.shape) ? crop.shape : null)
|
||||
|
||||
// Forme du cadre dans le canevas : même règle que resolveFrameType et drawFrame (renderers.js).
|
||||
// Une photo très large ou très haute change la forme ; sinon le cadre tiré pour la personne (frameType) reste.
|
||||
export function resolveFrameKind(frameType, imageRatio) {
|
||||
// La forme choisie l'emporte ; sinon une photo très large ou très haute change la forme, et à défaut
|
||||
// le cadre tiré pour la personne (frameType) reste.
|
||||
export function resolveFrameKind(frameType, imageRatio, shape = null) {
|
||||
if (shape) return shape === 'portrait' || shape === 'landscape' ? 'rect' : shape
|
||||
if (imageRatio >= 1.28) return 'rect'
|
||||
if (imageRatio <= 0.78) return 'polaroid'
|
||||
return frameType || 'round'
|
||||
}
|
||||
|
||||
// Cadre rectangle : couché si on l'a choisi, sinon selon la photo (carrée : debout, le visage reste entier)
|
||||
export function isLandscapeRect(imageRatio, shape = null) {
|
||||
return shape ? shape === 'landscape' : imageRatio > 1.05
|
||||
}
|
||||
|
||||
// Nom de la forme affichée, pour le sélecteur
|
||||
export function shapeOfKind(frameKind, imageRatio) {
|
||||
if (frameKind !== 'rect') return frameKind
|
||||
return isLandscapeRect(imageRatio) ? 'landscape' : 'portrait'
|
||||
}
|
||||
|
||||
// Rapport largeur / hauteur de la zone visible, comme drawFrame le dessine.
|
||||
export function frameAspect(frameKind, imageRatio) {
|
||||
export function frameAspect(frameKind, imageRatio, shape = null) {
|
||||
if (frameKind === 'rect') {
|
||||
// Paysage : 80 x 40 ; portrait : 60 x 68 (renderers.js, drawFrame)
|
||||
return imageRatio > 1.05 ? 2 : 60 / 68
|
||||
return isLandscapeRect(imageRatio, shape) ? 2 : 60 / 68
|
||||
}
|
||||
// round, polaroid et square : la zone photo est carrée
|
||||
return 1
|
||||
@@ -32,7 +50,8 @@ export function normalizeCrop(crop) {
|
||||
const y = Number(crop.y)
|
||||
const zoom = Number(crop.zoom)
|
||||
if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(zoom)) return DEFAULT_CROP
|
||||
return { x: clamp(x, 0, 1), y: clamp(y, 0, 1), zoom: clamp(zoom, 1, CROP_MAX_ZOOM) }
|
||||
const shape = cropShape(crop)
|
||||
return { x: clamp(x, 0, 1), y: clamp(y, 0, 1), zoom: clamp(zoom, 1, CROP_MAX_ZOOM), ...(shape ? { shape } : {}) }
|
||||
}
|
||||
|
||||
// Zone de l'image visible dans le cadre, en pixels de l'image. Le centre est borné pour qu'il n'y ait jamais
|
||||
@@ -77,11 +96,13 @@ export function imagePlacement(imageW, imageH, aspect, crop, windowW = 1, window
|
||||
}
|
||||
}
|
||||
|
||||
// Ce qu'il faut à l'enregistrement : null pour le cadrage par défaut, sinon le cadrage borné.
|
||||
export function cropForSave(imageW, imageH, aspect, crop) {
|
||||
// Ce qu'il faut à l'enregistrement : null pour le cadrage par défaut sans forme choisie, sinon le cadrage
|
||||
// borné, avec la forme quand on l'a choisie.
|
||||
export function cropForSave(imageW, imageH, aspect, crop, shape = null) {
|
||||
const c = clampCrop(imageW, imageH, aspect, crop)
|
||||
const round = (value) => Math.round(value * 10000) / 10000
|
||||
const normalized = { x: round(c.x), y: round(c.y), zoom: round(c.zoom) }
|
||||
if (shape) return { ...normalized, shape }
|
||||
if (normalized.x === 0.5 && normalized.y === 0.5 && normalized.zoom === 1) return null
|
||||
return normalized
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
imagePlacement,
|
||||
normalizeCrop,
|
||||
resolveFrameKind,
|
||||
shapeOfKind,
|
||||
} from './portraitCrop.js'
|
||||
|
||||
// Le cadrage visible ne sort jamais de la photo : aucun vide dans le cadre
|
||||
@@ -86,3 +87,29 @@ describe('portraitCrop', () => {
|
||||
expect(frameAspect('rect', 1)).toBeCloseTo(60 / 68)
|
||||
})
|
||||
})
|
||||
|
||||
describe('forme choisie au recadrage', () => {
|
||||
it('l emporte sur le format de la photo et sur le tirage de la personne', () => {
|
||||
// Photo très large : cadre couché par défaut, rond si on le choisit
|
||||
expect(resolveFrameKind('polaroid', 1.6)).toBe('rect')
|
||||
expect(resolveFrameKind('polaroid', 1.6, 'round')).toBe('round')
|
||||
expect(frameAspect(resolveFrameKind('polaroid', 1.6, 'round'), 1.6, 'round')).toBe(1)
|
||||
// Vertical choisi sur une photo couchée : la zone visible est debout
|
||||
expect(resolveFrameKind('round', 1.6, 'portrait')).toBe('rect')
|
||||
expect(frameAspect('rect', 1.6, 'portrait')).toBeCloseTo(60 / 68)
|
||||
expect(frameAspect('rect', 0.7, 'landscape')).toBe(2)
|
||||
})
|
||||
|
||||
it('le sélecteur montre la forme en cours quand rien n est choisi', () => {
|
||||
expect(shapeOfKind('rect', 1.6)).toBe('landscape')
|
||||
expect(shapeOfKind('rect', 1)).toBe('portrait')
|
||||
expect(shapeOfKind('polaroid', 0.7)).toBe('polaroid')
|
||||
})
|
||||
|
||||
it('est gardée à la lecture et à l enregistrement, même sans recadrage', () => {
|
||||
expect(normalizeCrop({ x: 0.2, y: 0.3, zoom: 2, shape: 'square' })).toEqual({ x: 0.2, y: 0.3, zoom: 2, shape: 'square' })
|
||||
expect(normalizeCrop({ x: 0.2, y: 0.3, zoom: 2, shape: 'hexagone' })).toEqual({ x: 0.2, y: 0.3, zoom: 2 })
|
||||
expect(cropForSave(400, 400, 1, DEFAULT_CROP)).toBeNull()
|
||||
expect(cropForSave(400, 400, 1, DEFAULT_CROP, 'round')).toEqual({ x: 0.5, y: 0.5, zoom: 1, shape: 'round' })
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user