"use client"; import Link from "next/link"; import { useParams, useRouter } from "next/navigation"; import { useCallback, useEffect, useMemo, useState } from "react"; import { api } from "@/lib/api/client"; import type { components } from "@/lib/api/schema"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Input } from "@/components/ui/input"; type Person = components["schemas"]["PersonRead"]; type Event = components["schemas"]["EventRead"]; type Relationship = components["schemas"]["RelationshipRead"]; type Qualifier = components["schemas"]["ParentChildQualifier"]; type RelCreate = components["schemas"]["RelationshipCreate"]; type Source = components["schemas"]["SourceRead"]; type Citation = components["schemas"]["CitationRead"]; type CitationCreate = components["schemas"]["CitationCreate"]; const fieldCls = "h-9 rounded-md border border-[var(--border)] bg-[var(--surface)] px-2 text-sm"; const QUALIFIERS: Qualifier[] = ["biological", "adoptive", "step", "foster", "donor", "guardian"]; // Curated genealogical event vocabulary (with an escape hatch). const EVENT_TYPES = [ "birth", "death", "marriage", "divorce", "engagement", "baptism", "burial", "residence", "census", "immigration", "emigration", "occupation", "education", "military service", "naturalization", "other", ]; const MONTHS = ["", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; const GED_MON = ["", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; const DATE_QUALS: Record = { exact: "", about: "ABT", before: "BEF", after: "AFT" }; const pad = (n: number, len: number) => String(n).padStart(len, "0"); function composeDate(qual: string, day: string, month: string, year: string) { const y = year.trim(); if (!y || Number.isNaN(Number(y))) { return { date_value: null as string | null, date_start: null as string | null, date_precision: null as string | null }; } const m = month ? Number(month) : null; const d = day.trim() ? Number(day) : null; const parts: string[] = []; if (d && m) parts.push(String(d)); if (m) parts.push(GED_MON[m]); parts.push(y); const prefix = DATE_QUALS[qual]; return { date_value: (prefix ? `${prefix} ` : "") + parts.join(" "), date_start: `${pad(Number(y), 4)}-${pad(m ?? 1, 2)}-${pad(d ?? 1, 2)}`, date_precision: qual, }; } // Parse a stored date_value (e.g. "ABT 12 MAR 1900") back into form fields. function parseDateValue(v: string | null | undefined) { let qual = "exact"; let day = ""; let month = ""; let year = ""; if (v) { let s = v.trim(); const up = s.toUpperCase(); for (const [q, pre] of Object.entries(DATE_QUALS)) { if (pre && up.startsWith(`${pre} `)) { qual = q; s = s.slice(pre.length + 1).trim(); break; } } for (const t of s.toUpperCase().split(/\s+/).filter(Boolean)) { if (/^\d{3,4}$/.test(t) && !year) year = t; else if (/^\d{1,2}$/.test(t)) day = String(Number(t)); else { const mi = GED_MON.indexOf(t); if (mi > 0) month = String(mi); } } } return { qual, day, month, year }; } export default function PersonDetailPage() { const router = useRouter(); const params = useParams<{ id: string; personId: string }>(); const treeId = params.id; const personId = params.personId; const [person, setPerson] = useState(null); const [people, setPeople] = useState([]); const [events, setEvents] = useState([]); const [rels, setRels] = useState([]); const [sources, setSources] = useState([]); const [citations, setCitations] = useState([]); const [ready, setReady] = useState(false); const [evType, setEvType] = useState("birth"); const [evTypeOther, setEvTypeOther] = useState(""); const [dateQual, setDateQual] = useState("exact"); const [dateDay, setDateDay] = useState(""); const [dateMonth, setDateMonth] = useState(""); const [dateYear, setDateYear] = useState(""); // Inline edit-event form. const [editId, setEditId] = useState(null); const [edType, setEdType] = useState("birth"); const [edTypeOther, setEdTypeOther] = useState(""); const [edQual, setEdQual] = useState("exact"); const [edDay, setEdDay] = useState(""); const [edMonth, setEdMonth] = useState(""); const [edYear, setEdYear] = useState(""); // Inline edit-person form (name + vitals). const [editingPerson, setEditingPerson] = useState(false); const [pGiven, setPGiven] = useState(""); const [pSurname, setPSurname] = useState(""); const [pGender, setPGender] = useState(""); const [pLiving, setPLiving] = useState("unknown"); const [pPrivacy, setPPrivacy] = useState<"inherit" | "private" | "public">("inherit"); const [relKind, setRelKind] = useState<"parent" | "child" | "partner" | "sibling">("parent"); const [relOther, setRelOther] = useState(""); const [relQual, setRelQual] = useState("biological"); // Inline citation form: which fact is being cited ("p" = person, `e:`). const [citeFor, setCiteFor] = useState(null); const [citeSource, setCiteSource] = useState(""); const [citePage, setCitePage] = useState(""); const load = useCallback(async () => { const p = await api.GET("/api/v1/trees/{tree_id}/persons/{person_id}", { params: { path: { tree_id: treeId, person_id: personId } }, }); if (p.response.status === 401) { router.push("/login"); return; } setPerson(p.data ?? null); const [all, ev, rl, src, cit] = await Promise.all([ api.GET("/api/v1/trees/{tree_id}/persons", { params: { path: { tree_id: treeId } } }), api.GET("/api/v1/trees/{tree_id}/persons/{person_id}/events", { params: { path: { tree_id: treeId, person_id: personId } }, }), api.GET("/api/v1/trees/{tree_id}/persons/{person_id}/relationships", { params: { path: { tree_id: treeId, person_id: personId } }, }), api.GET("/api/v1/trees/{tree_id}/sources", { params: { path: { tree_id: treeId } } }), api.GET("/api/v1/trees/{tree_id}/citations", { params: { path: { tree_id: treeId } } }), ]); setPeople(all.data ?? []); setEvents(ev.data ?? []); setRels(rl.data ?? []); setSources(src.data ?? []); setCitations(cit.data ?? []); setReady(true); }, [router, treeId, personId]); useEffect(() => { load(); }, [load]); const nameOf = useMemo(() => { const m = new Map(people.map((p) => [p.id, p.primary_name ?? "Unnamed"])); return (id: string) => m.get(id) ?? "Unknown"; }, [people]); const sourceName = useMemo(() => { const m = new Map(sources.map((s) => [s.id, s.title])); return (id: string) => m.get(id) ?? "source"; }, [sources]); const others = people.filter((p) => p.id !== personId); const parents = rels.filter((r) => r.type === "parent_child" && r.person_to_id === personId); const children = rels.filter((r) => r.type === "parent_child" && r.person_from_id === personId); const partners = rels.filter((r) => r.type === "partnership"); const siblings = rels.filter((r) => r.type === "sibling"); const eventCites = (id: string) => citations.filter((c) => c.event_id === id); const personCites = citations.filter((c) => c.person_id === personId); async function addEvent(e: React.FormEvent) { e.preventDefault(); const event_type = evType === "other" ? evTypeOther.trim() : evType; if (!event_type) return; const { date_value, date_start, date_precision } = composeDate( dateQual, dateDay, dateMonth, dateYear, ); const { error } = await api.POST("/api/v1/trees/{tree_id}/events", { params: { path: { tree_id: treeId } }, body: { event_type, person_id: personId, date_value, date_start, date_precision }, }); if (!error) { setDateDay(""); setDateMonth(""); setDateYear(""); setDateQual("exact"); setEvTypeOther(""); load(); } } async function removeEvent(id: string) { await api.DELETE("/api/v1/trees/{tree_id}/events/{event_id}", { params: { path: { tree_id: treeId, event_id: id } }, }); load(); } function startEdit(ev: Event) { setEditId(ev.id); const known = EVENT_TYPES.includes(ev.event_type); setEdType(known ? ev.event_type : "other"); setEdTypeOther(known ? "" : ev.event_type); const parsed = parseDateValue(ev.date_value); setEdQual(parsed.qual); setEdDay(parsed.day); setEdMonth(parsed.month); setEdYear(parsed.year); } async function saveEdit() { if (!editId) return; const event_type = edType === "other" ? edTypeOther.trim() : edType; if (!event_type) return; const { date_value, date_start, date_precision } = composeDate(edQual, edDay, edMonth, edYear); const { error } = await api.PATCH("/api/v1/trees/{tree_id}/events/{event_id}", { params: { path: { tree_id: treeId, event_id: editId } }, body: { event_type, date_value, date_start, date_precision }, }); if (!error) { setEditId(null); load(); } } async function addRel(e: React.FormEvent) { e.preventDefault(); if (!relOther) return; let body: RelCreate; if (relKind === "parent") { body = { type: "parent_child", person_from_id: relOther, person_to_id: personId, qualifier: relQual }; } else if (relKind === "child") { body = { type: "parent_child", person_from_id: personId, person_to_id: relOther, qualifier: relQual }; } else if (relKind === "partner") { body = { type: "partnership", person_from_id: personId, person_to_id: relOther }; } else { body = { type: "sibling", person_from_id: personId, person_to_id: relOther }; } const { error } = await api.POST("/api/v1/trees/{tree_id}/relationships", { params: { path: { tree_id: treeId } }, body, }); if (!error) { setRelOther(""); load(); } } async function removeRel(id: string) { await api.DELETE("/api/v1/trees/{tree_id}/relationships/{relationship_id}", { params: { path: { tree_id: treeId, relationship_id: id } }, }); load(); } async function addCitation(target: Partial) { if (!citeSource) return; const body: CitationCreate = { source_id: citeSource, page: citePage || null, ...target }; const { error } = await api.POST("/api/v1/trees/{tree_id}/citations", { params: { path: { tree_id: treeId } }, body, }); if (!error) { setCiteFor(null); setCiteSource(""); setCitePage(""); load(); } } async function removeCitation(id: string) { await api.DELETE("/api/v1/trees/{tree_id}/citations/{citation_id}", { params: { path: { tree_id: treeId, citation_id: id } }, }); load(); } async function removePerson() { await api.DELETE("/api/v1/trees/{tree_id}/persons/{person_id}", { params: { path: { tree_id: treeId, person_id: personId } }, }); router.push(`/trees/${treeId}`); } function startEditPerson(current: Person) { const t = (current.primary_name ?? "").trim().split(/\s+/).filter(Boolean); setPGiven(t.length > 1 ? t.slice(0, -1).join(" ") : (t[0] ?? "")); setPSurname(t.length > 1 ? t[t.length - 1] : ""); setPGender(current.gender ?? ""); setPLiving(current.is_living === true ? "living" : current.is_living === false ? "deceased" : "unknown"); setPPrivacy((current.privacy as "inherit" | "private" | "public") ?? "inherit"); setEditingPerson(true); } async function savePerson() { const { error } = await api.PATCH("/api/v1/trees/{tree_id}/persons/{person_id}", { params: { path: { tree_id: treeId, person_id: personId } }, body: { given: pGiven || null, surname: pSurname || null, gender: pGender || null, is_living: pLiving === "living" ? true : pLiving === "deceased" ? false : null, privacy: pPrivacy, }, }); if (!error) { setEditingPerson(false); load(); } } if (!ready) return

