Public view: add tree chart + homepage Explore links #49

Merged
justin merged 1 commits from public-tree-chart-and-explore-link into main 2026-06-09 09:44:25 -04:00
3 changed files with 221 additions and 9 deletions
+30 -3
View File
@@ -1,25 +1,30 @@
"use client";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useParams, useRouter } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import { api } from "@/lib/api/client";
import type { components } from "@/lib/api/schema";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { PublicTreeChart } from "@/components/public-tree-chart";
type Person = components["schemas"]["PersonRead"];
type Event = components["schemas"]["EventRead"];
type Relationship = components["schemas"]["RelationshipRead"];
type Tree = components["schemas"]["PublicTreeRead"];
// Public, no-login view of a tree. Everything here is already redacted by the
// /api/v1/public surface (living people show as "Living person").
export default function PublicTreePage() {
const { treeId } = useParams<{ treeId: string }>();
const router = useRouter();
const [tree, setTree] = useState<Tree | null>(null);
const [people, setPeople] = useState<Person[]>([]);
const [events, setEvents] = useState<Event[]>([]);
const [rels, setRels] = useState<Relationship[]>([]);
const [focusId, setFocusId] = useState<string | null>(null);
const [status, setStatus] = useState<"loading" | "ready" | "notfound">("loading");
const [search, setSearch] = useState("");
@@ -34,14 +39,22 @@ export default function PublicTreePage() {
setStatus("notfound");
return;
}
const [p, e] = await Promise.all([
const [p, e, r] = await Promise.all([
api.GET("/api/v1/public/trees/{tree_id}/persons", { params: { path: { tree_id: treeId } } }),
api.GET("/api/v1/public/trees/{tree_id}/events", { params: { path: { tree_id: treeId } } }),
api.GET("/api/v1/public/trees/{tree_id}/relationships", {
params: { path: { tree_id: treeId } },
}),
]);
if (cancelled) return;
const ppl = p.data ?? [];
const home = t.data.home_person_id;
const homeId = home && ppl.some((x) => x.id === home) ? home : null;
setTree(t.data);
setPeople(p.data ?? []);
setPeople(ppl);
setEvents(e.data ?? []);
setRels(r.data ?? []);
setFocusId((cur) => cur ?? homeId ?? ppl[0]?.id ?? null);
setStatus("ready");
})();
return () => {
@@ -97,12 +110,26 @@ export default function PublicTreePage() {
</p>
</div>
{focusId && people.length > 0 && (
<PublicTreeChart
people={people}
rels={rels}
events={events}
focusId={focusId}
onFocus={setFocusId}
onOpen={(id) => router.push(`/p/${treeId}/persons/${id}`)}
/>
)}
<div className="space-y-3">
<h2 className="font-serif text-base font-semibold">All people</h2>
<Input
className="w-72"
placeholder="Search people…"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</div>
<Card className="overflow-hidden">
<CardContent className="p-0">
+8
View File
@@ -31,6 +31,9 @@ export default function Home() {
<img src="/provenance-logo-plain.svg" alt="Provenance" className="h-7 w-auto" />
</Link>
<nav className="flex items-center gap-5 text-sm">
<Link href="/explore" className="text-[var(--muted)] hover:text-[var(--foreground)]">
Explore
</Link>
<Link href="/trees" className="text-[var(--muted)] hover:text-[var(--foreground)]">
Trees
</Link>
@@ -66,6 +69,11 @@ export default function Home() {
Sign in
</Button>
</Link>
<Link href="/explore">
<Button size="lg" variant="ghost">
Explore public trees
</Button>
</Link>
</div>
</div>
+177
View File
@@ -0,0 +1,177 @@
"use client";
// Vendored family-chart styles (the package blocks the CSS subpath export).
import "../app/trees/[id]/tree/chart.css";
import { useCallback, useEffect, useMemo, useRef } from "react";
import type { components } from "@/lib/api/schema";
type Person = components["schemas"]["PersonRead"];
type Relationship = components["schemas"]["RelationshipRead"];
type Event = components["schemas"]["EventRead"];
function splitName(name: string | null | undefined): [string, string] {
const t = (name ?? "").trim().split(/\s+/).filter(Boolean);
if (t.length <= 1) return [name ?? "", ""];
return [t.slice(0, -1).join(" "), t[t.length - 1]];
}
/**
* Read-only family-chart hourglass for the public surface. Same renderer the
* member tree view uses (incl. the cycle-sanitisation that keeps a bad graph
* from blowing the stack), fed by already-redacted public data. Clicking a card
* recenters; `onOpen` links out to the person's public page.
*/
export function PublicTreeChart({
people,
rels,
events,
focusId,
onFocus,
onOpen,
}: {
people: Person[];
rels: Relationship[];
events: Event[];
focusId: string | null;
onFocus: (id: string) => void;
onOpen?: (id: string) => void;
}) {
const containerRef = useRef<HTMLDivElement>(null);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const chartRef = useRef<any>(null);
const parentsOf = useCallback(
(id: string) =>
rels.filter((x) => x.type === "parent_child" && x.person_to_id === id).map((x) => x.person_from_id),
[rels],
);
const partnersOf = useCallback(
(id: string) =>
rels
.filter((x) => x.type === "partnership" && (x.person_from_id === id || x.person_to_id === id))
.map((x) => (x.person_from_id === id ? x.person_to_id : x.person_from_id)),
[rels],
);
const years = useMemo(() => {
const m = new Map<string, string>();
for (const ev of events) {
if (ev.person_id && ev.event_type === "birth" && !m.has(ev.person_id)) {
const y = ev.date_start ? ev.date_start.slice(0, 4) : ev.date_value ?? "";
if (y) m.set(ev.person_id, y);
}
}
return m;
}, [events]);
const byId = useMemo(() => new Map(people.map((p) => [p.id, p])), [people]);
const nameOf = useCallback((id: string) => byId.get(id)?.primary_name ?? "person", [byId]);
// Build the chart when the data changes (not on focus — recenter handles that).
useEffect(() => {
if (people.length === 0 || !containerRef.current) return;
let cancelled = false;
(async () => {
const alive = new Set(people.map((pp) => pp.id));
const ok = (ids: string[], self: string) =>
[...new Set(ids)].filter((id) => alive.has(id) && id !== self);
const parentsMap = new Map<string, string[]>();
const childrenMap = new Map<string, string[]>();
const isAncestorOf = (ancestor: string, of: string): boolean => {
const stack = [...(parentsMap.get(of) ?? [])];
const seen = new Set<string>();
while (stack.length) {
const n = stack.pop()!;
if (n === ancestor) return true;
if (seen.has(n)) continue;
seen.add(n);
for (const p of parentsMap.get(n) ?? []) stack.push(p);
}
return false;
};
for (const pp of people) {
const accepted: string[] = [];
for (const par of ok(parentsOf(pp.id), pp.id)) {
if (isAncestorOf(pp.id, par)) continue;
accepted.push(par);
parentsMap.set(pp.id, accepted);
childrenMap.set(par, [...(childrenMap.get(par) ?? []), pp.id]);
}
parentsMap.set(pp.id, accepted);
}
const data = people.map((pp) => {
const [fn, ln] = splitName(pp.primary_name);
return {
id: pp.id,
data: {
"first name": fn || "Unnamed",
"last name": ln,
birthday: years.get(pp.id) ?? "",
gender: pp.gender === "female" ? "F" : "M",
},
rels: {
spouses: ok(partnersOf(pp.id), pp.id),
parents: parentsMap.get(pp.id) ?? [],
children: childrenMap.get(pp.id) ?? [],
},
};
});
const f3 = await import("family-chart");
if (cancelled || !containerRef.current) return;
try {
containerRef.current.innerHTML = "";
const chart = f3.createChart(containerRef.current, data);
chart.setCardHtml().setCardDisplay([["first name", "last name"], ["birthday"]]);
chart.setOrientationHorizontal();
chart.setAncestryDepth?.(3);
chart.setProgenyDepth?.(2);
chart.setAfterUpdate?.(() => {
const md = chart.getMainDatum?.();
const id = md?.id ?? md?.data?.id;
if (id) onFocus(id);
});
chartRef.current = chart;
if (focusId) chart.updateMainId(focusId);
chart.updateTree({ initial: true });
} catch (err) {
console.error("public tree render failed", err);
if (containerRef.current) containerRef.current.innerHTML = "";
}
})();
return () => {
cancelled = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [people, rels, events]);
// Recenter when the focus changes without rebuilding the chart.
useEffect(() => {
if (focusId && chartRef.current) {
chartRef.current.updateMainId?.(focusId);
chartRef.current.updateTree?.();
}
}, [focusId]);
return (
<div className="space-y-2">
<div
ref={containerRef}
className="f3 rounded-xl border border-[var(--border)]"
style={{ width: "100%", height: "70vh", background: "var(--surface)" }}
/>
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="text-sm text-[var(--muted)]">
Drag to pan · scroll to zoom · click a person to recenter.
</p>
{focusId && onOpen && (
<button onClick={() => onOpen(focusId)} className="text-sm text-bronze hover:underline">
Open {nameOf(focusId)}
</button>
)}
</div>
</div>
);
}