diff --git a/docs/xflow/FlowProvider.md b/docs/xflow/FlowProvider.md index a64bb2581..7f6384eb7 100644 --- a/docs/xflow/FlowProvider.md +++ b/docs/xflow/FlowProvider.md @@ -35,6 +35,7 @@ group: - fitBounds:适应边界 - screenToFlowPosition:将屏幕坐标转换为画布坐标 - flowToScreenPosition:将画布坐标转换为屏幕坐标 +- runAutoLayout:自动布局节点 ## useNodes diff --git a/packages/x-flow/src/XFlow.tsx b/packages/x-flow/src/XFlow.tsx index e49b8e61e..3d54b13b8 100644 --- a/packages/x-flow/src/XFlow.tsx +++ b/packages/x-flow/src/XFlow.tsx @@ -42,7 +42,7 @@ const edgeTypes = { buttonedge: memo(CustomEdge) }; */ const XFlow: FC = memo(props => { const workflowContainerRef = useRef(null); - const store = useStoreApi(); + const storeApi = useStoreApi(); const { zoomTo } = useReactFlow(); const { layout, @@ -124,7 +124,7 @@ const XFlow: FC = memo(props => { eventEmitter?.useSubscription((v: any) => { // 整理画布 if (v.type === 'auto-layout-nodes') { - const newNodes: any = autoLayoutNodes(store.getState().nodes, edges); + const newNodes: any = autoLayoutNodes(storeApi.getState().nodes, edges); setNodes(newNodes, false); } diff --git a/packages/x-flow/src/hooks/useFlow.ts b/packages/x-flow/src/hooks/useFlow.ts index 4e6118a6a..a9ab5b234 100644 --- a/packages/x-flow/src/hooks/useFlow.ts +++ b/packages/x-flow/src/hooks/useFlow.ts @@ -3,6 +3,7 @@ import { useMemoizedFn } from 'ahooks'; import { useMemo } from 'react'; import { FlowNode } from '../models/store'; import { useStoreApi } from './useStore'; +import autoLayoutNodes from '../utils/autoLayoutNodes'; // useFlow 维护原则 // 1. 尽量复用 reactflow 已有的方法,不要重复造轮子 @@ -38,6 +39,10 @@ export const useFlow = () => { const addEdges = useMemoizedFn((edges: Edge[]) => { storeApi.getState().addEdges(edges); }); + const runAutoLayout = useMemoizedFn(() => { + const newNodes: any = autoLayoutNodes(storeApi.getState().nodes, storeApi.getState().edges); + setNodes(newNodes, false); + }); return useMemo( () => ({ @@ -58,7 +63,8 @@ export const useFlow = () => { setCenter, fitBounds, screenToFlowPosition, - flowToScreenPosition + flowToScreenPosition, + runAutoLayout }), [instance] );