// src/lib/autoLayout.ts // Auto-layout algorithms for genogram and ecomap canvas rendering. // Pure functions — safe to import from both server and client. export interface LayoutMember { id?: string name: string generation: number birth_year?: number | null gender?: string // for male-left, female-right couple positioning is_client?: boolean // for centering layout on client } export interface LayoutRelationship { from: string // member ID, or an unambiguous legacy name to: string type: string // 'spouse' | 'parent' | 'child' | 'divorced' etc. } export interface FamilyUnit { parentIndices: number[] // indices into members array (1 for single parent, 2 for couple) childIndices: number[] // indices into members array, sorted by birth_year coupleRelType: string | null // couple relationship type, null for single parent coupleQuality: string | null // couple quality, null for single parent } const COUPLE_TYPES = new Set(['spouse', 'divorced', 'separated', 'partner']) /** * Build family units from members and relationships. * A family unit groups a couple (or single parent) with their children. */ export function buildFamilyUnits( members: LayoutMember[], relationships: LayoutRelationship[], ): FamilyUnit[] { // IDs are authoritative. Legacy name-based input is usable only when unique. const ids = new Map(members.flatMap((m, i) => m.id ? [[m.id, i] as const] : [])) const names = new Map() members.forEach((m, i) => names.set(m.name, [...(names.get(m.name) ?? []), i])) const resolve = (key: string) => ids.get(key) ?? (names.get(key)?.length === 1 ? names.get(key)![0] : undefined) const units: FamilyUnit[] = [] const pairs = new Set() const parents = new Map>() for (const rel of relationships) { const from = resolve(rel.from) const to = resolve(rel.to) if (from === undefined || to === undefined || from === to) continue if (COUPLE_TYPES.has(rel.type)) { const key = [from, to].sort((a, b) => a - b).join(':') if (!pairs.has(key)) { pairs.add(key) units.push({ parentIndices: [from, to], childIndices: [], coupleRelType: rel.type, coupleQuality: null }) } } else if (rel.type === 'parent' || rel.type === 'child') { const [parent, child] = rel.type === 'parent' ? [from, to] : [to, from] if (!parents.has(child)) parents.set(child, new Set()) parents.get(child)!.add(parent) } } const singles = new Map() for (const [child, knownParents] of parents) { const assigned = new Set() // Never infer parenthood merely because a person is a parent's partner. for (const unit of units) { if (unit.parentIndices.every(p => knownParents.has(p))) { unit.childIndices.push(child) unit.parentIndices.forEach(p => assigned.add(p)) } } for (const parent of knownParents) { if (assigned.has(parent)) continue if (!singles.has(parent)) singles.set(parent, { parentIndices: [parent], childIndices: [], coupleRelType: null, coupleQuality: null, }) singles.get(parent)!.childIndices.push(child) } } units.push(...singles.values()) for (const unit of units) { unit.childIndices.sort((a, b) => (members[a].birth_year ?? 9999) - (members[b].birth_year ?? 9999)) } return units } interface Position { x: number y: number } /** * Simple row-based layout (original algorithm). * Same generation → same row, members spaced evenly within each row. */ function layoutGenogramSimple( members: LayoutMember[], canvasWidth: number, canvasHeight: number, ): Position[] { if (members.length === 0) return [] // Group by generation const generations = new Map() for (let i = 0; i < members.length; i++) { const gen = members[i].generation if (!generations.has(gen)) generations.set(gen, []) generations.get(gen)!.push(i) } // Sort generation keys (most negative = top row) const genKeys = [...generations.keys()].sort((a, b) => a - b) const rowCount = genKeys.length const rowHeight = Math.max(140, canvasHeight / (rowCount + 1)) const positions: Position[] = new Array(members.length) for (let row = 0; row < genKeys.length; row++) { const indices = generations.get(genKeys[row])! // McGoldrick standard: oldest sibling on left (sort by birth_year) indices.sort((a, b) => { const ya = members[a].birth_year ?? 9999 const yb = members[b].birth_year ?? 9999 return ya - yb }) const colWidth = Math.max(120, canvasWidth / (indices.length + 1)) const rowStart = (canvasWidth - (indices.length - 1) * colWidth) / 2 const y = rowHeight * (row + 1) for (let col = 0; col < indices.length; col++) { positions[indices[col]] = { x: rowStart + colWidth * col, y, } } } return positions } // Layout constants for family-unit-aware positioning const GENERATION_GAP = 150 const COUPLE_GAP = 120 const SIBLING_GAP = 120 const FAMILY_GAP = 120 /** * Family-unit-aware layout. * Couples are placed side-by-side; children are centered below their parents. */ function layoutGenogramFamilyAware( members: LayoutMember[], relationships: LayoutRelationship[], canvasWidth: number, _canvasHeight: number, ): Position[] { if (members.length === 0) return [] const units = buildFamilyUnits(members, relationships) // Group members by generation; sort gen keys ascending (most negative = top) const generations = new Map() for (let i = 0; i < members.length; i++) { const gen = members[i].generation if (!generations.has(gen)) generations.set(gen, []) generations.get(gen)!.push(i) } const genKeys = [...generations.keys()].sort((a, b) => a - b) // Vertical positioning: genY[gen] = GENERATION_GAP * (rowIndex + 1) const genY = new Map() for (let row = 0; row < genKeys.length; row++) { genY.set(genKeys[row], GENERATION_GAP * (row + 1)) } const positions: (Position | undefined)[] = new Array(members.length).fill(undefined) // Track which members have been positioned const positioned = new Set() const partnerSlot = (anchor: number, direction: number, generation: number) => { const free = (x: number) => [...positioned].every(i => members[i].generation !== generation || Math.abs(positions[i]!.x - x) >= COUPLE_GAP) for (let distance = 1; ; distance++) { for (const side of [direction, -direction]) { const x = anchor + side * distance * COUPLE_GAP if (free(x)) return x } } } // For each generation (top to bottom), place family units whose parents are on that generation for (const gen of genKeys) { // Find units whose parents belong to this generation const genUnits = units.filter(unit => unit.parentIndices.length > 0 && members[unit.parentIndices[0]].generation === gen, ) let cursorX = 0 for (const unit of genUnits) { const parentY = genY.get(gen)! // Determine parent positions let parentMidX: number if (unit.parentIndices.length >= 2) { // Couple: male on left, female on right let [pA, pB] = unit.parentIndices const genderA = members[pA].gender const genderB = members[pB].gender // If A is female and B is male, swap so male is on left if (genderA === 'female' && genderB !== 'female') { ;[pA, pB] = [pB, pA] } let leftX: number let rightX: number if (positioned.has(pA) && positioned.has(pB)) { // Both already placed (e.g. remarriage) — use existing positions leftX = positions[pA]!.x rightX = positions[pB]!.x } else if (positioned.has(pA)) { leftX = positions[pA]!.x rightX = partnerSlot(leftX, 1, members[pB].generation) positions[pB] = { x: rightX, y: genY.get(members[pB].generation)! } positioned.add(pB) cursorX = Math.max(cursorX, rightX + COUPLE_GAP / 2) } else if (positioned.has(pB)) { rightX = positions[pB]!.x leftX = partnerSlot(rightX, -1, members[pA].generation) positions[pA] = { x: leftX, y: genY.get(members[pA].generation)! } positioned.add(pA) cursorX = Math.max(cursorX, rightX + COUPLE_GAP / 2) } else { // Place fresh couple leftX = cursorX + COUPLE_GAP / 2 rightX = leftX + COUPLE_GAP positions[pA] = { x: leftX, y: parentY } positions[pB] = { x: rightX, y: genY.get(members[pB].generation)! } positioned.add(pA) positioned.add(pB) cursorX = rightX + FAMILY_GAP } parentMidX = (leftX + rightX) / 2 } else { // Single parent const pIdx = unit.parentIndices[0] let px: number if (positioned.has(pIdx)) { px = positions[pIdx]!.x } else { px = cursorX + COUPLE_GAP / 2 positions[pIdx] = { x: px, y: parentY } positioned.add(pIdx) cursorX = px + FAMILY_GAP } parentMidX = px } // Position children: center cluster below parents' midpoint, SIBLING_GAP apart if (unit.childIndices.length > 0) { // Sort children by birth_year (oldest left) const sortedChildren = [...unit.childIndices].sort((a, b) => { const ya = members[a].birth_year ?? 9999 const yb = members[b].birth_year ?? 9999 return ya - yb }) const childCount = sortedChildren.length const childGen = members[sortedChildren[0]].generation const childY = genY.get(childGen)! // Total width of the children cluster const totalChildWidth = (childCount - 1) * SIBLING_GAP const firstChildX = parentMidX - totalChildWidth / 2 for (let ci = 0; ci < sortedChildren.length; ci++) { const childIdx = sortedChildren[ci] if (!positioned.has(childIdx)) { positions[childIdx] = { x: firstChildX + ci * SIBLING_GAP, y: genY.get(members[childIdx].generation) ?? childY } positioned.add(childIdx) } } // Advance cursor to cover children spread const lastChildX = firstChildX + (childCount - 1) * SIBLING_GAP cursorX = Math.max(cursorX, lastChildX + FAMILY_GAP) } } // Place standalone members for this generation (not in any family unit as parents or children) const allUnitMembers = new Set() for (const unit of units) { for (const idx of unit.parentIndices) allUnitMembers.add(idx) for (const idx of unit.childIndices) allUnitMembers.add(idx) } const standAlone = (generations.get(gen) ?? []).filter( idx => !allUnitMembers.has(idx) && !positioned.has(idx), ) const standAloneY = genY.get(gen)! for (const idx of generations.get(gen) ?? []) { if (positioned.has(idx)) cursorX = Math.max(cursorX, positions[idx]!.x + SIBLING_GAP / 2) } for (const idx of standAlone) { positions[idx] = { x: cursorX + COUPLE_GAP / 2, y: standAloneY } positioned.add(idx) cursorX += SIBLING_GAP } } // Any remaining unpositioned members (e.g. children not in any unit) for (let i = 0; i < members.length; i++) { if (!positioned.has(i)) { const gen = members[i].generation const y = genY.get(gen) ?? GENERATION_GAP positions[i] = { x: 0, y } } } // Resolve overlaps introduced by multiple families / remarriages. Keep // generation rows and relative order; never change relationship data. for (const indices of generations.values()) { const ordered = [...indices].sort((a, b) => positions[a]!.x - positions[b]!.x) for (let i = 1; i < ordered.length; i++) { positions[ordered[i]]!.x = Math.max(positions[ordered[i]]!.x, positions[ordered[i - 1]]!.x + SIBLING_GAP) } } // Center horizontally in canvas const xs = (positions as Position[]).map(p => p.x) const minX = Math.min(...xs) const maxX = Math.max(...xs) const layoutWidth = maxX - minX const offsetX = (canvasWidth - layoutWidth) / 2 - minX return (positions as Position[]).map(p => ({ x: p.x + offsetX, y: p.y })) } /** * Assign x/y positions to genogram members. * * Overloaded signatures: * layoutGenogram(members) * layoutGenogram(members, relationships) * layoutGenogram(members, relationships, canvasWidth, canvasHeight) * layoutGenogram(members, canvasWidth, canvasHeight) ← legacy */ export function layoutGenogram( members: LayoutMember[], relationshipsOrWidth?: LayoutRelationship[] | number, canvasWidthOrHeight?: number, canvasHeight?: number, ): Position[] { // Detect legacy calling pattern: layoutGenogram(members, canvasWidth, canvasHeight) if (typeof relationshipsOrWidth === 'number') { return layoutGenogramSimple(members, relationshipsOrWidth, canvasWidthOrHeight ?? 500) } const relationships = relationshipsOrWidth const width = canvasWidthOrHeight ?? 700 const height = canvasHeight ?? 500 if (!relationships || relationships.length === 0) { return layoutGenogramSimple(members, width, height) } return layoutGenogramFamilyAware(members, relationships, width, height) } /** * Assign x/y positions to ecomap systems in a circle around the center. * Client is at center; systems evenly distributed on a ring. */ export function layoutEcomap( systemCount: number, canvasWidth = 700, canvasHeight = 500, ): Position[] { if (systemCount === 0) return [] const cx = canvasWidth / 2 const cy = canvasHeight / 2 // Grow the world, not the density; the viewport can fit/zoom the result. const radius = Math.max(150, Math.min(cx, cy) * 0.65, systemCount > 1 ? 120 / (2 * Math.sin(Math.PI / systemCount)) : 0) const positions: Position[] = [] for (let i = 0; i < systemCount; i++) { const angle = (2 * Math.PI * i) / systemCount - Math.PI / 2 // start from top positions.push({ x: Math.round(cx + radius * Math.cos(angle)), y: Math.round(cy + radius * Math.sin(angle)), }) } return positions }