Loading…

; if (!person) return

Not found.

; // Inline "cite" control: a badge with count, a toggle, and the picker form. function citeControl(key: string, target: Partial, cites: Citation[]) { return ( {cites.length > 0 && ( sourceName(c.source_id)).join(", ")} > ✓ {cites.length} sourced )} {citeFor === key ? (
{ e.preventDefault(); addCitation(target); }} className="inline-flex items-center gap-1" > setCitePage(e.target.value)} />
) : sources.length === 0 ? ( + add a source first ) : ( )}
); } const relGroup = (label: string, items: Relationship[], otherId: (r: Relationship) => string) => items.length > 0 && (

{label}

    {items.map((r) => (
  • {nameOf(otherId(r))} {r.qualifier ? · {r.qualifier} : null}
  • ))}
); return (
← Back to tree {editingPerson ? (
{ e.preventDefault(); savePerson(); }} className="space-y-3 rounded-lg border border-[var(--border)] p-4" >
setPGiven(e.target.value)} /> setPSurname(e.target.value)} /> setPGender(e.target.value)} />
) : (

{person.primary_name ?? "Unnamed person"}

{citeControl("p", { person_id: personId }, personCites)}
)} Life events {events.length === 0 ? (

No events yet.

) : (
    {events.map((ev) => editId === ev.id ? (
  • { e.preventDefault(); saveEdit(); }} className="flex flex-wrap items-end gap-2" > {edType === "other" && ( setEdTypeOther(e.target.value)} /> )} setEdDay(e.target.value)} /> setEdYear(e.target.value)} />
  • ) : (
  • {ev.event_type} {ev.date_value ? ( — {ev.date_value} ) : null} {citeControl(`e:${ev.id}`, { event_id: ev.id }, eventCites(ev.id))}
  • ), )}
)}
{evType === "other" && ( )}
Relationships {rels.length === 0 ? (

No relationships yet.

) : (
{relGroup("Parents", parents, (r) => r.person_from_id)} {relGroup("Children", children, (r) => r.person_to_id)} {relGroup("Partners", partners, (r) => r.person_from_id === personId ? r.person_to_id : r.person_from_id, )} {relGroup("Siblings", siblings, (r) => r.person_from_id === personId ? r.person_to_id : r.person_from_id, )}
)} {others.length === 0 ? (

Add more people to the tree to link them.

) : (
Add {(relKind === "parent" || relKind === "child") && ( )}
)}
); }