Commit 1b73632f authored by StyleZhang's avatar StyleZhang

utils

parent 0a7cbf6f
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<WorkflowProps> = memo(({
}) => {
const [nodes] = useNodesState(initialNodes)
const [edges, _, onEdgesChange] = useEdgesState(initialEdges)
const nodesInitialized = useNodesInitialized()
useEffect(() => {
if (nodesInitialized)
console.log('initialed')
}, [nodesInitialized])
const {
handleEnterNode,
......
......@@ -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<string, PositionMap> = {}
if (startNode) {
nodesLevelOrderTraverse(startNode, nodes, edges, ({ node, depth, breath }) => {
positionMap[node.id] = {
index: {
x: depth,
y: breath,
},
}
})
}
return positionMap
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment