diff --git a/web/app/components/workflow/index.tsx b/web/app/components/workflow/index.tsx index 585e2c248b..498aac64ea 100644 --- a/web/app/components/workflow/index.tsx +++ b/web/app/components/workflow/index.tsx @@ -1,10 +1,11 @@ import type { FC } from 'react' -import { memo } from 'react' +import { memo, useEffect } from 'react' import { useKeyPress } from 'ahooks' import ReactFlow, { Background, ReactFlowProvider, useEdgesState, + useNodesInitialized, useNodesState, } from 'reactflow' import 'reactflow/dist/style.css' @@ -38,6 +39,12 @@ const Workflow: FC = memo(({ }) => { const [nodes] = useNodesState(initialNodes) const [edges, _, onEdgesChange] = useEdgesState(initialEdges) + const nodesInitialized = useNodesInitialized() + + useEffect(() => { + if (nodesInitialized) + console.log('initialed') + }, [nodesInitialized]) const { handleEnterNode, diff --git a/web/app/components/workflow/utils.ts b/web/app/components/workflow/utils.ts index 91be52872a..257ded1027 100644 --- a/web/app/components/workflow/utils.ts +++ b/web/app/components/workflow/utils.ts @@ -7,20 +7,31 @@ import type { Edge, Node, } from './types' +import { BlockEnum } from './types' export const nodesLevelOrderTraverse = ( firstNode: Node, nodes: Node[], edges: Edge[], - callback: (n: Node) => void, + callback: (n: any) => void, ) => { const queue = [{ node: firstNode, + depth: 0, + breath: 0, }] + let currenDepth = 0 + let currentBreath = 0 while (queue.length) { - const { node } = queue.shift()! - callback(node) + const { node, depth, breath } = queue.shift()! + + if (currenDepth !== depth) { + currenDepth = depth + currentBreath = 0 + } + + callback({ node, depth, breath }) const targetBranches = node.data.targetBranches if (targetBranches?.length) { @@ -37,11 +48,19 @@ export const nodesLevelOrderTraverse = ( }) const outgoers = getOutgoers(node, nodes, sortedTargetEdges) - queue.push(...outgoers.map((outgoer) => { + + queue.push(...outgoers.map((outgoer, index) => { return { node: outgoer, + depth: depth + 1, + breath: currentBreath + index, } })) + + currentBreath += outgoers.length + } + else { + currentBreath += 1 } } else { @@ -50,8 +69,12 @@ export const nodesLevelOrderTraverse = ( if (outgoers.length === 1) { queue.push({ node: outgoers[0], + depth: depth + 1, + breath: 0, }) } + + currentBreath += 1 } } } @@ -72,12 +95,26 @@ export const initialNodesAndEdges = (nodes: Node[], edges: Edge[]) => { } export type PositionMap = { - position: { - x: number - y: number - } index: { x: number y: number } } + +export const getNodesPositionMap = (nodes: Node[], edges: Edge[]) => { + const startNode = nodes.find((node: Node) => node.data.type === BlockEnum.Start) + const positionMap: Record = {} + + if (startNode) { + nodesLevelOrderTraverse(startNode, nodes, edges, ({ node, depth, breath }) => { + positionMap[node.id] = { + index: { + x: depth, + y: breath, + }, + } + }) + } + + return positionMap +}