mirror of
https://github.com/IliesAllali/parenthese.git
synced 2026-11-17 00:33:28 +00:00
Ajout de la fonctionnalité drag and drop
This commit is contained in:
1 parent
3a5fa42670
commit
43441f31e1
22 files changed
+386
-18
No files matched your search
+1
-1
@@ -8,7 +8,7 @@ Site et démo : [parenthese.io](https://parenthese.io) · [English version](READ
|
||||
|
||||
## Ce que fait l'application
|
||||
|
||||
- Un arbre par famille : personnes, unions, liens parent-enfant, mise en page automatique.
|
||||
- Un arbre par famille : personnes, unions, liens parent-enfant, mise en page automatique réagençable par glisser-déposer en mode édition.
|
||||
- Des médias sur chaque personne : photos, vidéos (fichier ou lien YouTube), enregistrements audio pour garder une voix, documents, traces GPS.
|
||||
- Des annotations libres sur l'arbre : dessins, stickers, textes, photos posées où l'on veut.
|
||||
- Un partage par lien : chaque arbre a une adresse `/arbre/<nom>` protégée par un mot de passe de partage, qui permet de regarder et de proposer des ajouts.
|
||||
|
||||
@@ -13,7 +13,7 @@ Website: [parenthese.io/en](https://parenthese.io/en/) · Demo, no account neede
|
||||
|
||||
## What it does
|
||||
|
||||
- One tree per family: people, couples, parent-child links, laid out automatically.
|
||||
- One tree per family: people, couples, parent-child links, laid out automatically and rearrangeable by dragging people in edit mode.
|
||||
- Memories on each person: photos, videos (a file or a YouTube link), audio recordings to keep a voice, documents, GPS tracks.
|
||||
- Free annotations on the tree: drawings, stickers, text, photos placed anywhere.
|
||||
- Sharing by link: each tree has an address `/arbre/<name>` protected by a sharing password. With it, relatives can look around and suggest additions.
|
||||
|
||||
@@ -228,6 +228,14 @@ components:
|
||||
deathDate:
|
||||
type: string
|
||||
nullable: true
|
||||
layoutX:
|
||||
type: number
|
||||
nullable: true
|
||||
description: Manual tree-layout X coordinate for the person.
|
||||
layoutY:
|
||||
type: number
|
||||
nullable: true
|
||||
description: Manual tree-layout Y coordinate for the person.
|
||||
sex:
|
||||
type: string
|
||||
nullable: true
|
||||
@@ -345,6 +353,12 @@ components:
|
||||
deathDate:
|
||||
type: string
|
||||
nullable: true
|
||||
layoutX:
|
||||
type: number
|
||||
nullable: true
|
||||
layoutY:
|
||||
type: number
|
||||
nullable: true
|
||||
sex:
|
||||
type: string
|
||||
nullable: true
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE "persons"
|
||||
ADD COLUMN "layoutX" DOUBLE PRECISION,
|
||||
ADD COLUMN "layoutY" DOUBLE PRECISION;
|
||||
@@ -198,6 +198,8 @@ model Person {
|
||||
birthName String?
|
||||
birthDate DateTime?
|
||||
deathDate DateTime?
|
||||
layoutX Float?
|
||||
layoutY Float?
|
||||
birthPlace String?
|
||||
profession String?
|
||||
region String?
|
||||
|
||||
@@ -86,6 +86,8 @@ const personUpdateSchema = z
|
||||
birthName: z.string().max(120).optional().nullable(),
|
||||
birthDate: z.string().regex(isoDateRegex).optional().nullable(),
|
||||
deathDate: z.string().regex(isoDateRegex).optional().nullable(),
|
||||
layoutX: z.number().finite().optional().nullable(),
|
||||
layoutY: z.number().finite().optional().nullable(),
|
||||
birthPlace: z.string().max(200).optional().nullable(),
|
||||
profession: z.string().max(200).optional().nullable(),
|
||||
region: z.string().max(120).optional().nullable(),
|
||||
@@ -402,6 +404,8 @@ async function applyContributionChange(
|
||||
birthName: parsed.data.birthName !== undefined ? toTrimmedStringOrNull(parsed.data.birthName) : undefined,
|
||||
birthDate: parsed.data.birthDate !== undefined ? toDateOrNull(parsed.data.birthDate) : undefined,
|
||||
deathDate: parsed.data.deathDate !== undefined ? toDateOrNull(parsed.data.deathDate) : undefined,
|
||||
layoutX: parsed.data.layoutX,
|
||||
layoutY: parsed.data.layoutY,
|
||||
birthPlace: parsed.data.birthPlace !== undefined ? toTrimmedStringOrNull(parsed.data.birthPlace) : undefined,
|
||||
profession: parsed.data.profession !== undefined ? toTrimmedStringOrNull(parsed.data.profession) : undefined,
|
||||
region: parsed.data.region !== undefined ? toTrimmedStringOrNull(parsed.data.region) : undefined,
|
||||
@@ -794,6 +798,8 @@ async function snapshotEntity(
|
||||
birthName: true,
|
||||
birthDate: true,
|
||||
deathDate: true,
|
||||
layoutX: true,
|
||||
layoutY: true,
|
||||
birthPlace: true,
|
||||
profession: true,
|
||||
region: true,
|
||||
|
||||
@@ -101,6 +101,8 @@ const patchPersonSchema = z
|
||||
birthName: z.string().max(120).optional().nullable(),
|
||||
birthDate: z.string().regex(isoDateRegex).optional().nullable(),
|
||||
deathDate: z.string().regex(isoDateRegex).optional().nullable(),
|
||||
layoutX: z.number().finite().optional().nullable(),
|
||||
layoutY: z.number().finite().optional().nullable(),
|
||||
birthPlace: z.string().max(200).optional().nullable(),
|
||||
profession: z.string().max(200).optional().nullable(),
|
||||
region: z.string().max(120).optional().nullable(),
|
||||
@@ -1302,6 +1304,8 @@ export const treeRoutes: FastifyPluginAsync = async (app) => {
|
||||
birthName?: string | null
|
||||
birthDate?: Date | null
|
||||
deathDate?: Date | null
|
||||
layoutX?: number | null
|
||||
layoutY?: number | null
|
||||
birthPlace?: string | null
|
||||
profession?: string | null
|
||||
region?: string | null
|
||||
@@ -1331,6 +1335,14 @@ export const treeRoutes: FastifyPluginAsync = async (app) => {
|
||||
data.deathDate = toDateOrNull(payload.data.deathDate)
|
||||
}
|
||||
|
||||
if (payload.data.layoutX !== undefined) {
|
||||
data.layoutX = payload.data.layoutX
|
||||
}
|
||||
|
||||
if (payload.data.layoutY !== undefined) {
|
||||
data.layoutY = payload.data.layoutY
|
||||
}
|
||||
|
||||
if (payload.data.birthPlace !== undefined) {
|
||||
data.birthPlace = toTrimmedStringOrNull(payload.data.birthPlace)
|
||||
}
|
||||
|
||||
@@ -10,6 +10,8 @@ export type GraphPayload = {
|
||||
birthName: string | null
|
||||
birthDate: string | null
|
||||
deathDate: string | null
|
||||
layoutX: number | null
|
||||
layoutY: number | null
|
||||
birthPlace: string | null
|
||||
profession: string | null
|
||||
region: string | null
|
||||
@@ -83,6 +85,8 @@ export function buildGraphPayload(
|
||||
birthName: person.birthName,
|
||||
birthDate: formatDate(person.birthDate),
|
||||
deathDate: formatDate(person.deathDate),
|
||||
layoutX: person.layoutX ?? null,
|
||||
layoutY: person.layoutY ?? null,
|
||||
birthPlace: person.birthPlace,
|
||||
profession: person.profession,
|
||||
region: person.region,
|
||||
|
||||
@@ -456,11 +456,15 @@ describe('API security and authz', () => {
|
||||
payload: {
|
||||
firstName: 'Alice',
|
||||
notes: 'Mise a jour',
|
||||
layoutX: 321.5,
|
||||
layoutY: 654.25,
|
||||
},
|
||||
})
|
||||
|
||||
expect(patchResponse.statusCode).toBe(200)
|
||||
expect(prismaMock.person.updateMany).toHaveBeenCalled()
|
||||
expect(prismaMock.person.updateMany).toHaveBeenCalledWith(expect.objectContaining({
|
||||
data: expect.objectContaining({ layoutX: 321.5, layoutY: 654.25 }),
|
||||
}))
|
||||
|
||||
prismaMock.union.updateMany.mockResolvedValueOnce({ count: 2 })
|
||||
prismaMock.parentChildLink.updateMany.mockResolvedValueOnce({ count: 3 })
|
||||
|
||||
@@ -545,7 +545,7 @@ describe('Journey 4 — Admin reviews a contribution session', () => {
|
||||
action: 'update',
|
||||
entityId: 'person-1',
|
||||
beforeJson: { firstName: 'Pierre' },
|
||||
afterJson: { notes: 'Surnomme Pierrot' },
|
||||
afterJson: { notes: 'Surnomme Pierrot', layoutX: 234.5, layoutY: 678.25 },
|
||||
conflictState: 'none',
|
||||
},
|
||||
],
|
||||
@@ -581,7 +581,9 @@ describe('Journey 4 — Admin reviews a contribution session', () => {
|
||||
|
||||
// Both changes should be applied
|
||||
expect(prismaMock.person.create).toHaveBeenCalled()
|
||||
expect(prismaMock.person.updateMany).toHaveBeenCalled()
|
||||
expect(prismaMock.person.updateMany).toHaveBeenCalledWith(expect.objectContaining({
|
||||
data: expect.objectContaining({ layoutX: 234.5, layoutY: 678.25 }),
|
||||
}))
|
||||
|
||||
// Audit log for review
|
||||
expect(prismaMock.auditLog.create).toHaveBeenCalledWith(
|
||||
|
||||
@@ -15,6 +15,8 @@ describe('buildGraphPayload', () => {
|
||||
birthName: 'Durand',
|
||||
birthDate: new Date('1994-06-02T00:00:00.000Z'),
|
||||
deathDate: null,
|
||||
layoutX: 432.5,
|
||||
layoutY: -19.25,
|
||||
sex: null,
|
||||
notes: null,
|
||||
avatarPath: 't-1/p-2/avatar.jpg',
|
||||
@@ -96,6 +98,8 @@ describe('buildGraphPayload', () => {
|
||||
expect(graph.persons[0].id).toBe('p-2')
|
||||
expect(graph.persons[0].birthDate).toBe('1994-06-02')
|
||||
expect(graph.persons[0].birthName).toBe('Durand')
|
||||
expect(graph.persons[0].layoutX).toBe(432.5)
|
||||
expect(graph.persons[0].layoutY).toBe(-19.25)
|
||||
expect(graph.persons[0].avatarUrlPath).toBe('/trees/t-1/persons/p-2/avatar')
|
||||
expect(graph.persons[1].avatarUrlPath).toBeNull()
|
||||
expect(graph.unions[0].id).toBe('u-1')
|
||||
|
||||
+29
-2
@@ -283,6 +283,8 @@ function buildContributionChangesFromDraft(draft = {}) {
|
||||
if (Object.prototype.hasOwnProperty.call(source, 'region')) after.region = (source.region || '').trim() || null
|
||||
if (Object.prototype.hasOwnProperty.call(source, 'nationality')) after.nationality = (source.nationality || '').trim() || null
|
||||
if (Object.prototype.hasOwnProperty.call(source, 'note')) after.notes = source.note || null
|
||||
if (Object.prototype.hasOwnProperty.call(source, 'layoutX')) after.layoutX = source.layoutX
|
||||
if (Object.prototype.hasOwnProperty.call(source, 'layoutY')) after.layoutY = source.layoutY
|
||||
if (Object.prototype.hasOwnProperty.call(source, 'isAlive') && source.isAlive === true) after.deathDate = null
|
||||
|
||||
if (Object.keys(after).length > 0) {
|
||||
@@ -625,6 +627,28 @@ function App() {
|
||||
treeId: tree.treeContext.treeId,
|
||||
canEdit: canEditInCurrentMode,
|
||||
})
|
||||
const manualPositionOverrides = useMemo(() => {
|
||||
if (!editMode.hasDraft) return {}
|
||||
const positions = {}
|
||||
for (const [personId, changes] of Object.entries(editMode.restoreDraft().modifiedPersons || {})) {
|
||||
if (Number.isFinite(changes?.layoutX) && Number.isFinite(changes?.layoutY)) {
|
||||
positions[String(personId)] = { layoutX: changes.layoutX, layoutY: changes.layoutY }
|
||||
}
|
||||
}
|
||||
return positions
|
||||
}, [editMode.hasDraft, editMode.restoreDraft])
|
||||
const handlePersonPositionChange = useCallback((personId, position) => {
|
||||
const draft = editMode.restoreDraft()
|
||||
editMode.updateDraft({
|
||||
modifiedPersons: {
|
||||
...(draft.modifiedPersons || {}),
|
||||
[String(personId)]: {
|
||||
...(draft.modifiedPersons?.[String(personId)] || {}),
|
||||
...position,
|
||||
},
|
||||
},
|
||||
})
|
||||
}, [editMode.restoreDraft, editMode.updateDraft])
|
||||
|
||||
const localEntityCounterRef = useRef(0)
|
||||
const makeLocalId = useCallback((prefix) => {
|
||||
@@ -1192,6 +1216,8 @@ function App() {
|
||||
if (Object.prototype.hasOwnProperty.call(rawChanges, 'nationality')) payload.nationality = (rawChanges.nationality || '').trim() || null
|
||||
if (Object.prototype.hasOwnProperty.call(rawChanges, 'isAlive') && rawChanges.isAlive === true) payload.deathDate = null
|
||||
if (Object.prototype.hasOwnProperty.call(rawChanges, 'note')) payload.notes = rawChanges.note || null
|
||||
if (Object.prototype.hasOwnProperty.call(rawChanges, 'layoutX')) payload.layoutX = rawChanges.layoutX
|
||||
if (Object.prototype.hasOwnProperty.call(rawChanges, 'layoutY')) payload.layoutY = rawChanges.layoutY
|
||||
|
||||
if (Object.keys(payload).length > 0) {
|
||||
try {
|
||||
@@ -2826,6 +2852,9 @@ function App() {
|
||||
<Galaxy
|
||||
onPersonSelect={handlePersonSelect}
|
||||
onMediaSelect={handleMediaSelectFresh}
|
||||
onPersonPositionChange={handlePersonPositionChange}
|
||||
editModeActive={editMode.isActive}
|
||||
manualPositionOverrides={manualPositionOverrides}
|
||||
selectedPersonId={tree.selectedPerson?.id || null}
|
||||
searchHighlightIds={search.matchedPersonIds}
|
||||
graphRevision={tree.graphRevision}
|
||||
@@ -2968,5 +2997,3 @@ function App() {
|
||||
export default App
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { memo, useEffect, useImperativeHandle, useRef, useState, useCallback } from 'react'
|
||||
import { getPersonMedias, getParents, getChildren, getPersonUnions } from '../data/mockData'
|
||||
import { getPersonById, getPersonMedias, getParents, getChildren, getPersonUnions } from '../data/mockData'
|
||||
import { PERSON_R, FLOAT_SPEED, FLOAT_AMPLITUDE, REPULSION_RADIUS, REPULSION_STRENGTH, MAX_ORBIT_MEDIAS, ENTRANCE_GEN_DELAY, ENTRANCE_NODE_DURATION, ENTRANCE_NODE_STAGGER, ENTRANCE_MAX_GEN_SPAN, ENTRANCE_MAX_NODE_SPAN, ENTRANCE_LINE_DELAY, ENTRANCE_LINE_DURATION, ENTRANCE_ORBIT_DELAY, ENTRANCE_ORBIT_DURATION, ENTRANCE_ORBIT_STAGGER } from './galaxy/constants'
|
||||
import { easeOutCubic } from './galaxy/utils'
|
||||
import { computeLayout, generateNodeRandomData, coupleBarMeta } from './galaxy/elkLayout'
|
||||
@@ -12,6 +12,11 @@ import { drawBackground, drawCoupleLinks, drawFiliations, drawAnnotations, drawP
|
||||
import { annotations as annotationData } from '../data/mockData'
|
||||
import { useImageCache } from './galaxy/useImageCache'
|
||||
import { useGalaxyInteractions } from './galaxy/useGalaxyInteractions'
|
||||
import {
|
||||
applyManualPersonPositions,
|
||||
captureAutomaticPersonPositions,
|
||||
positionUnionJunctions,
|
||||
} from './galaxy/layoutPositions'
|
||||
import './Galaxy.css'
|
||||
|
||||
// Assez bas pour cadrer un grand arbre entier à l'ouverture
|
||||
@@ -29,7 +34,7 @@ const MAX_SCALE = 3.2
|
||||
const FOCUS_MIN_READABLE_SCALE = 0.5
|
||||
const FOCUS_SCALE = 0.95
|
||||
|
||||
const Galaxy = ({ onPersonSelect, onMediaSelect, selectedPersonId, searchHighlightIds = [], graphRevision = 0, annotationHandlers = null, transformReadRef = null, zoomApiRef = null, focusPersonId = null, assetRevision = 0, photoHint = false }) => {
|
||||
const Galaxy = ({ onPersonSelect, onMediaSelect, onPersonPositionChange, editModeActive = false, manualPositionOverrides = {}, selectedPersonId, searchHighlightIds = [], graphRevision = 0, annotationHandlers = null, transformReadRef = null, zoomApiRef = null, focusPersonId = null, assetRevision = 0, photoHint = false }) => {
|
||||
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)
|
||||
@@ -38,7 +43,10 @@ const Galaxy = ({ onPersonSelect, onMediaSelect, selectedPersonId, searchHighlig
|
||||
// Propriétaire : un portrait vide survolé montre « + photo »
|
||||
const photoHintRef = useRef(photoHint)
|
||||
useEffect(() => { photoHintRef.current = photoHint }, [photoHint])
|
||||
const manualPositionOverridesRef = useRef(manualPositionOverrides)
|
||||
useEffect(() => { manualPositionOverridesRef.current = manualPositionOverrides }, [manualPositionOverrides])
|
||||
const layoutDataRef = useRef(null)
|
||||
const automaticPersonPositionsRef = useRef(new Map())
|
||||
const [layoutReady, setLayoutReady] = useState(false)
|
||||
const transformRef = useRef({ x: 0, y: 0, scale: 1 })
|
||||
|
||||
@@ -84,6 +92,7 @@ const Galaxy = ({ onPersonSelect, onMediaSelect, selectedPersonId, searchHighlig
|
||||
const getAnimatedPos = useCallback((node, time) => {
|
||||
const baseCx = node.x + node.width / 2
|
||||
const baseCy = node.y + node.height / 2
|
||||
if (node._manualPosition) return { cx: baseCx, cy: baseCy }
|
||||
const rd = nodeRandomDataRef.current.get(node.id)
|
||||
if (!rd) return { cx: baseCx, cy: baseCy }
|
||||
|
||||
@@ -117,6 +126,7 @@ const Galaxy = ({ onPersonSelect, onMediaSelect, selectedPersonId, searchHighlig
|
||||
layoutDataRef, nodeRandomDataRef, entranceRef,
|
||||
hoveredNodeIdRef: hoveredNodeId, hoveredMediaKeyRef: hoveredMediaKey, mouseWorldPosRef: mouseWorldPos,
|
||||
getAnimatedPos, onPersonSelect, onMediaSelect,
|
||||
onPersonPositionChange, editModeActive,
|
||||
annotationHandlers,
|
||||
minScale: MIN_SCALE,
|
||||
maxScale: MAX_SCALE,
|
||||
@@ -201,6 +211,12 @@ const Galaxy = ({ onPersonSelect, onMediaSelect, selectedPersonId, searchHighlig
|
||||
// Layout
|
||||
useEffect(() => {
|
||||
const result = USE_BLOCK_LAYOUT ? computeBlockLayout() : computeLayout()
|
||||
automaticPersonPositionsRef.current = captureAutomaticPersonPositions(result)
|
||||
applyManualPersonPositions(result, {
|
||||
draftPositions: manualPositionOverridesRef.current,
|
||||
getPersonById,
|
||||
automaticPositions: automaticPersonPositionsRef.current,
|
||||
})
|
||||
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas) return
|
||||
@@ -330,6 +346,15 @@ const Galaxy = ({ onPersonSelect, onMediaSelect, selectedPersonId, searchHighlig
|
||||
setLayoutReady(true)
|
||||
}, [graphRevision])
|
||||
|
||||
useEffect(() => {
|
||||
applyManualPersonPositions(layoutDataRef.current, {
|
||||
draftPositions: manualPositionOverrides,
|
||||
getPersonById,
|
||||
automaticPositions: automaticPersonPositionsRef.current,
|
||||
})
|
||||
needsRedrawRef.current = true
|
||||
}, [graphRevision, manualPositionOverrides])
|
||||
|
||||
// Sync selectedPersonId
|
||||
useEffect(() => {
|
||||
selectedPersonIdRef.current = selectedPersonId
|
||||
@@ -394,6 +419,7 @@ const Galaxy = ({ onPersonSelect, onMediaSelect, selectedPersonId, searchHighlig
|
||||
layoutData.children.forEach(node => {
|
||||
posMap.set(node.id, getAnimatedPos(node, timestamp))
|
||||
})
|
||||
positionUnionJunctions(coupleBarMeta, posMap)
|
||||
|
||||
const nodeMap = new Map()
|
||||
layoutData.children.forEach(n => nodeMap.set(n.id, n))
|
||||
|
||||
@@ -210,7 +210,9 @@ export function computeBlockLayout(graphData = null) {
|
||||
const renvoisByUnion = new Map()
|
||||
for (const e of result.edges) {
|
||||
const u = e.sources[0], c = e.targets[0]
|
||||
if (!externalEdges.has(`${u}>${c}`) || Math.abs(centerX(u) - centerX(c)) <= RENVOI_MIN_DX) continue
|
||||
if (!externalEdges.has(`${u}>${c}`)) continue
|
||||
e._renvoiEligible = true
|
||||
if (Math.abs(centerX(u) - centerX(c)) <= RENVOI_MIN_DX) continue
|
||||
e._renvoi = true
|
||||
e._renvoiIndex = renvoisByUnion.get(u) || 0
|
||||
renvoisByUnion.set(u, e._renvoiIndex + 1)
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
function readLayoutPosition(person) {
|
||||
if (!Number.isFinite(person?.layoutX) || !Number.isFinite(person?.layoutY)) return null
|
||||
return { x: person.layoutX, y: person.layoutY }
|
||||
}
|
||||
|
||||
export function captureAutomaticPersonPositions(layoutData) {
|
||||
return new Map(
|
||||
layoutData.children
|
||||
.filter((node) => node._type === 'person')
|
||||
.map((node) => [node.id, { x: node.x, y: node.y }]),
|
||||
)
|
||||
}
|
||||
|
||||
export function applyManualPersonPositions(
|
||||
layoutData,
|
||||
{ draftPositions = {}, getPersonById, automaticPositions = new Map() } = {},
|
||||
) {
|
||||
if (!layoutData) return
|
||||
|
||||
for (const node of layoutData.children) {
|
||||
if (node._type !== 'person') continue
|
||||
|
||||
const personId = String(node._data.id)
|
||||
const draftPosition = readLayoutPosition(draftPositions[personId])
|
||||
const person = getPersonById?.(node._data.id) || node._data
|
||||
const position = draftPosition || readLayoutPosition(person)
|
||||
|
||||
if (position) {
|
||||
node.x = position.x - node.width / 2
|
||||
node.y = position.y - node.height / 2
|
||||
node._manualPosition = true
|
||||
continue
|
||||
}
|
||||
|
||||
const automaticPosition = automaticPositions.get(node.id)
|
||||
if (automaticPosition) {
|
||||
node.x = automaticPosition.x
|
||||
node.y = automaticPosition.y
|
||||
}
|
||||
node._manualPosition = false
|
||||
}
|
||||
}
|
||||
|
||||
export function positionUnionJunctions(coupleBarMeta, positionById) {
|
||||
for (const { elkId, p1Key, p2Key } of coupleBarMeta) {
|
||||
const partner1 = positionById.get(p1Key)
|
||||
const partner2 = positionById.get(p2Key)
|
||||
if (!partner1 || !partner2) continue
|
||||
|
||||
positionById.set(elkId, {
|
||||
cx: (partner1.cx + partner2.cx) / 2,
|
||||
cy: (partner1.cy + partner2.cy) / 2,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
applyManualPersonPositions,
|
||||
captureAutomaticPersonPositions,
|
||||
positionUnionJunctions,
|
||||
} from './layoutPositions'
|
||||
|
||||
const makeLayout = () => ({
|
||||
children: [
|
||||
{ id: 'p-1', _type: 'person', _data: { id: '1', layoutX: 300, layoutY: 400 }, x: 10, y: 20, width: 80, height: 80 },
|
||||
{ id: 'p-2', _type: 'person', _data: { id: '2' }, x: 110, y: 120, width: 80, height: 80 },
|
||||
{ id: 'u-1', _type: 'union', _data: { id: 'u-1' }, x: 50, y: 70, width: 20, height: 20 },
|
||||
],
|
||||
edges: [{ id: 'edge-1', sources: ['p-1'], targets: ['p-2'] }],
|
||||
})
|
||||
|
||||
describe('manual person layout positions', () => {
|
||||
it('uses draft coordinates ahead of persisted coordinates and leaves relationships intact', () => {
|
||||
const layout = makeLayout()
|
||||
const automaticPositions = captureAutomaticPersonPositions(layout)
|
||||
|
||||
applyManualPersonPositions(layout, {
|
||||
draftPositions: { 1: { layoutX: 500, layoutY: 600 } },
|
||||
automaticPositions,
|
||||
})
|
||||
|
||||
expect(layout.children[0]).toMatchObject({ x: 460, y: 560, _manualPosition: true })
|
||||
expect(layout.edges).toEqual([{ id: 'edge-1', sources: ['p-1'], targets: ['p-2'] }])
|
||||
expect(layout.children[2].x).toBe(50)
|
||||
})
|
||||
|
||||
it('restores automatic coordinates when draft positions are discarded', () => {
|
||||
const layout = makeLayout()
|
||||
layout.children[0]._data.layoutX = null
|
||||
layout.children[0]._data.layoutY = null
|
||||
const automaticPositions = captureAutomaticPersonPositions(layout)
|
||||
layout.children[0].x = 900
|
||||
layout.children[0].y = 900
|
||||
|
||||
applyManualPersonPositions(layout, { automaticPositions })
|
||||
|
||||
expect(layout.children[0]).toMatchObject({ x: 10, y: 20, _manualPosition: false })
|
||||
})
|
||||
|
||||
it('ignores incomplete coordinates and falls back to saved person coordinates', () => {
|
||||
const layout = makeLayout()
|
||||
|
||||
applyManualPersonPositions(layout, {
|
||||
draftPositions: { 1: { layoutX: 500 } },
|
||||
automaticPositions: captureAutomaticPersonPositions(layout),
|
||||
})
|
||||
|
||||
expect(layout.children[0]).toMatchObject({ x: 260, y: 360, _manualPosition: true })
|
||||
})
|
||||
})
|
||||
|
||||
describe('dynamic union junction positions', () => {
|
||||
it('keeps the junction centered between partners after their positions change', () => {
|
||||
const positions = new Map([
|
||||
['p-1', { cx: 400, cy: 250 }],
|
||||
['p-2', { cx: 700, cy: 350 }],
|
||||
['u-1', { cx: 100, cy: 100 }],
|
||||
])
|
||||
|
||||
positionUnionJunctions(
|
||||
[{ elkId: 'u-1', p1Key: 'p-1', p2Key: 'p-2' }],
|
||||
positions,
|
||||
)
|
||||
|
||||
expect(positions.get('u-1')).toEqual({ cx: 550, cy: 300 })
|
||||
})
|
||||
|
||||
it('leaves a junction unchanged if either partner position is unavailable', () => {
|
||||
const originalJunction = { cx: 100, cy: 100 }
|
||||
const positions = new Map([
|
||||
['p-1', { cx: 400, cy: 250 }],
|
||||
['u-1', originalJunction],
|
||||
])
|
||||
|
||||
positionUnionJunctions(
|
||||
[{ elkId: 'u-1', p1Key: 'p-1', p2Key: 'p-2' }],
|
||||
positions,
|
||||
)
|
||||
|
||||
expect(positions.get('u-1')).toBe(originalJunction)
|
||||
})
|
||||
})
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
PERSON_R, UNKNOWN_R, UNION_W, UNION_H, COMPACT_R, COMPACT_SCALE,
|
||||
MAX_ORBIT_MEDIAS, ORBIT_MEDIA_SIZE,
|
||||
COLORS,
|
||||
RENVOI_MIN_DX,
|
||||
LOD_SHADOW_MIN_SCALE, LOD_DETAIL_MIN_SCALE, LOD_LABEL_FADE_IN, LOD_LABEL_FADE_OUT, CULL_MARGIN,
|
||||
} from './constants'
|
||||
import { getEntranceProgress, drawPartialBezier } from './utils'
|
||||
@@ -101,6 +102,11 @@ const BUS_TURN = 56
|
||||
// En dessous de cet écart union → enfant, pas de virage
|
||||
const BUS_STRAIGHT_DX = 30
|
||||
|
||||
export function shouldRenderRenvoi(edge, sourcePos, targetPos) {
|
||||
if (!edge._renvoiEligible) return Boolean(edge._renvoi)
|
||||
return Math.abs(sourcePos.cx - targetPos.cx) > RENVOI_MIN_DX
|
||||
}
|
||||
|
||||
function busY(sourceId, sy) {
|
||||
let h = 0
|
||||
for (let i = 0; i < sourceId.length; i++) h = (h * 31 + sourceId.charCodeAt(i)) | 0
|
||||
@@ -251,6 +257,7 @@ export function drawFiliations(ctx, edges, posMap, nodeMap, nodeRandomData, entr
|
||||
renvoiHitAreas.length = 0
|
||||
renvoiPills.length = 0
|
||||
if (!edges) return
|
||||
const renvoiIndexBySource = new Map()
|
||||
|
||||
edges.forEach(edge => {
|
||||
const sourceId = edge.sources[0]
|
||||
@@ -287,8 +294,13 @@ export function drawFiliations(ctx, edges, posMap, nodeMap, nodeRandomData, entr
|
||||
ctx.globalAlpha = Math.min(1, edgeProgress * 1.5)
|
||||
|
||||
const childR = nodeRadius(targetNode)
|
||||
if (edge._renvoi) {
|
||||
drawRenvoi(ctx, edge, sourcePos, targetPos, targetNode, childR, view)
|
||||
const isRenvoi = shouldRenderRenvoi(edge, sourcePos, targetPos)
|
||||
if (isRenvoi) {
|
||||
const index = edge._renvoiEligible
|
||||
? (renvoiIndexBySource.get(sourceId) || 0)
|
||||
: (edge._renvoiIndex || 0)
|
||||
if (edge._renvoiEligible) renvoiIndexBySource.set(sourceId, index + 1)
|
||||
drawRenvoi(ctx, { ...edge, _renvoiIndex: index }, sourcePos, targetPos, targetNode, childR, view)
|
||||
ctx.globalAlpha = 1
|
||||
ctx.setLineDash([])
|
||||
return
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { RENVOI_MIN_DX } from './constants'
|
||||
import { shouldRenderRenvoi } from './renderers'
|
||||
|
||||
describe('renvoi rendering with manual positions', () => {
|
||||
it('replaces an eligible renvoi with a direct link once the nodes are close enough', () => {
|
||||
expect(shouldRenderRenvoi(
|
||||
{ _renvoi: true, _renvoiEligible: true },
|
||||
{ cx: 0, cy: 0 },
|
||||
{ cx: RENVOI_MIN_DX, cy: 200 },
|
||||
)).toBe(false)
|
||||
})
|
||||
|
||||
it('retains a renvoi for an eligible edge that is still far away', () => {
|
||||
expect(shouldRenderRenvoi(
|
||||
{ _renvoiEligible: true },
|
||||
{ cx: 0, cy: 0 },
|
||||
{ cx: RENVOI_MIN_DX + 1, cy: 200 },
|
||||
)).toBe(true)
|
||||
})
|
||||
|
||||
it('preserves the precomputed behavior for non-eligible edges', () => {
|
||||
expect(shouldRenderRenvoi({ _renvoi: true }, { cx: 0 }, { cx: 0 })).toBe(true)
|
||||
expect(shouldRenderRenvoi({}, { cx: 0 }, { cx: 1000 })).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRef, useCallback } from 'react'
|
||||
import { useRef, useCallback, useEffect } from 'react'
|
||||
import { getPersonMedias } from '../../data/mockData'
|
||||
import { MAX_ORBIT_MEDIAS, ORBIT_MEDIA_SIZE } from './constants'
|
||||
import { nodeRadius, renvoiHitAreas } from './renderers'
|
||||
@@ -8,6 +8,7 @@ import { getEntranceProgress } from './utils'
|
||||
|
||||
const CURSOR_GRAB = 'default'
|
||||
const CURSOR_GRABBING = 'grabbing'
|
||||
const CURSOR_NODE_GRAB = 'grab'
|
||||
const CURSOR_POINTER = 'pointer'
|
||||
const CURSOR_CROSSHAIR = 'crosshair'
|
||||
|
||||
@@ -22,6 +23,7 @@ export function useGalaxyInteractions({
|
||||
layoutDataRef, nodeRandomDataRef, entranceRef,
|
||||
hoveredNodeIdRef, hoveredMediaKeyRef, mouseWorldPosRef,
|
||||
getAnimatedPos, onPersonSelect, onMediaSelect,
|
||||
onPersonPositionChange, editModeActive = false,
|
||||
annotationHandlers,
|
||||
minScale = 0.2,
|
||||
maxScale = 4,
|
||||
@@ -32,6 +34,11 @@ export function useGalaxyInteractions({
|
||||
const lastMouse = useRef({ x: 0, y: 0 })
|
||||
const hasDragged = useRef(false)
|
||||
const annotationDragging = useRef(false)
|
||||
const draggedPersonRef = useRef(null)
|
||||
const handleMouseUpRef = useRef(null)
|
||||
const handleGlobalMouseUp = useCallback(() => {
|
||||
handleMouseUpRef.current?.()
|
||||
}, [])
|
||||
|
||||
const getWorldPos = useCallback((e) => {
|
||||
const rect = canvasRef.current?.getBoundingClientRect()
|
||||
@@ -65,11 +72,37 @@ export function useGalaxyInteractions({
|
||||
}
|
||||
}
|
||||
|
||||
if (editModeActive && (!ah || ah.activeTool === 'pointer') && worldPos && layoutDataRef.current) {
|
||||
const now = performance.now()
|
||||
for (let index = layoutDataRef.current.children.length - 1; index >= 0; index -= 1) {
|
||||
const node = layoutDataRef.current.children[index]
|
||||
if (node._type !== 'person') continue
|
||||
const pos = getAnimatedPos(node, now)
|
||||
if (Math.hypot(pos.cx - worldPos.x, pos.cy - worldPos.y) >= nodeRadius(node)) continue
|
||||
|
||||
draggedPersonRef.current = {
|
||||
node,
|
||||
offsetX: worldPos.x - pos.cx,
|
||||
offsetY: worldPos.y - pos.cy,
|
||||
startClientX: e.clientX,
|
||||
startClientY: e.clientY,
|
||||
}
|
||||
hoveredNodeIdRef.current = node.id
|
||||
hasDragged.current = false
|
||||
lastMouse.current = { x: e.clientX, y: e.clientY }
|
||||
setCanvasCursor(canvasRef, CURSOR_GRABBING)
|
||||
if (e.nativeEvent?.type === 'mousedown' && typeof window !== 'undefined' && handleMouseUpRef.current) {
|
||||
window.addEventListener('mouseup', handleGlobalMouseUp)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
isDragging.current = true
|
||||
hasDragged.current = false
|
||||
lastMouse.current = { x: e.clientX, y: e.clientY }
|
||||
setCanvasCursor(canvasRef, CURSOR_GRABBING)
|
||||
}, [canvasRef, annotationHandlers, getWorldPos])
|
||||
}, [canvasRef, annotationHandlers, getWorldPos, editModeActive, layoutDataRef, getAnimatedPos, hoveredNodeIdRef, handleGlobalMouseUp])
|
||||
|
||||
const handleMouseMove = useCallback((e) => {
|
||||
const rect = canvasRef.current?.getBoundingClientRect()
|
||||
@@ -83,6 +116,19 @@ export function useGalaxyInteractions({
|
||||
|
||||
const ah = annotationHandlers
|
||||
|
||||
if (draggedPersonRef.current) {
|
||||
const drag = draggedPersonRef.current
|
||||
if (!hasDragged.current && Math.hypot(e.clientX - drag.startClientX, e.clientY - drag.startClientY) <= 2) return
|
||||
hasDragged.current = true
|
||||
drag.node.x = mouseWorldPosRef.current.x - drag.offsetX - drag.node.width / 2
|
||||
drag.node.y = mouseWorldPosRef.current.y - drag.offsetY - drag.node.height / 2
|
||||
drag.node._manualPosition = true
|
||||
hoveredNodeIdRef.current = drag.node.id
|
||||
lastMouse.current = { x: e.clientX, y: e.clientY }
|
||||
setCanvasCursor(canvasRef, CURSOR_GRABBING)
|
||||
return
|
||||
}
|
||||
|
||||
// Drawing tool: accumulate points
|
||||
if (ah && ah.activeTool === 'drawing' && ah.drawingPathRef.current) {
|
||||
ah.onCanvasMouseMove(mouseWorldPosRef.current.x, mouseWorldPosRef.current.y)
|
||||
@@ -142,7 +188,9 @@ export function useGalaxyInteractions({
|
||||
hoveredMediaKeyRef.current = newHoveredMedia
|
||||
|
||||
if (!ah || ah.activeTool === 'pointer') {
|
||||
const cursor = isOverClickable ? CURSOR_POINTER : CURSOR_GRAB
|
||||
const cursor = editModeActive && newHoveredNode
|
||||
? CURSOR_NODE_GRAB
|
||||
: isOverClickable ? CURSOR_POINTER : CURSOR_GRAB
|
||||
setCanvasCursor(canvasRef, cursor)
|
||||
}
|
||||
}
|
||||
@@ -157,7 +205,7 @@ export function useGalaxyInteractions({
|
||||
x: targetTransformRef.current.x + dx,
|
||||
y: targetTransformRef.current.y + dy,
|
||||
}
|
||||
}, [canvasRef, transformRef, targetTransformRef, layoutDataRef, nodeRandomDataRef, entranceRef, hoveredNodeIdRef, hoveredMediaKeyRef, mouseWorldPosRef, getAnimatedPos, annotationHandlers])
|
||||
}, [canvasRef, transformRef, targetTransformRef, layoutDataRef, nodeRandomDataRef, entranceRef, hoveredNodeIdRef, hoveredMediaKeyRef, mouseWorldPosRef, getAnimatedPos, annotationHandlers, editModeActive])
|
||||
|
||||
const handleMouseUp = useCallback(() => {
|
||||
const ah = annotationHandlers
|
||||
@@ -177,15 +225,42 @@ export function useGalaxyInteractions({
|
||||
return
|
||||
}
|
||||
|
||||
if (draggedPersonRef.current) {
|
||||
const { node } = draggedPersonRef.current
|
||||
draggedPersonRef.current = null
|
||||
if (typeof window !== 'undefined') {
|
||||
window.removeEventListener('mouseup', handleGlobalMouseUp)
|
||||
}
|
||||
if (hasDragged.current) {
|
||||
onPersonPositionChange?.(node._data.id, {
|
||||
layoutX: node.x + node.width / 2,
|
||||
layoutY: node.y + node.height / 2,
|
||||
})
|
||||
}
|
||||
hoveredNodeIdRef.current = node.id
|
||||
setCanvasCursor(canvasRef, editModeActive ? CURSOR_NODE_GRAB : CURSOR_POINTER)
|
||||
return
|
||||
}
|
||||
|
||||
isDragging.current = false
|
||||
const isOverClickable = hoveredNodeIdRef.current || hoveredMediaKeyRef.current
|
||||
setCanvasCursor(canvasRef, isOverClickable ? CURSOR_POINTER : CURSOR_GRAB)
|
||||
}, [canvasRef, hoveredNodeIdRef, hoveredMediaKeyRef, mouseWorldPosRef, annotationHandlers])
|
||||
}, [canvasRef, hoveredNodeIdRef, hoveredMediaKeyRef, mouseWorldPosRef, annotationHandlers, onPersonPositionChange, editModeActive, handleGlobalMouseUp])
|
||||
|
||||
useEffect(() => {
|
||||
handleMouseUpRef.current = handleMouseUp
|
||||
}, [handleMouseUp])
|
||||
|
||||
useEffect(() => () => {
|
||||
if (typeof window !== 'undefined') {
|
||||
window.removeEventListener('mouseup', handleGlobalMouseUp)
|
||||
}
|
||||
}, [handleGlobalMouseUp])
|
||||
|
||||
const handleMouseLeave = useCallback(() => {
|
||||
isDragging.current = false
|
||||
annotationDragging.current = false
|
||||
setCanvasCursor(canvasRef, CURSOR_GRAB)
|
||||
setCanvasCursor(canvasRef, draggedPersonRef.current ? CURSOR_GRABBING : CURSOR_GRAB)
|
||||
mouseWorldPosRef.current = { x: -9999, y: -9999 }
|
||||
hoveredNodeIdRef.current = null
|
||||
hoveredMediaKeyRef.current = null
|
||||
|
||||
@@ -100,6 +100,8 @@ function mapRemotePersonToLocal(person, current = null) {
|
||||
|
||||
return {
|
||||
id: person?.id ?? current?.id,
|
||||
layoutX: Number.isFinite(person?.layoutX) ? person.layoutX : null,
|
||||
layoutY: Number.isFinite(person?.layoutY) ? person.layoutY : null,
|
||||
firstName: person?.firstName || current?.firstName || t('Inconnu'),
|
||||
lastName: person?.lastName || current?.lastName || '',
|
||||
birthName: person?.birthName ?? current?.birthName ?? null,
|
||||
|
||||
@@ -13,6 +13,8 @@ describe('loadGraphData avatar mapping', () => {
|
||||
lastName: 'Martin',
|
||||
birthDate: null,
|
||||
deathDate: null,
|
||||
layoutX: 420.5,
|
||||
layoutY: 275.25,
|
||||
notes: null,
|
||||
avatarUrlPath: '/trees/t-1/persons/p-1/avatar',
|
||||
},
|
||||
@@ -46,6 +48,7 @@ describe('loadGraphData avatar mapping', () => {
|
||||
)
|
||||
|
||||
expect(getPersonById('p-1')?.photo).toBe('/api/trees/t-1/persons/p-1/avatar?token=abc')
|
||||
expect(getPersonById('p-1')).toMatchObject({ layoutX: 420.5, layoutY: 275.25 })
|
||||
expect(getPersonById('p-2')?.photo).toBeNull()
|
||||
expect(getPersonMedias('p-2')[0]?.source).toBe('Album familial')
|
||||
})
|
||||
|
||||
@@ -46,6 +46,8 @@ export function adaptGraphForGalaxy(apiGraph, _treeId) {
|
||||
// Adapter les personnes
|
||||
const adaptedPersons = persons.map((p) => ({
|
||||
id: p.id,
|
||||
layoutX: Number.isFinite(p.layoutX) ? p.layoutX : null,
|
||||
layoutY: Number.isFinite(p.layoutY) ? p.layoutY : null,
|
||||
firstName: p.firstName || '',
|
||||
lastName: p.lastName || '',
|
||||
birthName: p.birthName || null,
|
||||
|
||||
Reference in new issue
Block a user