diff --git a/frontend/src/lib/components/graph/FlowGraphV2.svelte b/frontend/src/lib/components/graph/FlowGraphV2.svelte index 7636649f4f..8214d12481 100644 --- a/frontend/src/lib/components/graph/FlowGraphV2.svelte +++ b/frontend/src/lib/components/graph/FlowGraphV2.svelte @@ -17,6 +17,7 @@ import { graphBuilder, isTriggerStep, + topologicalSort, type InlineScript, type InsertKind, type NodeLayout, @@ -224,7 +225,7 @@ const nodes2 = nodes.map((n) => { return { ...n, position: { x: 0, y: 0 } } }) - for (const n of nodes.reverse()) { + for (const n of topologicalSort(nodes)) { const endId = n.id + '-end' if (nodeWidths[endId] != undefined) { diff --git a/frontend/src/lib/components/graph/graphBuilder.svelte.ts b/frontend/src/lib/components/graph/graphBuilder.svelte.ts index 07bc9f2159..0a0eef6ffb 100644 --- a/frontend/src/lib/components/graph/graphBuilder.svelte.ts +++ b/frontend/src/lib/components/graph/graphBuilder.svelte.ts @@ -291,6 +291,24 @@ export type AssetsOverflowedN = { } } +export function topologicalSort(nodes: NodeLayout[]): NodeLayout[] { + const nodeMap = new Map(nodes.map(n => [n.id, n])); + const result: NodeLayout[] = []; + const visited = new Set(); + + function visit(id: string): void { + if (visited.has(id)) return; + visited.add(id); + + const node = nodeMap.get(id)!; + node.parentIds?.forEach(visit); + result.push(node); + } + + nodes.forEach(n => visit(n.id)); + return result.reverse(); +} + // input2: InputNode, // module: ModuleNode, // branchAllStart: BranchAllStart,