export type RelationshipContextState = "related" | "ancestor" | "descendant"; export interface ContextRelationship { from: string; to: string; kind?: string; } export interface RelationshipContextEdge extends ContextRelationship { state: RelationshipContextState; } export interface RelationshipContext { focusedId: string; relatedIds: string[]; ancestorIds: string[]; descendantIds: string[]; edges: RelationshipContextEdge[]; } const SOURCE_IS_ANCESTOR = new Set(["parent", "contains", "supports"]); const SOURCE_IS_DESCENDANT = new Set(["child", "depends-on"]); const STATE_PRIORITY: Record = { related: 1, descendant: 2, ancestor: 3, }; function normalizeKind(kind?: string) { return kind?.trim().toLowerCase() || "related"; } function resolveEdgeState( relationship: ContextRelationship, focusedId: string, ): RelationshipContextState { const kind = normalizeKind(relationship.kind); const focusedIsSource = relationship.from === focusedId; if (SOURCE_IS_ANCESTOR.has(kind)) { return focusedIsSource ? "descendant" : "ancestor"; } if (SOURCE_IS_DESCENDANT.has(kind)) { return focusedIsSource ? "ancestor" : "descendant"; } return "related"; } export function resolveRelationshipContext( focusedId: string, relationships: ContextRelationship[], ): RelationshipContext { const statesById = new Map(); const edges: RelationshipContextEdge[] = []; for (const relationship of relationships) { if (relationship.from !== focusedId && relationship.to !== focusedId) { continue; } const counterpartId = relationship.from === focusedId ? relationship.to : relationship.from; if (!counterpartId || counterpartId === focusedId) { continue; } const state = resolveEdgeState(relationship, focusedId); const currentState = statesById.get(counterpartId); if (!currentState || STATE_PRIORITY[state] > STATE_PRIORITY[currentState]) { statesById.set(counterpartId, state); } edges.push({ ...relationship, state }); } const idsFor = (state: RelationshipContextState) => [...statesById.entries()] .filter(([, candidate]) => candidate === state) .map(([id]) => id); return { focusedId, relatedIds: idsFor("related"), ancestorIds: idsFor("ancestor"), descendantIds: idsFor("descendant"), edges, }; } export function getRelationshipContextState( context: RelationshipContext, entityId: string, ): RelationshipContextState | null { if (context.ancestorIds.includes(entityId)) return "ancestor"; if (context.descendantIds.includes(entityId)) return "descendant"; if (context.relatedIds.includes(entityId)) return "related"; return null; }