mirror of
https://github.com/IliesAllali/parenthese.git
synced 2026-11-17 08:42:23 +00:00
Merge pull request #76 from IliesAllali/frise-de-vie
Onglet Vie : la frise de vie, et ajouter un moment
This commit is contained in:
17 files changed
+1118
-13
No files matched your search
@@ -0,0 +1,2 @@
|
||||
-- Photo rattachée à un événement de vie (souvenir de la personne), facultative
|
||||
ALTER TABLE "life_events" ADD COLUMN "mediaId" TEXT;
|
||||
@@ -424,6 +424,7 @@ model LifeEvent {
|
||||
description String?
|
||||
notes String?
|
||||
sources String?
|
||||
mediaId String?
|
||||
displayOrder Int @default(1)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@ -203,7 +203,7 @@ export const graphRoutes: FastifyPluginAsync = async (app) => {
|
||||
where: { treeId, deletedAt: null, OR: [{ personId }, ...(unionIds.length ? [{ unionId: { in: unionIds } }] : [])] },
|
||||
select: {
|
||||
id: true, personId: true, unionId: true, type: true, label: true, date: true, dateEnd: true, datePrecision: true,
|
||||
dateText: true, place: true, description: true, notes: true, sources: true, displayOrder: true,
|
||||
dateText: true, place: true, description: true, notes: true, sources: true, mediaId: true, displayOrder: true,
|
||||
},
|
||||
orderBy: [{ date: 'asc' }, { displayOrder: 'asc' }, { createdAt: 'asc' }],
|
||||
})
|
||||
|
||||
@@ -156,6 +156,49 @@ const patchParentChildLinkSchema = z
|
||||
message: 'at_least_one_field_required',
|
||||
})
|
||||
|
||||
// Événements de vie saisis dans l'onglet Vie (« Ajouter un moment »). Naissance, décès et mariage gardent
|
||||
// leur date sur la personne ou l'union et ne passent pas par ici.
|
||||
const LIFE_EVENT_PRECISIONS = ['about', 'estimated', 'calculated', 'before', 'after', 'between', 'from', 'to', 'interpreted'] as const
|
||||
const RESERVED_LIFE_EVENT_TYPES = new Set(['birth', 'death', 'marriage'])
|
||||
const lifeEventDateRegex = /^\d{4}(-\d{2}-\d{2})?$/
|
||||
const lifeEventPayloadSchema = z.object({
|
||||
type: z.string().trim().min(1).max(40).regex(/^[a-z_]+$/).refine((type) => !RESERVED_LIFE_EVENT_TYPES.has(type)).default('custom'),
|
||||
label: z.string().trim().max(120).nullable().optional(),
|
||||
description: z.string().trim().max(1000).nullable().optional(),
|
||||
date: z.string().regex(lifeEventDateRegex).nullable().optional(),
|
||||
dateEnd: z.string().regex(lifeEventDateRegex).nullable().optional(),
|
||||
datePrecision: z.enum(LIFE_EVENT_PRECISIONS).nullable().optional(),
|
||||
place: z.string().trim().max(300).nullable().optional(),
|
||||
notes: z.string().trim().max(4000).nullable().optional(),
|
||||
sources: z.string().trim().max(4000).nullable().optional(),
|
||||
mediaId: z.string().min(1).nullable().optional(),
|
||||
})
|
||||
const lifeEventParamsSchema = z.object({ id: z.string().min(1), eventId: z.string().min(1) })
|
||||
|
||||
const lifeEventDate = (value: string | null | undefined) => {
|
||||
if (value === undefined) return undefined
|
||||
if (!value) return null
|
||||
return new Date(`${value.length === 4 ? `${value}-01-01` : value}T00:00:00.000Z`)
|
||||
}
|
||||
const emptyToNull = (value: string | null | undefined) => (value === undefined ? undefined : value?.trim() ? value.trim() : null)
|
||||
|
||||
function lifeEventData(payload: z.infer<typeof lifeEventPayloadSchema>) {
|
||||
return {
|
||||
type: payload.type,
|
||||
label: emptyToNull(payload.label),
|
||||
description: emptyToNull(payload.description),
|
||||
date: lifeEventDate(payload.date),
|
||||
dateEnd: lifeEventDate(payload.dateEnd),
|
||||
datePrecision: payload.datePrecision,
|
||||
// Saisi dans l'app : pas de texte GEDCOM d'origine à garder
|
||||
dateText: null,
|
||||
place: emptyToNull(payload.place),
|
||||
notes: emptyToNull(payload.notes),
|
||||
sources: emptyToNull(payload.sources),
|
||||
mediaId: payload.mediaId,
|
||||
}
|
||||
}
|
||||
|
||||
const personParamsSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
personId: z.string().min(1),
|
||||
@@ -2006,6 +2049,84 @@ export const treeRoutes: FastifyPluginAsync = async (app) => {
|
||||
})
|
||||
|
||||
// Réordonner une fratrie : displayOrder des liens parent-enfant réécrit en une transaction
|
||||
// Photo rattachée : un souvenir de cette personne, dans cet arbre
|
||||
const checkLifeEventMedia = async (treeId: string, personId: string, mediaId: string | null | undefined) => {
|
||||
if (!mediaId) return true
|
||||
const media = await app.prisma.mediaItem.findFirst({ where: { id: mediaId, treeId, personId, deletedAt: null }, select: { id: true } })
|
||||
return Boolean(media)
|
||||
}
|
||||
|
||||
app.post('/trees/:id/persons/:personId/life/events', async (request, reply) => {
|
||||
const user = requireUser(request, reply)
|
||||
if (!user) return
|
||||
const params = personParamsSchema.safeParse(request.params)
|
||||
if (!params.success) return reply.code(400).send({ error: 'invalid_params' })
|
||||
const payload = lifeEventPayloadSchema.safeParse(request.body ?? {})
|
||||
if (!payload.success) return reply.code(400).send({ error: 'invalid_payload', details: payload.error.flatten() })
|
||||
if (!payload.data.label?.trim() && !payload.data.description?.trim() && payload.data.type === 'custom') {
|
||||
return reply.code(400).send({ error: 'invalid_payload' })
|
||||
}
|
||||
|
||||
const membership = await getAdminMembership(app, user.userId, params.data.id)
|
||||
if (!hasActiveAdminMembership(membership)) return reply.code(403).send({ error: 'forbidden' })
|
||||
|
||||
const person = await app.prisma.person.findFirst({ where: { id: params.data.personId, treeId: params.data.id, deletedAt: null }, select: { id: true } })
|
||||
if (!person) return reply.code(404).send({ error: 'person_not_found' })
|
||||
if (!(await checkLifeEventMedia(params.data.id, params.data.personId, payload.data.mediaId))) {
|
||||
return reply.code(400).send({ error: 'invalid_media_reference' })
|
||||
}
|
||||
|
||||
const event = await app.prisma.lifeEvent.create({
|
||||
data: { treeId: params.data.id, personId: params.data.personId, ...lifeEventData(payload.data) },
|
||||
})
|
||||
return reply.code(201).send({ event: { id: event.id } })
|
||||
})
|
||||
|
||||
app.patch('/trees/:id/life/events/:eventId', async (request, reply) => {
|
||||
const user = requireUser(request, reply)
|
||||
if (!user) return
|
||||
const params = lifeEventParamsSchema.safeParse(request.params)
|
||||
if (!params.success) return reply.code(400).send({ error: 'invalid_params' })
|
||||
const payload = lifeEventPayloadSchema.partial().safeParse(request.body ?? {})
|
||||
if (!payload.success) return reply.code(400).send({ error: 'invalid_payload', details: payload.error.flatten() })
|
||||
|
||||
const membership = await getAdminMembership(app, user.userId, params.data.id)
|
||||
if (!hasActiveAdminMembership(membership)) return reply.code(403).send({ error: 'forbidden' })
|
||||
|
||||
const existing = await app.prisma.lifeEvent.findFirst({
|
||||
where: { id: params.data.eventId, treeId: params.data.id, deletedAt: null },
|
||||
select: { personId: true, type: true },
|
||||
})
|
||||
if (!existing || !existing.personId || RESERVED_LIFE_EVENT_TYPES.has(existing.type)) {
|
||||
return reply.code(404).send({ error: 'event_not_found' })
|
||||
}
|
||||
if (!(await checkLifeEventMedia(params.data.id, existing.personId, payload.data.mediaId))) {
|
||||
return reply.code(400).send({ error: 'invalid_media_reference' })
|
||||
}
|
||||
|
||||
// Le type ne change pas après coup (le schéma partiel remettrait sa valeur par défaut)
|
||||
const data = lifeEventData({ ...payload.data, type: existing.type } as z.infer<typeof lifeEventPayloadSchema>)
|
||||
await app.prisma.lifeEvent.update({ where: { id: params.data.eventId }, data })
|
||||
return reply.send({ ok: true })
|
||||
})
|
||||
|
||||
app.delete('/trees/:id/life/events/:eventId', async (request, reply) => {
|
||||
const user = requireUser(request, reply)
|
||||
if (!user) return
|
||||
const params = lifeEventParamsSchema.safeParse(request.params)
|
||||
if (!params.success) return reply.code(400).send({ error: 'invalid_params' })
|
||||
|
||||
const membership = await getAdminMembership(app, user.userId, params.data.id)
|
||||
if (!hasActiveAdminMembership(membership)) return reply.code(403).send({ error: 'forbidden' })
|
||||
|
||||
const deleted = await app.prisma.lifeEvent.updateMany({
|
||||
where: { id: params.data.eventId, treeId: params.data.id, deletedAt: null, personId: { not: null }, type: { notIn: [...RESERVED_LIFE_EVENT_TYPES] } },
|
||||
data: { deletedAt: new Date() },
|
||||
})
|
||||
if (deleted.count === 0) return reply.code(404).send({ error: 'event_not_found' })
|
||||
return reply.code(204).send()
|
||||
})
|
||||
|
||||
app.put('/trees/:id/links/order', async (request, reply) => {
|
||||
const user = requireUser(request, reply)
|
||||
if (!user) {
|
||||
|
||||
@@ -71,6 +71,9 @@ const { prismaMock } = vi.hoisted(() => ({
|
||||
updateMany: vi.fn(),
|
||||
},
|
||||
lifeEvent: {
|
||||
findFirst: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
createMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
updateMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
@@ -628,6 +631,56 @@ describe('Graph routes', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Événements de vie saisis dans l’onglet Vie', () => {
|
||||
it('un admin ajoute un moment avec sa photo, le modifie sans changer son type, le supprime', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
const auth = { authorization: `Bearer ${token}` }
|
||||
prismaMock.mediaItem.findFirst.mockResolvedValue({ id: 'm-1' })
|
||||
prismaMock.lifeEvent.create.mockResolvedValue({ id: 'e-1' })
|
||||
|
||||
const created = await app.inject({
|
||||
method: 'POST', url: '/trees/tree-1/persons/person-1/life/events', headers: auth,
|
||||
payload: { label: 'Service militaire', date: '1940', datePrecision: 'about', place: 'Limoges', mediaId: 'm-1' },
|
||||
})
|
||||
expect(created.statusCode).toBe(201)
|
||||
expect(prismaMock.lifeEvent.create).toHaveBeenCalledWith({ data: expect.objectContaining({
|
||||
treeId: 'tree-1', personId: 'person-1', type: 'custom', label: 'Service militaire',
|
||||
date: new Date('1940-01-01T00:00:00.000Z'), datePrecision: 'about', place: 'Limoges', mediaId: 'm-1',
|
||||
}) })
|
||||
|
||||
prismaMock.lifeEvent.findFirst.mockResolvedValue({ personId: 'person-1', type: 'occupation' })
|
||||
const patched = await app.inject({ method: 'PATCH', url: '/trees/tree-1/life/events/e-1', headers: auth, payload: { place: '' } })
|
||||
expect(patched.statusCode).toBe(200)
|
||||
expect(prismaMock.lifeEvent.update).toHaveBeenCalledWith({ where: { id: 'e-1' }, data: expect.objectContaining({ type: 'occupation', place: null }) })
|
||||
|
||||
prismaMock.lifeEvent.updateMany.mockResolvedValue({ count: 1 })
|
||||
const deleted = await app.inject({ method: 'DELETE', url: '/trees/tree-1/life/events/e-1', headers: auth })
|
||||
expect(deleted.statusCode).toBe(204)
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('refuse un membre non admin, une photo d’une autre personne, un moment sans titre, une naissance', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
const auth = { authorization: `Bearer ${token}` }
|
||||
const post = (payload: object) => app.inject({ method: 'POST', url: '/trees/tree-1/persons/person-1/life/events', headers: auth, payload })
|
||||
|
||||
prismaMock.mediaItem.findFirst.mockResolvedValue(null)
|
||||
expect((await post({ label: 'Mariage', mediaId: 'autre' })).statusCode).toBe(400)
|
||||
expect((await post({ label: ' ' })).statusCode).toBe(400)
|
||||
expect((await post({ type: 'birth', label: 'Naissance' })).statusCode).toBe(400)
|
||||
|
||||
prismaMock.lifeEvent.findFirst.mockResolvedValue({ personId: 'person-1', type: 'birth' })
|
||||
expect((await app.inject({ method: 'PATCH', url: '/trees/tree-1/life/events/e-1', headers: auth, payload: { place: 'x' } })).statusCode).toBe(404)
|
||||
|
||||
prismaMock.treeMembership.findUnique.mockResolvedValue({ role: 'member', tree: { deletedAt: null } })
|
||||
expect((await post({ label: 'Service militaire' })).statusCode).toBe(403)
|
||||
expect(prismaMock.lifeEvent.create).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Visit log', () => {
|
||||
it('refuses the visit log to a non-admin member', async () => {
|
||||
const app = createApp()
|
||||
|
||||
@@ -2966,6 +2966,7 @@ function App() {
|
||||
relationActionError={relationFeedback.error}
|
||||
siblingPlace={siblingPlace}
|
||||
onMoveSibling={(delta) => galaxyZoomApiRef.current?.moveSibling?.(tree.selectedPerson.id, delta)}
|
||||
onUploadMomentPhoto={tree.canEditCurrentTree ? media.uploadMomentPhoto : undefined}
|
||||
/>
|
||||
)}
|
||||
{tree.selectedMedia && (
|
||||
|
||||
@@ -59,6 +59,38 @@ export async function fetchTreeGraph(treeId, token) {
|
||||
}
|
||||
}
|
||||
|
||||
// Frise de vie d'une personne : événements, précisions de date, lieux des unions
|
||||
export async function fetchPersonLife(treeId, personId, token) {
|
||||
return apiRequest(`/trees/${encodeURIComponent(treeId)}/persons/${encodeURIComponent(personId)}/life`, {
|
||||
method: 'GET',
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
}
|
||||
|
||||
// Moments saisis dans l'onglet Vie (administrateurs)
|
||||
export async function createLifeEvent(treeId, personId, payload, token) {
|
||||
return apiRequest(`/trees/${encodeURIComponent(treeId)}/persons/${encodeURIComponent(personId)}/life/events`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateLifeEvent(treeId, eventId, payload, token) {
|
||||
return apiRequest(`/trees/${encodeURIComponent(treeId)}/life/events/${encodeURIComponent(eventId)}`, {
|
||||
method: 'PATCH',
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteLifeEvent(treeId, eventId, token) {
|
||||
return apiRequest(`/trees/${encodeURIComponent(treeId)}/life/events/${encodeURIComponent(eventId)}`, {
|
||||
method: 'DELETE',
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
}
|
||||
|
||||
export async function listTrees(token) {
|
||||
const data = await apiRequest('/trees', {
|
||||
method: 'GET',
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
/* Onglet Vie de la fiche (direction A2 retenue le 16/10). Variables --pz-* : src/styles/pz.css */
|
||||
|
||||
.lt { padding: 2px 0 4px; }
|
||||
.lt-rail { position: relative; list-style: none; margin: 0; padding: 0; display: grid; gap: 2px; }
|
||||
/* Le fil : un segment par entrée, du premier point au dernier (il s'arrête au décès) */
|
||||
|
||||
.lt-ev { --dot-y: 17.5px; position: relative; display: grid; grid-template-columns: 40px minmax(0, 1fr); gap: 0 30px; padding: 8px 0; }
|
||||
.lt-ev::before { content: ""; position: absolute; left: 54px; top: 0; bottom: -2px; width: 1px; background: var(--pz-line); }
|
||||
.lt-ev:first-child::before { top: var(--dot-y); }
|
||||
.lt-ev:last-child::before { bottom: auto; height: var(--dot-y); }
|
||||
.lt-ev:only-child::before { display: none; }
|
||||
.lt-ev::after {
|
||||
content: ""; position: absolute; left: 51px; top: 14px; width: 7px; height: 7px; border-radius: 50%;
|
||||
background: var(--pz-surface); box-shadow: inset 0 0 0 1.5px var(--pz-a500);
|
||||
}
|
||||
.lt-year { font: 400 13.5px/1.35 var(--pz-sans); color: var(--pz-ink-2); font-variant-numeric: tabular-nums; text-align: right; padding-top: 1px; }
|
||||
.lt-title { font: 400 14px/1.35 var(--pz-sans); color: var(--pz-ink); overflow-wrap: anywhere; }
|
||||
.lt-meta { font: 400 13px/1.45 var(--pz-sans); color: var(--pz-muted); margin-top: 2px; }
|
||||
.lt-note { font: 400 13px/1.5 var(--pz-sans); color: var(--pz-ink-2); margin: 4px 0 0; white-space: pre-line; }
|
||||
|
||||
/* Grands repères : naissance, unions, décès */
|
||||
.lt-ev--mile { --dot-y: 23.5px; padding: 12px 0 10px; }
|
||||
.lt-ev--mile::after { top: 19px; left: 50px; width: 9px; height: 9px; background: var(--pz-a500); }
|
||||
.lt-ev--mile .lt-title { font: 400 21px/1.2 var(--pz-serif); letter-spacing: -.005em; }
|
||||
.lt-ev--mile .lt-year { font-size: 14px; color: var(--pz-ink); padding-top: 6px; }
|
||||
|
||||
/* Famille proche, en retrait */
|
||||
.lt-ev--fam::after { box-shadow: inset 0 0 0 1.5px var(--pz-line); }
|
||||
.lt-ev--fam .lt-title { color: var(--pz-muted); }
|
||||
|
||||
.lt-sources { margin-top: 3px; }
|
||||
.lt-src {
|
||||
appearance: none; border: 0; background: none; padding: 2px 0; cursor: pointer;
|
||||
font: 500 12.5px var(--pz-sans); color: var(--pz-a700); text-underline-offset: 3px;
|
||||
}
|
||||
@media (hover: hover) and (pointer: fine) { .lt-src:hover { text-decoration: underline; } }
|
||||
.lt-src:focus-visible { outline: 2px solid var(--pz-a500); outline-offset: 2px; border-radius: 4px; }
|
||||
.lt-src-list {
|
||||
list-style: none; margin: 6px 0 0; padding: 8px 10px; display: grid; gap: 4px;
|
||||
background: var(--pz-bg); border-radius: var(--pz-r-s);
|
||||
font: 400 12.5px/1.5 var(--pz-sans); color: var(--pz-ink-2);
|
||||
animation: lt-open 180ms var(--pz-ease) both;
|
||||
}
|
||||
@keyframes lt-open { from { opacity: 0; transform: translateY(-3px); } to { opacity: 1; transform: none; } }
|
||||
|
||||
.lt-failed { margin-top: 10px; }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) { .lt-src-list { animation: none; } }
|
||||
|
||||
/* Moment modifiable (administrateurs) : le titre s'ouvre en fiche */
|
||||
.lt-title--edit {
|
||||
appearance: none; border: 0; background: none; padding: 0; margin: 0; text-align: left; cursor: pointer;
|
||||
font: inherit; color: inherit; border-radius: 4px; text-decoration: underline; text-decoration-color: transparent;
|
||||
text-underline-offset: 3px; transition: text-decoration-color 160ms ease;
|
||||
}
|
||||
@media (hover: hover) and (pointer: fine) { .lt-title--edit:hover { text-decoration-color: var(--pz-a300); } }
|
||||
.lt-title--edit:focus-visible { outline: 2px solid var(--pz-a500); outline-offset: 2px; }
|
||||
|
||||
.lt-photo {
|
||||
display: block; width: 112px; height: 84px; object-fit: cover; margin-top: 8px;
|
||||
border-radius: var(--pz-r-s); box-shadow: 0 0 0 1px rgba(42, 38, 34, .06);
|
||||
}
|
||||
.lt-add { margin-top: 14px; }
|
||||
.pc-empty .lt-add { margin-top: 12px; }
|
||||
@@ -0,0 +1,75 @@
|
||||
import { useState } from 'react'
|
||||
import { Plus } from 'lucide-react'
|
||||
import { t } from '../i18n/index.js'
|
||||
import { buildLifeTimeline } from '../utils/lifeTimeline.js'
|
||||
import './LifeTimeline.css'
|
||||
|
||||
// Onglet Vie de la fiche : naissance, unions et décès en grands repères, les autres événements
|
||||
// plus petits entre eux, la famille proche en retrait. Les sources restent repliées.
|
||||
function Sources({ text }) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const list = text.split('\n').map((s) => s.trim()).filter(Boolean)
|
||||
if (list.length === 0) return null
|
||||
return (
|
||||
<div className="lt-sources">
|
||||
<button type="button" className="lt-src" aria-expanded={open} onClick={() => setOpen((v) => !v)}>
|
||||
{list.length === 1 ? t('1 source') : t('{n} sources', { n: list.length })}
|
||||
</button>
|
||||
{open && (
|
||||
<ul className="lt-src-list">
|
||||
{list.map((source) => <li key={source}>{source}</li>)}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function LifeTimeline({ person, family, life, loading = false, failed = false, medias = [], canEdit = false, onAdd, onEdit }) {
|
||||
const entries = buildLifeTimeline(person, family, life)
|
||||
const mediaById = new Map(medias.map((m) => [String(m.id), m]))
|
||||
const addButton = canEdit && (
|
||||
<button type="button" className="pz-btn pz-btn--soft pz-btn--block lt-add" onClick={onAdd}>
|
||||
<Plus size={16} strokeWidth={2} />
|
||||
{t('Ajouter un moment')}
|
||||
</button>
|
||||
)
|
||||
|
||||
if (entries.length === 0) {
|
||||
return (
|
||||
<div className="pc-empty">
|
||||
<p className="pz-sub">{t('Pas encore de date connue pour {name}.', { name: person.firstName })}</p>
|
||||
<p className="pz-small">{t('Les dates de naissance, d’union et de décès, et celles de sa famille, apparaîtront ici.')}</p>
|
||||
{addButton}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="lt" aria-busy={loading || undefined}>
|
||||
<ol className="lt-rail">
|
||||
{entries.map((entry) => (
|
||||
<li key={entry.key} className={`lt-ev lt-ev--${entry.kind}`}>
|
||||
<span className="lt-year">{entry.year ?? ''}</span>
|
||||
<div className="lt-body">
|
||||
{canEdit && entry.event ? (
|
||||
<button type="button" className="lt-title lt-title--edit" onClick={() => onEdit?.(entry.event)} aria-label={t('Modifier « {title} »', { title: entry.title })}>
|
||||
{entry.title}
|
||||
</button>
|
||||
) : (
|
||||
<div className="lt-title">{entry.title}</div>
|
||||
)}
|
||||
{entry.meta && <div className="lt-meta">{entry.meta}</div>}
|
||||
{entry.note && <p className="lt-note">{entry.note}</p>}
|
||||
{entry.sources && <Sources text={entry.sources} />}
|
||||
{entry.mediaId && mediaById.get(String(entry.mediaId))?.url && (
|
||||
<img className="lt-photo" src={mediaById.get(String(entry.mediaId)).url} alt={entry.title} loading="lazy" />
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
{failed && <p className="pz-small lt-failed">{t('Les autres événements n’ont pas pu être chargés.')}</p>}
|
||||
{addButton}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/* Fiche « Ajouter un moment » de l'onglet Vie. Variables --pz-* : src/styles/pz.css */
|
||||
|
||||
.ms { width: min(100%, 460px); }
|
||||
.ms-title { font-size: 26px; }
|
||||
.ms-form { display: grid; gap: 16px; }
|
||||
.ms-optional { font-weight: 400; color: var(--pz-faint); margin-left: 4px; }
|
||||
|
||||
.ms-chips { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.ms-chip {
|
||||
appearance: none; border: 1px solid var(--pz-line); background: var(--pz-surface); border-radius: 999px;
|
||||
padding: 5px 11px; font: 500 12.5px var(--pz-sans); color: var(--pz-ink-2); cursor: pointer;
|
||||
transition: background-color 160ms ease, border-color 160ms ease, transform 140ms var(--pz-ease);
|
||||
}
|
||||
@media (hover: hover) and (pointer: fine) { .ms-chip:hover { border-color: var(--pz-a300); } }
|
||||
.ms-chip:active { transform: scale(.97); }
|
||||
.ms-chip.is-on { background: var(--pz-a50); border-color: var(--pz-a300); color: var(--pz-a700); }
|
||||
.ms-chip:focus-visible { outline: 2px solid var(--pz-a500); outline-offset: 2px; }
|
||||
|
||||
.ms-row { display: flex; gap: 12px; align-items: flex-end; flex-wrap: wrap; }
|
||||
.ms-row > .pz-field { flex: 1 1 150px; min-width: 0; }
|
||||
.ms-row > .ms-year { flex: 0 1 120px; }
|
||||
.ms-check { display: inline-flex; align-items: center; gap: 8px; min-height: 44px; font: 400 14px var(--pz-sans); color: var(--pz-ink-2); cursor: pointer; }
|
||||
.ms-check input { width: 16px; height: 16px; accent-color: var(--pz-a500); }
|
||||
|
||||
.ms-photo-add {
|
||||
display: inline-flex; align-items: center; gap: 8px; min-height: 40px; padding: 0 14px;
|
||||
border: 1.5px dashed var(--pz-a300); border-radius: 999px; background: var(--pz-a50);
|
||||
font: 500 13.5px var(--pz-sans); color: var(--pz-a700); cursor: pointer;
|
||||
transition: background-color 160ms ease, transform 140ms var(--pz-ease);
|
||||
}
|
||||
@media (hover: hover) and (pointer: fine) { .ms-photo-add:hover { background: var(--pz-a100); } }
|
||||
.ms-photo-add:active { transform: scale(.97); }
|
||||
.ms-photo-current { display: flex; align-items: center; gap: 12px; }
|
||||
.ms-photo-current img { width: 84px; height: 64px; object-fit: cover; border-radius: var(--pz-r-s); box-shadow: 0 0 0 1px rgba(42, 38, 34, .06); }
|
||||
|
||||
.ms-more { border-top: 1px solid var(--pz-line-soft); padding-top: 12px; }
|
||||
.ms-more summary { cursor: pointer; font: 500 13.5px var(--pz-sans); color: var(--pz-ink-2); list-style-position: inside; }
|
||||
.ms-more summary:focus-visible { outline: 2px solid var(--pz-a500); outline-offset: 2px; border-radius: 4px; }
|
||||
.ms-more-body { display: grid; gap: 14px; margin-top: 12px; }
|
||||
|
||||
.ms-actions-end { display: flex; gap: 8px; margin-left: auto; }
|
||||
.ms-confirm { display: flex; gap: 8px; }
|
||||
.pz-btn.ms-delete { color: var(--pz-danger); padding-left: 0; }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) { .ms-chip, .ms-photo-add { transition: none; } }
|
||||
@@ -0,0 +1,224 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { X, ImagePlus } from 'lucide-react'
|
||||
import { t } from '../i18n/index.js'
|
||||
import { createLifeEvent, updateLifeEvent, deleteLifeEvent } from '../api/treeApi.js'
|
||||
import { DESCRIBED_TYPES, eventTitle } from '../utils/lifeTimeline.js'
|
||||
import './MomentSheet.css'
|
||||
|
||||
// Fiche « Ajouter un moment » de l'onglet Vie : quoi, quand, où, une photo. La date exacte, la fin,
|
||||
// la source et la note restent dans « Plus de détails ». Sert aussi à modifier un moment existant.
|
||||
|
||||
// Suggestions touchables : le texte exact devient le type correspondant (exporté en GEDCOM sous sa balise)
|
||||
const SUGGESTIONS = [
|
||||
{ label: t('Baptême'), type: 'baptism' },
|
||||
{ label: t('Déménagement'), type: 'residence' },
|
||||
{ label: t('Diplôme'), type: 'graduation' },
|
||||
{ label: t('Service militaire'), type: 'military' },
|
||||
{ label: t('Retraite'), type: 'retirement' },
|
||||
]
|
||||
|
||||
const yearOf = (value) => String(value ?? '').match(/^(\d{4})/)?.[1] || ''
|
||||
const exactDay = (value) => (/^\d{4}-\d{2}-\d{2}$/.test(String(value ?? '')) && !String(value).endsWith('-01-01') ? value : '')
|
||||
|
||||
export default function MomentSheet({ person, event = null, treeId, token, medias = [], onUploadPhoto, onClose, onSaved }) {
|
||||
const editing = Boolean(event)
|
||||
const [what, setWhat] = useState(() => (event ? eventTitle(event) : ''))
|
||||
const [year, setYear] = useState(() => yearOf(event?.date))
|
||||
const [approx, setApprox] = useState(() => ['about', 'estimated', 'calculated', 'between'].includes(event?.datePrecision))
|
||||
const [place, setPlace] = useState(event?.place || '')
|
||||
const [day, setDay] = useState(() => exactDay(event?.date))
|
||||
const [endYear, setEndYear] = useState(() => yearOf(event?.dateEnd))
|
||||
const [sources, setSources] = useState(event?.sources || '')
|
||||
const [notes, setNotes] = useState(event?.notes || '')
|
||||
const [mediaId, setMediaId] = useState(event?.mediaId || null)
|
||||
const [file, setFile] = useState(null)
|
||||
const [preview, setPreview] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [confirmDelete, setConfirmDelete] = useState(false)
|
||||
const whatRef = useRef(null)
|
||||
const fileRef = useRef(null)
|
||||
const hasDetails = Boolean(day || endYear || sources || notes)
|
||||
|
||||
useEffect(() => { whatRef.current?.focus() }, [])
|
||||
useEffect(() => {
|
||||
const onKey = (e) => { if (e.key === 'Escape' && !busy) onClose() }
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [busy, onClose])
|
||||
useEffect(() => {
|
||||
if (!file) { setPreview(''); return undefined }
|
||||
const url = URL.createObjectURL(file)
|
||||
setPreview(url)
|
||||
return () => URL.revokeObjectURL(url)
|
||||
}, [file])
|
||||
|
||||
const linkedMedia = mediaId ? medias.find((m) => String(m.id) === String(mediaId)) : null
|
||||
const yearValid = !year || /^\d{4}$/.test(year)
|
||||
const endValid = !endYear || (/^\d{4}$/.test(endYear) && (!year || Number(endYear) >= Number(year)))
|
||||
const canSave = what.trim().length > 0 && yearValid && endValid && !busy
|
||||
|
||||
const buildPayload = (photoId) => {
|
||||
const text = what.trim()
|
||||
const suggestion = SUGGESTIONS.find((s) => s.label.toLowerCase() === text.toLowerCase())
|
||||
const type = editing ? event.type : (suggestion?.type || 'custom')
|
||||
const textField = DESCRIBED_TYPES.includes(type) ? 'description' : 'label'
|
||||
// Une suggestion reprise telle quelle n'a pas besoin de libellé : le type suffit
|
||||
const textValue = !editing && suggestion ? null : text
|
||||
const start = day || year || null
|
||||
let datePrecision = null
|
||||
if (start && endYear) datePrecision = approx ? 'between' : 'from'
|
||||
else if (start && approx && !day) datePrecision = 'about'
|
||||
return {
|
||||
...(editing ? {} : { type }),
|
||||
[textField]: textValue,
|
||||
...(textField === 'description' ? { label: null } : {}),
|
||||
date: start,
|
||||
dateEnd: start && endYear ? endYear : null,
|
||||
datePrecision,
|
||||
place: place.trim() || null,
|
||||
sources: sources.trim() || null,
|
||||
notes: notes.trim() || null,
|
||||
mediaId: photoId,
|
||||
}
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
if (!canSave) return
|
||||
setBusy(true)
|
||||
setError('')
|
||||
try {
|
||||
let photoId = mediaId
|
||||
if (file && onUploadPhoto) {
|
||||
const created = await onUploadPhoto(person.id, file, [what.trim(), year].filter(Boolean).join(', '))
|
||||
photoId = created?.id || null
|
||||
}
|
||||
const payload = buildPayload(photoId)
|
||||
if (editing) await updateLifeEvent(treeId, event.id, payload, token)
|
||||
else await createLifeEvent(treeId, person.id, payload, token)
|
||||
onSaved()
|
||||
} catch (err) {
|
||||
setError(err?.message && !/^request_failed|^invalid_/.test(err.message) ? err.message : t('L’enregistrement n’a pas abouti. Réessayez dans un instant.'))
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const remove = async () => {
|
||||
setBusy(true)
|
||||
setError('')
|
||||
try {
|
||||
await deleteLifeEvent(treeId, event.id, token)
|
||||
onSaved()
|
||||
} catch {
|
||||
setError(t('La suppression n’a pas abouti. Réessayez dans un instant.'))
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return createPortal(
|
||||
<div className="pz-overlay ms-overlay" onMouseDown={(e) => { if (e.target === e.currentTarget && !busy) onClose() }}>
|
||||
<div className="pz-modal ms" role="dialog" aria-modal="true" aria-labelledby="ms-title">
|
||||
<button type="button" className="pz-btn pz-btn--ghost pz-btn--icon pz-modal-close" onClick={onClose} aria-label={t('Fermer')} disabled={busy}>
|
||||
<X size={18} strokeWidth={1.8} />
|
||||
</button>
|
||||
<div className="pz-modal-head">
|
||||
<h2 id="ms-title" className="pz-title ms-title">
|
||||
{editing ? t('Modifier ce moment') : t('Ajouter à la vie de {name}', { name: person.firstName })}
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
<form className="ms-form" onSubmit={(e) => { e.preventDefault(); save() }}>
|
||||
<div className="pz-field">
|
||||
<label htmlFor="ms-what">{t('Quoi ?')}</label>
|
||||
<input id="ms-what" ref={whatRef} value={what} maxLength={120} onChange={(e) => setWhat(e.target.value)} placeholder={t('Service militaire, premier emploi, départ pour Paris…')} />
|
||||
{!editing && (
|
||||
<div className="ms-chips">
|
||||
{SUGGESTIONS.map((s) => (
|
||||
<button key={s.type} type="button" className={`ms-chip${what === s.label ? ' is-on' : ''}`} onClick={() => setWhat(s.label)}>{s.label}</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="ms-row">
|
||||
<div className="pz-field ms-year">
|
||||
<label htmlFor="ms-year">{t('Quand ?')}</label>
|
||||
<input id="ms-year" inputMode="numeric" maxLength={4} value={year} onChange={(e) => setYear(e.target.value.replace(/\D/g, ''))} placeholder={t('Année')} aria-invalid={!yearValid || undefined} disabled={Boolean(day)} />
|
||||
</div>
|
||||
<label className="ms-check">
|
||||
<input type="checkbox" checked={approx} onChange={(e) => setApprox(e.target.checked)} disabled={Boolean(day) && !endYear} />
|
||||
{t('environ')}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="pz-field">
|
||||
<label htmlFor="ms-place">{t('Où ?')} <span className="ms-optional">{t('facultatif')}</span></label>
|
||||
<input id="ms-place" value={place} maxLength={300} onChange={(e) => setPlace(e.target.value)} placeholder={t('Ville ou adresse')} />
|
||||
</div>
|
||||
|
||||
<div className="ms-photo">
|
||||
{(preview || linkedMedia?.url) ? (
|
||||
<div className="ms-photo-current">
|
||||
<img src={preview || linkedMedia.url} alt="" />
|
||||
<button type="button" className="pz-btn pz-btn--ghost" onClick={() => { setFile(null); setMediaId(null) }} disabled={busy}>
|
||||
{t('Retirer la photo')}
|
||||
</button>
|
||||
</div>
|
||||
) : onUploadPhoto && (
|
||||
<button type="button" className="ms-photo-add" onClick={() => fileRef.current?.click()} disabled={busy}>
|
||||
<ImagePlus size={16} strokeWidth={1.8} />
|
||||
{t('Une photo')} <span className="ms-optional">{t('facultatif')}</span>
|
||||
</button>
|
||||
)}
|
||||
<input ref={fileRef} type="file" accept="image/*" hidden onChange={(e) => { setFile(e.target.files?.[0] || null); e.target.value = '' }} />
|
||||
</div>
|
||||
|
||||
<details className="ms-more" open={hasDetails || undefined}>
|
||||
<summary>{t('Plus de détails')}</summary>
|
||||
<div className="ms-more-body">
|
||||
<div className="ms-row">
|
||||
<div className="pz-field">
|
||||
<label htmlFor="ms-day">{t('Date exacte')}</label>
|
||||
<input id="ms-day" type="date" value={day} onChange={(e) => { setDay(e.target.value); if (e.target.value) setYear(e.target.value.slice(0, 4)) }} />
|
||||
</div>
|
||||
<div className="pz-field ms-year">
|
||||
<label htmlFor="ms-end">{t('Jusqu’en')}</label>
|
||||
<input id="ms-end" inputMode="numeric" maxLength={4} value={endYear} onChange={(e) => setEndYear(e.target.value.replace(/\D/g, ''))} placeholder={t('Année')} aria-invalid={!endValid || undefined} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="pz-field">
|
||||
<label htmlFor="ms-sources">{t('Source')}</label>
|
||||
<textarea id="ms-sources" rows={2} value={sources} maxLength={4000} onChange={(e) => setSources(e.target.value)} placeholder={t('Registre, acte, archive, témoignage… une par ligne')} />
|
||||
</div>
|
||||
<div className="pz-field">
|
||||
<label htmlFor="ms-notes">{t('Note')}</label>
|
||||
<textarea id="ms-notes" rows={2} value={notes} maxLength={4000} onChange={(e) => setNotes(e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
{error && <p className="pz-error" role="alert">{error}</p>}
|
||||
|
||||
<div className={`pz-modal-actions${editing ? ' pz-modal-actions--split' : ''}`}>
|
||||
{editing && (confirmDelete ? (
|
||||
<span className="ms-confirm">
|
||||
<button type="button" className="pz-btn pz-btn--danger" onClick={remove} disabled={busy}>{t('Supprimer')}</button>
|
||||
<button type="button" className="pz-btn pz-btn--ghost" onClick={() => setConfirmDelete(false)} disabled={busy}>{t('Garder')}</button>
|
||||
</span>
|
||||
) : (
|
||||
<button type="button" className="pz-btn pz-btn--ghost ms-delete" onClick={() => setConfirmDelete(true)} disabled={busy}>{t('Supprimer ce moment')}</button>
|
||||
))}
|
||||
<span className="ms-actions-end">
|
||||
<button type="button" className="pz-btn pz-btn--ghost" onClick={onClose} disabled={busy}>{t('Annuler')}</button>
|
||||
<button type="submit" className="pz-btn pz-btn--primary" disabled={!canSave}>
|
||||
{busy ? t('Enregistrement…') : editing ? t('Enregistrer') : t('Ajouter')}
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
import { useState, useEffect, useRef, forwardRef } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { Save, Trash2, Plus, X, Search, Check, Play, ImagePlus, Sparkles, ChevronLeft, ChevronRight } from 'lucide-react'
|
||||
import { getParents, getChildren, getPersonUnions, getPersonMedias, filiations, persons, unions } from '../data/mockData'
|
||||
import { getParents, getChildren, getPersonUnions, getPersonMedias, getDemoLife, filiations, persons, unions } from '../data/mockData'
|
||||
import { fetchPersonLife } from '../api/treeApi.js'
|
||||
import LifeTimeline from './LifeTimeline.jsx'
|
||||
import MomentSheet from './MomentSheet.jsx'
|
||||
import { fetchImmichConfig } from '../api/immichApi.js'
|
||||
import GeoMediaThumbnail from './GeoMediaThumbnail'
|
||||
import ImmichFacePanel from './ImmichFacePanel.jsx'
|
||||
@@ -54,9 +57,35 @@ const PersonCard = ({
|
||||
relationActionError = '',
|
||||
siblingPlace = null,
|
||||
onMoveSibling,
|
||||
onUploadMomentPhoto,
|
||||
}) => {
|
||||
// Souvenirs d'abord quand il y en a, ou quand on peut en ajouter : c'est là qu'est le bouton
|
||||
const [tab, setTab] = useState(() => (getPersonMedias(person.id).length > 0 || canManageMedia ? 'medias' : 'infos'))
|
||||
const [lifeState, setLifeState] = useState({ personId: null, data: null, loading: false, failed: false })
|
||||
|
||||
const lifeRequestedFor = useRef(null)
|
||||
// Fiche « Ajouter un moment » : null fermée, {} pour ajouter, { event } pour modifier
|
||||
const [momentSheet, setMomentSheet] = useState(null)
|
||||
const [lifeRevision, setLifeRevision] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
if (tab !== 'vie' || lifeRequestedFor.current === person.id) return undefined
|
||||
lifeRequestedFor.current = person.id
|
||||
if (!treeId || !immichToken) {
|
||||
setLifeState({ personId: person.id, data: getDemoLife(person.id), loading: false, failed: false })
|
||||
return undefined
|
||||
}
|
||||
let cancelled = false
|
||||
// Retour sur l'onglet : on garde la frise affichée pendant qu'elle se rafraîchit
|
||||
setLifeState((prev) => (prev.personId === person.id && prev.data ? prev : { personId: person.id, data: null, loading: true, failed: false }))
|
||||
fetchPersonLife(treeId, person.id, immichToken)
|
||||
.then((data) => { if (!cancelled) setLifeState({ personId: person.id, data, loading: false, failed: false }) })
|
||||
.catch(() => { if (!cancelled) setLifeState({ personId: person.id, data: null, loading: false, failed: true }) })
|
||||
return () => {
|
||||
cancelled = true
|
||||
lifeRequestedFor.current = null
|
||||
}
|
||||
}, [tab, person.id, treeId, immichToken, lifeRevision])
|
||||
|
||||
// État local pour les modifications en mode édition
|
||||
const [edits, setEdits] = useState({})
|
||||
@@ -88,6 +117,7 @@ const PersonCard = ({
|
||||
setRelationSearchQuery('')
|
||||
setSaveSuccess(false)
|
||||
setShowSourceMenu(false)
|
||||
setMomentSheet(null)
|
||||
}, [person.id])
|
||||
|
||||
// Connexion Immich de l'arbre : métadonnées sans clé. Une erreur (rôle périmé, réseau) se
|
||||
@@ -239,6 +269,27 @@ const PersonCard = ({
|
||||
})()
|
||||
const personMedias = getPersonMedias(person.id)
|
||||
|
||||
// Frise de vie : la famille vient de l'arbre déjà chargé, les événements de la route /life,
|
||||
// demandée seulement à l'ouverture de l'onglet (la démo a ses propres données)
|
||||
const siblingsList = (() => {
|
||||
const seen = new Map()
|
||||
for (const parent of parentsList) {
|
||||
for (const child of getChildren(parent.id)) if (child.id !== person.id) seen.set(child.id, child)
|
||||
}
|
||||
return [...seen.values()]
|
||||
})()
|
||||
// Ajouter un moment : administrateurs, sur un arbre en ligne (la démo reste en lecture)
|
||||
const canEditLife = Boolean(isAdmin && onUploadMomentPhoto && treeId && immichToken)
|
||||
const lifeFamily = {
|
||||
parents: parentsList,
|
||||
children: childrenList,
|
||||
siblings: siblingsList,
|
||||
unions: personUnions.map((union) => ({
|
||||
...union,
|
||||
partner: persons.find((p) => p.id === (union.partner1Id === person.id ? union.partner2Id : union.partner1Id)) || null,
|
||||
})),
|
||||
}
|
||||
|
||||
// Filter persons for relation search (exclude current person + already linked)
|
||||
const getFilteredPersonsForRelation = (relationType) => {
|
||||
const excludeIds = new Set([person.id])
|
||||
@@ -498,6 +549,9 @@ const PersonCard = ({
|
||||
<button type="button" role="tab" aria-selected={tab === 'medias'} className="pz-tab" onClick={() => setTab('medias')}>
|
||||
{t('Souvenirs')}{personMedias.length > 0 ? ` · ${personMedias.length}` : ''}
|
||||
</button>
|
||||
<button type="button" role="tab" aria-selected={tab === 'vie'} className="pz-tab" onClick={() => setTab('vie')}>
|
||||
{t('Vie')}
|
||||
</button>
|
||||
<button type="button" role="tab" aria-selected={tab === 'infos'} className="pz-tab" onClick={() => setTab('infos')}>
|
||||
{t('Infos')}
|
||||
</button>
|
||||
@@ -581,6 +635,21 @@ const PersonCard = ({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Vie ── */}
|
||||
{tab === 'vie' && (
|
||||
<LifeTimeline
|
||||
person={person}
|
||||
family={lifeFamily}
|
||||
life={lifeState.personId === person.id ? lifeState.data : null}
|
||||
loading={lifeState.personId !== person.id || lifeState.loading}
|
||||
failed={lifeState.personId === person.id && lifeState.failed}
|
||||
medias={personMedias}
|
||||
canEdit={canEditLife}
|
||||
onAdd={() => setMomentSheet({})}
|
||||
onEdit={(event) => setMomentSheet({ event })}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* ── Infos ── */}
|
||||
{tab === 'infos' && (
|
||||
<div className="pc-infos">
|
||||
@@ -801,6 +870,20 @@ const PersonCard = ({
|
||||
onImmichChange={onImmichChange}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* ── Ajouter ou modifier un moment de l'onglet Vie (modale) ── */}
|
||||
{momentSheet && canEditLife && (
|
||||
<MomentSheet
|
||||
person={person}
|
||||
event={momentSheet.event || null}
|
||||
treeId={treeId}
|
||||
token={immichToken}
|
||||
medias={personMedias}
|
||||
onUploadPhoto={onUploadMomentPhoto}
|
||||
onClose={() => setMomentSheet(null)}
|
||||
onSaved={() => { setMomentSheet(null); setLifeRevision((r) => r + 1) }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -8,17 +8,17 @@ import { buildMediaUrl } from '../utils/mediaToken.js'
|
||||
|
||||
// Démo : noms et lieux restent français, les textes descriptifs sont traduits.
|
||||
export let persons = [
|
||||
{ id: 1, firstName: 'Jean', lastName: 'Dupont', birthYear: 1890, deathYear: 1965, isAlive: false, photo: '/demo/jean.webp', frameType: 'polaroid', birthPlace: 'Limoges', region: 'Haute-Vienne', profession: t('Menuisier'), nationality: t('Française'), note: t('Patriarche de la famille') },
|
||||
{ id: 2, firstName: 'Marie', lastName: 'Martin', birthYear: 1895, deathYear: 1970, isAlive: false, photo: '/demo/marie.webp', frameType: 'round', birthPlace: 'Brive-la-Gaillarde', region: 'Corrèze', profession: t('Couturière'), note: t('Atelier de couture rue du Commerce') },
|
||||
{ id: 3, firstName: 'Robert', lastName: 'Dupont', birthYear: 1920, deathYear: 1995, isAlive: false, photo: '/demo/robert.webp', frameType: 'rect', birthPlace: 'Limoges', region: 'Haute-Vienne', profession: t('Instituteur'), note: t("A enseigné 35 ans à l'école communale") },
|
||||
{ id: 4, firstName: 'André', lastName: 'Dupont', birthYear: 1923, deathYear: 2000, isAlive: false, photo: '/demo/andre.webp', frameType: 'polaroid', birthPlace: 'Limoges', region: 'Haute-Vienne', profession: t('Charpentier') },
|
||||
{ id: 5, firstName: 'Simone', lastName: 'Petit', birthYear: 1925, deathYear: 2010, isAlive: false, photo: '/demo/simone.webp', frameType: 'round', birthPlace: 'Guéret', region: 'Creuse', profession: t('Infirmière') },
|
||||
{ id: 9, firstName: 'Isabelle', lastName: 'Bernard', birthYear: 1928, isAlive: true, photo: '/demo/isabelle.webp', frameType: 'rect', birthPlace: 'Fort-de-France', region: 'Martinique', profession: t('Sage-femme'), note: t('Doyenne de la famille, vit à Brive') },
|
||||
{ id: 6, firstName: 'Jacques', lastName: 'Dupont', birthYear: 1945, deathYear: 2015, isAlive: false, photo: '/demo/jacques.webp', frameType: 'polaroid', birthPlace: 'Limoges', region: 'Haute-Vienne', profession: t('Journaliste'), note: t('Reporter au Populaire du Centre') },
|
||||
{ id: 7, firstName: 'Philippe', lastName: 'Dupont', birthYear: 1948, isAlive: true, photo: '/demo/philippe.webp', frameType: 'round', birthPlace: 'Limoges', region: 'Haute-Vienne', profession: t('Pharmacien') },
|
||||
{ id: 8, firstName: 'Sophie', lastName: 'Dupont', birthYear: 1960, isAlive: true, photo: '/demo/sophie.webp', frameType: 'rect', birthPlace: 'Brive-la-Gaillarde', region: 'Corrèze', profession: t('Architecte'), note: t('Cabinet d’architecture à Bordeaux') },
|
||||
{ id: 10, firstName: 'Thomas', lastName: 'Dupont', birthYear: 1962, isAlive: true, photo: '/demo/thomas.webp', frameType: 'polaroid', birthPlace: 'Brive-la-Gaillarde', region: 'Corrèze', profession: t('Vétérinaire') },
|
||||
{ id: 11, firstName: 'Claire', lastName: 'Dupont', birthYear: 1955, isAlive: true, photo: '/demo/claire.webp', birthPlace: 'Paris', region: 'Ile-de-France', profession: t('Enseignante') },
|
||||
{ id: 1, firstName: 'Jean', sex: 'male', lastName: 'Dupont', birthYear: 1890, deathYear: 1965, isAlive: false, photo: '/demo/jean.webp', frameType: 'polaroid', birthPlace: 'Limoges', region: 'Haute-Vienne', profession: t('Menuisier'), nationality: t('Française'), note: t('Patriarche de la famille') },
|
||||
{ id: 2, firstName: 'Marie', sex: 'female', lastName: 'Martin', birthYear: 1895, deathYear: 1970, isAlive: false, photo: '/demo/marie.webp', frameType: 'round', birthPlace: 'Brive-la-Gaillarde', region: 'Corrèze', profession: t('Couturière'), note: t('Atelier de couture rue du Commerce') },
|
||||
{ id: 3, firstName: 'Robert', sex: 'male', lastName: 'Dupont', birthYear: 1920, deathYear: 1995, isAlive: false, photo: '/demo/robert.webp', frameType: 'rect', birthPlace: 'Limoges', region: 'Haute-Vienne', profession: t('Instituteur'), note: t("A enseigné 35 ans à l'école communale") },
|
||||
{ id: 4, firstName: 'André', sex: 'male', lastName: 'Dupont', birthYear: 1923, deathYear: 2000, isAlive: false, photo: '/demo/andre.webp', frameType: 'polaroid', birthPlace: 'Limoges', region: 'Haute-Vienne', profession: t('Charpentier') },
|
||||
{ id: 5, firstName: 'Simone', sex: 'female', lastName: 'Petit', birthYear: 1925, deathYear: 2010, isAlive: false, photo: '/demo/simone.webp', frameType: 'round', birthPlace: 'Guéret', region: 'Creuse', profession: t('Infirmière') },
|
||||
{ id: 9, firstName: 'Isabelle', sex: 'female', lastName: 'Bernard', birthYear: 1928, isAlive: true, photo: '/demo/isabelle.webp', frameType: 'rect', birthPlace: 'Fort-de-France', region: 'Martinique', profession: t('Sage-femme'), note: t('Doyenne de la famille, vit à Brive') },
|
||||
{ id: 6, firstName: 'Jacques', sex: 'male', lastName: 'Dupont', birthYear: 1945, deathYear: 2015, isAlive: false, photo: '/demo/jacques.webp', frameType: 'polaroid', birthPlace: 'Limoges', region: 'Haute-Vienne', profession: t('Journaliste'), note: t('Reporter au Populaire du Centre') },
|
||||
{ id: 7, firstName: 'Philippe', sex: 'male', lastName: 'Dupont', birthYear: 1948, isAlive: true, photo: '/demo/philippe.webp', frameType: 'round', birthPlace: 'Limoges', region: 'Haute-Vienne', profession: t('Pharmacien') },
|
||||
{ id: 8, firstName: 'Sophie', sex: 'female', lastName: 'Dupont', birthYear: 1960, isAlive: true, photo: '/demo/sophie.webp', frameType: 'rect', birthPlace: 'Brive-la-Gaillarde', region: 'Corrèze', profession: t('Architecte'), note: t('Cabinet d’architecture à Bordeaux') },
|
||||
{ id: 10, firstName: 'Thomas', sex: 'male', lastName: 'Dupont', birthYear: 1962, isAlive: true, photo: '/demo/thomas.webp', frameType: 'polaroid', birthPlace: 'Brive-la-Gaillarde', region: 'Corrèze', profession: t('Vétérinaire') },
|
||||
{ id: 11, firstName: 'Claire', sex: 'female', lastName: 'Dupont', birthYear: 1955, isAlive: true, photo: '/demo/claire.webp', birthPlace: 'Paris', region: 'Ile-de-France', profession: t('Enseignante') },
|
||||
]
|
||||
|
||||
export let medias = [
|
||||
@@ -114,11 +114,36 @@ function mapRemotePersonToLocal(person, current = null) {
|
||||
region: person?.region || null,
|
||||
profession: person?.profession || null,
|
||||
nationality: person?.nationality || null,
|
||||
sex: person?.sex ?? current?.sex ?? null,
|
||||
photo: current?.photo || null,
|
||||
avatarFromImmich: person?.avatarFromImmich ?? false,
|
||||
}
|
||||
}
|
||||
|
||||
// Frise de vie de la démo (onglet Vie), au format de GET /trees/:id/persons/:personId/life. Personnes fictives.
|
||||
const DEMO_LIFE = {
|
||||
3: {
|
||||
person: { birthDatePrecision: null, deathPlace: 'Brive-la-Gaillarde', nickname: null },
|
||||
unions: [
|
||||
{ id: 'u2', startDate: '1943-06-12', startPlace: 'Limoges', startDatePrecision: null },
|
||||
{ id: 'u3', startDate: '1959-01-01', startPlace: 'Brive-la-Gaillarde', startDatePrecision: null },
|
||||
],
|
||||
events: [
|
||||
{ id: 'd1', type: 'birth', sources: t('Registre des naissances de Limoges, acte n° 412') },
|
||||
{ id: 'd2', type: 'baptism', date: '1920-03-21', place: 'Saint-Michel-des-Lions, Limoges' },
|
||||
{ id: 'd3', type: 'education', date: '1938-01-01', dateEnd: '1940-01-01', datePrecision: 'from', description: t('École normale d’instituteurs'), place: 'Limoges' },
|
||||
{ id: 'd4', type: 'military', date: '1940-01-01', dateEnd: '1942-01-01', datePrecision: 'between', notes: t('Affecté au 63e régiment d’infanterie.') },
|
||||
{ id: 'd5', type: 'marriage', unionId: 'u2', sources: t('Registre des mariages de Limoges') },
|
||||
{ id: 'd6', type: 'occupation', date: '1946-01-01', dateEnd: '1981-01-01', datePrecision: 'from', description: t('Instituteur à l’école communale'), place: 'Limoges' },
|
||||
{ id: 'd7', type: 'retirement', date: '1981-01-01' },
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
export function getDemoLife(personId) {
|
||||
return DEMO_LIFE[personId] || null
|
||||
}
|
||||
|
||||
export function resetToDemoData() {
|
||||
persons = JSON.parse(JSON.stringify(INITIAL_PERSONS))
|
||||
medias = JSON.parse(JSON.stringify(INITIAL_MEDIAS))
|
||||
|
||||
@@ -166,6 +166,34 @@ export function useMediaManager({
|
||||
}
|
||||
}
|
||||
|
||||
// Photo d'un moment de l'onglet Vie : envoyée comme un souvenir de la personne, puis rattachée au moment.
|
||||
// Renvoie le souvenir créé ; une erreur remonte avec un message lisible.
|
||||
const uploadMomentPhoto = async (personId, file, caption) => {
|
||||
if (!canEditCurrentTree || !treeContext.treeId || !treeContext.accessToken) throw new Error(t('Action non autorisée.'))
|
||||
const validationError = validateMediaFile(file, 'photo', {})
|
||||
if (validationError) throw new Error(validationError)
|
||||
try {
|
||||
const created = await uploadPersonMedia(
|
||||
treeContext.treeId,
|
||||
personId,
|
||||
{
|
||||
type: 'photo',
|
||||
fileName: file.name || 'photo.jpg',
|
||||
mimeType: getUploadMimeType(file, 'photo'),
|
||||
sizeBytes: file.size,
|
||||
dataBase64: await fileToBase64(file),
|
||||
caption: caption || null,
|
||||
source: null,
|
||||
},
|
||||
treeContext.accessToken,
|
||||
)
|
||||
await refreshAfterMediaMutation(personId)
|
||||
return created
|
||||
} catch (error) {
|
||||
throw new Error(getAccountErrorMessage(error), { cause: error })
|
||||
}
|
||||
}
|
||||
|
||||
const handleMovePersonMedia = async (mediaId, direction) => {
|
||||
if (!canEditCurrentTree || !selectedPerson || !treeContext.treeId || !treeContext.accessToken) {
|
||||
return
|
||||
@@ -250,6 +278,7 @@ export function useMediaManager({
|
||||
handleCloseMediaManager,
|
||||
handleUploadPersonMedia,
|
||||
handleMovePersonMedia,
|
||||
uploadMomentPhoto,
|
||||
handleDeletePersonMedia,
|
||||
resetMediaManager,
|
||||
}
|
||||
|
||||
@@ -296,4 +296,90 @@ export default {
|
||||
'A portrait is already in place. Linking this Immich person will replace the current portrait and delete its file.',
|
||||
'Garder le portrait actuel': 'Keep the current portrait',
|
||||
'Remplacer le portrait et associer': 'Replace the portrait and link',
|
||||
// Onglet Vie (frise de vie)
|
||||
'1 source': '1 source',
|
||||
'{n} sources': '{n} sources',
|
||||
'Pas encore de date connue pour {name}.': 'No known dates for {name} yet.',
|
||||
'Les dates de naissance, d’union et de décès, et celles de sa famille, apparaîtront ici.': 'Dates of birth, marriage and death, and those of their family, will show up here.',
|
||||
'Les autres événements n’ont pas pu être chargés.': 'The other events could not be loaded.',
|
||||
'Vie': 'Life',
|
||||
'Registre des naissances de Limoges, acte n° 412': 'Limoges birth register, entry no. 412',
|
||||
'École normale d’instituteurs': 'Teacher training college',
|
||||
'Affecté au 63e régiment d’infanterie.': 'Assigned to the 63rd infantry regiment.',
|
||||
'Registre des mariages de Limoges': 'Limoges marriage register',
|
||||
'Instituteur à l’école communale': 'Teacher at the village school',
|
||||
'Baptême': 'Baptism',
|
||||
'Inhumation': 'Burial',
|
||||
'Crémation': 'Cremation',
|
||||
'Résidence': 'Residence',
|
||||
'Études': 'Education',
|
||||
'Religion': 'Religion',
|
||||
'Confirmation': 'Confirmation',
|
||||
'Première communion': 'First communion',
|
||||
'Bar-mitzvah': 'Bar mitzvah',
|
||||
'Bat-mitzvah': 'Bat mitzvah',
|
||||
'Ordination': 'Ordination',
|
||||
'Émigration': 'Emigration',
|
||||
'Immigration': 'Immigration',
|
||||
'Naturalisation': 'Naturalisation',
|
||||
'Recensement': 'Census',
|
||||
'Biens': 'Property',
|
||||
'Retraite': 'Retirement',
|
||||
'Testament': 'Will',
|
||||
'Succession': 'Probate',
|
||||
'Santé': 'Health',
|
||||
'Divorce': 'Divorce',
|
||||
'Demande de divorce': 'Divorce filed',
|
||||
'Annulation du mariage': 'Annulment',
|
||||
'Fiançailles': 'Engagement',
|
||||
'Bans du mariage': 'Marriage banns',
|
||||
'Contrat de mariage': 'Marriage contract',
|
||||
'Autorisation de mariage': 'Marriage licence',
|
||||
'Accord de mariage': 'Marriage settlement',
|
||||
'vers {year}': 'about {year}',
|
||||
'avant {year}': 'before {year}',
|
||||
'après {year}': 'after {year}',
|
||||
'entre {year} et {end}': 'between {year} and {end}',
|
||||
'jusqu’en {end}': 'until {end}',
|
||||
'jusqu’en {year}': 'until {year}',
|
||||
'Décès de son père {name}': 'Death of their father, {name}',
|
||||
'Décès de sa mère {name}': 'Death of their mother, {name}',
|
||||
'Décès de {name}, son parent': 'Death of {name}, a parent',
|
||||
'Naissance de son frère {name}': 'Birth of a brother, {name}',
|
||||
'Naissance de sa sœur {name}': 'Birth of a sister, {name}',
|
||||
'Naissance de {name}, sa fratrie': 'Birth of a sibling, {name}',
|
||||
'Naissance à {place}': 'Born in {place}',
|
||||
'Conjoint inconnu': 'Unknown partner',
|
||||
'Union avec {name}': 'Partnership with {name}',
|
||||
'Épouse {name}': 'Marries {name}',
|
||||
'Fin de l’union avec {name}': 'End of the relationship with {name}',
|
||||
'Décès de {name}': 'Death of {name}',
|
||||
'Événement': 'Event',
|
||||
'Naissance de {name}': 'Birth of {name}',
|
||||
'Décès à {place}': 'Died in {place}',
|
||||
'Ajouter un moment': 'Add a moment',
|
||||
'Modifier « {title} »': 'Edit “{title}”',
|
||||
'Déménagement': 'Move',
|
||||
'L’enregistrement n’a pas abouti. Réessayez dans un instant.': 'Saving did not go through. Try again in a moment.',
|
||||
'La suppression n’a pas abouti. Réessayez dans un instant.': 'Deleting did not go through. Try again in a moment.',
|
||||
'Modifier ce moment': 'Edit this moment',
|
||||
'Ajouter à la vie de {name}': 'Add to {name}’s life',
|
||||
'Quoi ?': 'What?',
|
||||
'Service militaire, premier emploi, départ pour Paris…': 'Military service, first job, moving to Paris…',
|
||||
'Quand ?': 'When?',
|
||||
'Année': 'Year',
|
||||
'environ': 'about',
|
||||
'Où ?': 'Where?',
|
||||
'Ville ou adresse': 'Town or address',
|
||||
'Retirer la photo': 'Remove the photo',
|
||||
'Une photo': 'A photo',
|
||||
'Plus de détails': 'More details',
|
||||
'Date exacte': 'Exact date',
|
||||
'Jusqu’en': 'Until',
|
||||
'Registre, acte, archive, témoignage… une par ligne': 'Register, record, archive, account… one per line',
|
||||
'Note': 'Note',
|
||||
'Garder': 'Keep',
|
||||
'Supprimer ce moment': 'Delete this moment',
|
||||
'Enregistrement…': 'Saving…',
|
||||
'Action non autorisée.': 'Not allowed.',
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
// Frise de vie d'une personne (onglet Vie de la fiche).
|
||||
//
|
||||
// Trois sources, rangées par date : la naissance, les unions et le décès, qui servent de grands repères ;
|
||||
// les événements importés ou saisis (baptême, métiers, service militaire…) ; et la famille proche que
|
||||
// l'arbre connaît déjà (naissance des enfants et des frères et sœurs, décès des parents, du conjoint, d'un
|
||||
// enfant), limitée aux années où la personne a vécu. Une fiche sans aucun événement a donc déjà une frise.
|
||||
|
||||
import { t, dateLocale } from '../i18n/index.js'
|
||||
import { formatPlace } from './place.js'
|
||||
|
||||
const EVENT_LABELS = {
|
||||
baptism: t('Baptême'),
|
||||
burial: t('Inhumation'),
|
||||
cremation: t('Crémation'),
|
||||
residence: t('Résidence'),
|
||||
occupation: t('Métier'),
|
||||
education: t('Études'),
|
||||
graduation: t('Diplôme'),
|
||||
degree: t('Diplôme'),
|
||||
religion: t('Religion'),
|
||||
confirmation: t('Confirmation'),
|
||||
first_communion: t('Première communion'),
|
||||
bar_mitzvah: t('Bar-mitzvah'),
|
||||
bat_mitzvah: t('Bat-mitzvah'),
|
||||
ordination: t('Ordination'),
|
||||
adoption: t('Adoption'),
|
||||
emigration: t('Émigration'),
|
||||
immigration: t('Immigration'),
|
||||
naturalization: t('Naturalisation'),
|
||||
census: t('Recensement'),
|
||||
title: t('Titre'),
|
||||
property: t('Biens'),
|
||||
retirement: t('Retraite'),
|
||||
will: t('Testament'),
|
||||
probate: t('Succession'),
|
||||
military: t('Service militaire'),
|
||||
medical: t('Santé'),
|
||||
divorce: t('Divorce'),
|
||||
divorce_filed: t('Demande de divorce'),
|
||||
annulment: t('Annulation du mariage'),
|
||||
engagement: t('Fiançailles'),
|
||||
marriage_banns: t('Bans du mariage'),
|
||||
marriage_contract: t('Contrat de mariage'),
|
||||
marriage_license: t('Autorisation de mariage'),
|
||||
marriage_settlement: t('Accord de mariage'),
|
||||
}
|
||||
|
||||
// Types dont la description dit déjà ce que c'est (« Instituteur », « École normale »)
|
||||
export const DESCRIBED_TYPES = ['occupation', 'education', 'graduation', 'degree', 'title']
|
||||
|
||||
// Titre d'un événement : son libellé s'il en a un, sinon le nom du type, complété de la description
|
||||
export function eventTitle(event) {
|
||||
if (DESCRIBED_TYPES.includes(event.type) && event.description) return event.description
|
||||
const base = event.label || (event.type === 'custom' ? '' : EVENT_LABELS[event.type]) || t('Événement')
|
||||
return event.description ? `${base}, ${event.description}` : base
|
||||
}
|
||||
|
||||
const yearOf = (value) => {
|
||||
const match = String(value ?? '').match(/^(\d{4})/)
|
||||
return match ? Number(match[1]) : null
|
||||
}
|
||||
|
||||
const fullName = (p) => [p?.firstName, p?.lastName].filter(Boolean).join(' ')
|
||||
|
||||
// « 12 mars » pour une date complète, rien pour une année seule (stockée au 1er janvier)
|
||||
function dayMonth(value) {
|
||||
const match = String(value ?? '').match(/^(\d{4})-(\d{2})-(\d{2})/)
|
||||
if (!match || (match[2] === '01' && match[3] === '01')) return ''
|
||||
const date = new Date(Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3])))
|
||||
return date.toLocaleDateString(dateLocale, { day: 'numeric', month: 'long', timeZone: 'UTC' })
|
||||
}
|
||||
|
||||
// La date telle qu'on la dit : « vers 1879 », « entre 1914 et 1918 », « jusqu'en 1981 »
|
||||
export function describeDate(date, end, precision) {
|
||||
const year = yearOf(date)
|
||||
const endYear = yearOf(end)
|
||||
if (!year) return ''
|
||||
switch (precision) {
|
||||
case 'about':
|
||||
case 'estimated':
|
||||
case 'calculated':
|
||||
return t('vers {year}', { year })
|
||||
case 'before': return t('avant {year}', { year })
|
||||
case 'after': return t('après {year}', { year })
|
||||
case 'between': return endYear ? t('entre {year} et {end}', { year, end: endYear }) : t('après {year}', { year })
|
||||
case 'from': return endYear ? t('jusqu’en {end}', { end: endYear }) : t('depuis {year}', { year })
|
||||
case 'to': return t('jusqu’en {year}', { year })
|
||||
default: return dayMonth(date)
|
||||
}
|
||||
}
|
||||
|
||||
const ageAt = (birthYear, year) => (birthYear && year && year > birthYear ? t('{age} ans', { age: year - birthYear }) : '')
|
||||
const joinMeta = (...parts) => parts.filter(Boolean).join(' · ')
|
||||
|
||||
const parentWord = (p) => {
|
||||
if (p.sex === 'male' || p.sex === 'M') return t('Décès de son père {name}', { name: p.firstName })
|
||||
if (p.sex === 'female' || p.sex === 'F') return t('Décès de sa mère {name}', { name: p.firstName })
|
||||
return t('Décès de {name}, son parent', { name: p.firstName })
|
||||
}
|
||||
|
||||
const siblingWord = (p) => {
|
||||
if (p.sex === 'male' || p.sex === 'M') return t('Naissance de son frère {name}', { name: p.firstName })
|
||||
if (p.sex === 'female' || p.sex === 'F') return t('Naissance de sa sœur {name}', { name: p.firstName })
|
||||
return t('Naissance de {name}, sa fratrie', { name: p.firstName })
|
||||
}
|
||||
|
||||
/**
|
||||
* @param person personne de la fiche (birthDate, deathDate, birthPlace, birthYear, deathYear)
|
||||
* @param family { parents, children, siblings, unions: [{ id, partner, startYear, endYear, unionType }] }
|
||||
* @param life réponse de GET /trees/:id/persons/:personId/life, ou null tant qu'elle n'est pas là
|
||||
* @returns entrées triées { key, year, kind: 'mile' | 'minor' | 'fam', title, meta, note, sources }
|
||||
*/
|
||||
export function buildLifeTimeline(person, family = {}, life = null) {
|
||||
const details = life?.person || {}
|
||||
const lifeUnions = new Map((life?.unions || []).map((u) => [String(u.id), u]))
|
||||
const events = life?.events || []
|
||||
const birthYear = yearOf(person.birthDate) ?? person.birthYear ?? null
|
||||
const deathYear = yearOf(person.deathDate) ?? person.deathYear ?? null
|
||||
const lastYear = deathYear ?? new Date().getFullYear()
|
||||
const within = (year) => year && (!birthYear || year >= birthYear) && year <= lastYear
|
||||
const sourcesOf = (type, unionId = null) => events.find((e) => e.type === type && (unionId ? String(e.unionId) === String(unionId) : !e.unionId))
|
||||
const out = []
|
||||
|
||||
if (birthYear) {
|
||||
const place = formatPlace(person.birthPlace || '')
|
||||
const extra = sourcesOf('birth')
|
||||
out.push({
|
||||
key: 'birth', year: birthYear, order: 0, kind: 'mile',
|
||||
title: place ? t('Naissance à {place}', { place: place.split(',')[0] }) : t('Naissance'),
|
||||
meta: describeDate(person.birthDate, details.birthDateEnd, details.birthDatePrecision),
|
||||
note: extra?.notes || '', sources: extra?.sources || '',
|
||||
})
|
||||
}
|
||||
|
||||
for (const union of family.unions || []) {
|
||||
const detail = lifeUnions.get(String(union.id)) || {}
|
||||
const year = yearOf(detail.startDate) ?? union.startYear
|
||||
const partnerName = union.partner ? fullName(union.partner) : t('Conjoint inconnu')
|
||||
const place = formatPlace(detail.startPlace || '')
|
||||
const extra = sourcesOf('marriage', union.id)
|
||||
out.push({
|
||||
key: `union-${union.id}`, year, order: 2, kind: 'mile',
|
||||
title: union.unionType === 'union' ? t('Union avec {name}', { name: partnerName }) : t('Épouse {name}', { name: partnerName }),
|
||||
meta: joinMeta(place, detail.startDatePrecision ? describeDate(detail.startDate, null, detail.startDatePrecision) : '', ageAt(birthYear, year)),
|
||||
note: extra?.notes || '', sources: extra?.sources || '',
|
||||
})
|
||||
const hasEndEvent = events.some((e) => String(e.unionId) === String(union.id) && ['divorce', 'annulment'].includes(e.type))
|
||||
if (union.endYear && !hasEndEvent) {
|
||||
out.push({ key: `union-end-${union.id}`, year: union.endYear, order: 3, kind: 'minor', title: t('Fin de l’union avec {name}', { name: union.partner?.firstName || partnerName }), meta: ageAt(birthYear, union.endYear) })
|
||||
}
|
||||
if (union.partner && within(yearOf(union.partner.deathDate) ?? union.partner.deathYear)) {
|
||||
const year2 = yearOf(union.partner.deathDate) ?? union.partner.deathYear
|
||||
out.push({ key: `partner-death-${union.id}`, year: year2, order: 4, kind: 'fam', title: t('Décès de {name}', { name: union.partner.firstName }) })
|
||||
}
|
||||
}
|
||||
|
||||
for (const event of events) {
|
||||
if (['birth', 'death', 'marriage'].includes(event.type)) continue
|
||||
const year = yearOf(event.date)
|
||||
let title = eventTitle(event)
|
||||
if (event.unionId) {
|
||||
const union = (family.unions || []).find((u) => String(u.id) === String(event.unionId))
|
||||
if (union?.partner && ['divorce', 'annulment', 'engagement', 'marriage_contract'].includes(event.type)) title = `${title} (${union.partner.firstName})`
|
||||
}
|
||||
out.push({
|
||||
key: `event-${event.id}`, year, order: 1, kind: 'minor', title,
|
||||
meta: joinMeta(formatPlace(event.place || ''), describeDate(event.date, event.dateEnd, event.datePrecision), ageAt(birthYear, year)),
|
||||
note: event.notes || '', sources: event.sources || '',
|
||||
mediaId: event.mediaId || null,
|
||||
// Seuls les moments propres à la personne se modifient depuis l'onglet (pas ceux d'une union)
|
||||
event: event.unionId ? null : event,
|
||||
})
|
||||
}
|
||||
|
||||
for (const child of family.children || []) {
|
||||
const year = yearOf(child.birthDate) ?? child.birthYear
|
||||
if (within(year)) out.push({ key: `child-${child.id}`, year, order: 5, kind: 'fam', title: t('Naissance de {name}', { name: child.firstName }) })
|
||||
const death = yearOf(child.deathDate) ?? child.deathYear
|
||||
if (within(death) && death !== deathYear) out.push({ key: `child-death-${child.id}`, year: death, order: 6, kind: 'fam', title: t('Décès de {name}', { name: child.firstName }) })
|
||||
}
|
||||
for (const sibling of family.siblings || []) {
|
||||
const year = yearOf(sibling.birthDate) ?? sibling.birthYear
|
||||
if (within(year) && year !== birthYear) out.push({ key: `sibling-${sibling.id}`, year, order: 5, kind: 'fam', title: siblingWord(sibling) })
|
||||
}
|
||||
for (const parent of family.parents || []) {
|
||||
const year = yearOf(parent.deathDate) ?? parent.deathYear
|
||||
if (within(year)) out.push({ key: `parent-death-${parent.id}`, year, order: 6, kind: 'fam', title: parentWord(parent) })
|
||||
}
|
||||
|
||||
if (deathYear) {
|
||||
const place = formatPlace(details.deathPlace || '')
|
||||
const extra = sourcesOf('death')
|
||||
out.push({
|
||||
key: 'death', year: deathYear, order: 9, kind: 'mile',
|
||||
title: place ? t('Décès à {place}', { place: place.split(',')[0] }) : t('Décès'),
|
||||
meta: joinMeta(describeDate(person.deathDate, details.deathDateEnd, details.deathDatePrecision), ageAt(birthYear, deathYear)),
|
||||
note: extra?.notes || '', sources: extra?.sources || '',
|
||||
})
|
||||
}
|
||||
|
||||
// Les entrées sans date restent en bas, dans l'ordre où elles sont arrivées
|
||||
return out
|
||||
.map((entry, index) => ({ ...entry, index }))
|
||||
.sort((a, b) => (a.year ?? Infinity) - (b.year ?? Infinity) || a.order - b.order || a.index - b.index)
|
||||
.map(({ order, index, ...entry }) => entry) // eslint-disable-line no-unused-vars
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildLifeTimeline, describeDate } from './lifeTimeline.js'
|
||||
|
||||
const robert = { id: 3, firstName: 'Robert', birthYear: 1920, deathYear: 1995, birthDate: '1920-03-12', deathDate: '1995-05-01', birthPlace: 'Limoges,87085,Haute-Vienne,,France,' }
|
||||
const simone = { id: 5, firstName: 'Simone', lastName: 'Petit', birthYear: 1925, deathYear: 2010 }
|
||||
const family = {
|
||||
parents: [{ id: 1, firstName: 'Jean', sex: 'male', deathYear: 1965 }, { id: 2, firstName: 'Marie', sex: 'female', deathYear: 2001 }],
|
||||
children: [{ id: 6, firstName: 'Jacques', birthYear: 1945, deathYear: 2015 }],
|
||||
siblings: [{ id: 4, firstName: 'André', sex: 'male', birthYear: 1923 }, { id: 9, firstName: 'Paul', sex: 'male', birthYear: 1915 }],
|
||||
unions: [{ id: 'u2', partner: simone, startYear: 1943, endYear: 1958, unionType: 'mariage' }],
|
||||
}
|
||||
const life = {
|
||||
person: { deathPlace: 'Brive-la-Gaillarde', birthDatePrecision: null },
|
||||
unions: [{ id: 'u2', startDate: '1943-06-12', startPlace: 'Limoges' }],
|
||||
events: [
|
||||
{ id: 'e1', type: 'birth', sources: 'Registre A\nRegistre B' },
|
||||
{ id: 'e2', type: 'occupation', date: '1946-01-01', dateEnd: '1981-01-01', datePrecision: 'from', description: 'Instituteur' },
|
||||
{ id: 'e3', type: 'custom', label: 'Militaire', date: '1940-01-01', dateEnd: '1942-01-01', datePrecision: 'between', notes: 'Verdun' },
|
||||
{ id: 'e4', type: 'residence', place: 'Rue des Écoles' },
|
||||
],
|
||||
}
|
||||
|
||||
describe('frise de vie', () => {
|
||||
const entries = buildLifeTimeline(robert, family, life)
|
||||
const titles = entries.map((e) => e.title)
|
||||
|
||||
it('range tout par date, les entrées sans date en bas', () => {
|
||||
expect(titles).toEqual([
|
||||
'Naissance à Limoges', 'Naissance de son frère André', 'Militaire', 'Épouse Simone Petit', 'Naissance de Jacques',
|
||||
'Instituteur', 'Fin de l’union avec Simone', 'Décès de son père Jean', 'Décès à Brive-la-Gaillarde', 'Résidence',
|
||||
])
|
||||
})
|
||||
|
||||
it('grands repères, précisions, âge et sources', () => {
|
||||
const birth = entries[0]
|
||||
expect(birth).toMatchObject({ kind: 'mile', year: 1920, sources: 'Registre A\nRegistre B' })
|
||||
expect(entries.find((e) => e.title === 'Instituteur').meta).toBe('jusqu’en 1981 · 26 ans')
|
||||
expect(entries.find((e) => e.title === 'Militaire')).toMatchObject({ kind: 'minor', meta: 'entre 1940 et 1942 · 20 ans', note: 'Verdun' })
|
||||
expect(entries.find((e) => e.title === 'Épouse Simone Petit')).toMatchObject({ kind: 'mile', meta: 'Limoges · 23 ans' })
|
||||
})
|
||||
|
||||
it('famille limitée à sa vie : frère aîné, mère morte après lui, enfant mort après lui écartés', () => {
|
||||
expect(titles.join()).not.toMatch(/Paul|Marie|Décès de Jacques/)
|
||||
})
|
||||
|
||||
it('sans données de la route, la famille et les repères suffisent', () => {
|
||||
const bare = buildLifeTimeline({ id: 1, firstName: 'X', birthYear: 1900 }, { children: [{ id: 2, firstName: 'Y', birthYear: 1930 }] }, null)
|
||||
expect(bare.map((e) => e.title)).toEqual(['Naissance', 'Naissance de Y'])
|
||||
expect(buildLifeTimeline({ id: 1, firstName: 'X' }, {}, null)).toEqual([])
|
||||
})
|
||||
|
||||
it('dit les dates comme on les dit', () => {
|
||||
expect(describeDate('1879-01-01', null, 'about')).toBe('vers 1879')
|
||||
expect(describeDate('1879-01-01', null, 'before')).toBe('avant 1879')
|
||||
expect(describeDate('1920-03-12', null, null)).toBe('12 mars')
|
||||
expect(describeDate('1920-01-01', null, null)).toBe('')
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user