import ELK from "elkjs/lib/elk.bundled.js";import type {Dag_View_Model} from "./dag_types";
const elk=new ELK();const layout_cache=new Map<string,Dag_View_Model>();
export async function layout_dag(model:Dag_View_Model,direction:"RIGHT"|"DOWN"="RIGHT"):Promise<Dag_View_Model>{const key=`${model.version}:${direction}:${model.nodes.map(node=>node.id).join(",")}:${model.edges.map(edge=>`${edge.source}>${edge.target}`).join(",")}`;const cached=layout_cache.get(key);if(cached)return{...cached,nodes:cached.nodes.map((node,index)=>({...node,data:model.nodes[index].data})),edges:model.edges};const result=await elk.layout({id:"root",layoutOptions:{"elk.algorithm":"layered","elk.direction":direction,"elk.spacing.nodeNode":"36","elk.layered.spacing.nodeNodeBetweenLayers":"70"},children:model.nodes.map(node=>({id:node.id,width:250,height:96})),edges:model.edges.map(edge=>({id:edge.id,sources:[edge.source],targets:[edge.target]}))});const positions=new Map(result.children?.map(node=>[node.id,{x:node.x??0,y:node.y??0}]));const laid={...model,nodes:model.nodes.map(node=>({...node,position:positions.get(node.id)??node.position}))};layout_cache.set(key,laid);return laid;}
