Layout engine for ComfyUI workflows. Positions nodes in a logical left-to-right flow (DAG layout).
| 2 | |
| 3 | |
| 4 | class WorkflowLayout: |
| 5 | """ |
| 6 | Layout engine for ComfyUI workflows. |
| 7 | Positions nodes in a logical left-to-right flow (DAG layout). |
| 8 | """ |
| 9 | |
| 10 | # Standard ComfyUI node dimensions and spacing |
| 11 | NODE_WIDTH = 210 |
| 12 | NODE_HEIGHT_BASE = 60 |
| 13 | SLOT_HEIGHT = 20 |
| 14 | |
| 15 | # Layout spacing |
| 16 | RANK_SEP = 450 # Horizontal spacing between layers |
| 17 | NODE_SEP = 150 # Vertical spacing between nodes |
| 18 | |
| 19 | def __init__(self, nodes: list[dict], links: list[list]): |
| 20 | """ |
| 21 | Initialize layout engine. |
| 22 | |
| 23 | Args: |
| 24 | nodes: List of node dictionaries |
| 25 | links: List of link arrays [id, src_id, src_slot, dst_id, dst_slot, type] |
| 26 | """ |
| 27 | self.nodes = nodes |
| 28 | self.links = links |
| 29 | self.node_map = {node["id"]: node for node in nodes} |
| 30 | |
| 31 | def apply_layout(self): |
| 32 | """ |
| 33 | Calculate and apply positions to all nodes. |
| 34 | Modifies the 'pos' attribute of nodes in-place. |
| 35 | """ |
| 36 | if not self.nodes: |
| 37 | return |
| 38 | |
| 39 | adj = defaultdict(list) |
| 40 | in_degree = defaultdict(int) |
| 41 | parents = defaultdict(list) |
| 42 | |
| 43 | for node in self.nodes: |
| 44 | in_degree[node["id"]] = 0 |
| 45 | |
| 46 | # Link format: [id, src_id, src_slot, dst_id, dst_slot, type] |
| 47 | for link in self.links: |
| 48 | if not link: |
| 49 | continue |
| 50 | |
| 51 | if isinstance(link, (list, tuple)) and len(link) >= 5: |
| 52 | src_id = link[1] |
| 53 | dst_id = link[3] |
| 54 | |
| 55 | if src_id in self.node_map and dst_id in self.node_map: |
| 56 | adj[src_id].append(dst_id) |
| 57 | parents[dst_id].append(src_id) |
| 58 | in_degree[dst_id] += 1 |
| 59 | |
| 60 | # Assign ranks (levels) using topological sort approach |
| 61 | ranks = {} |