import { isNullOrUnDef } from '@/utils/is' import type { Elements } from 'react-flow-renderer' import { Actions } from '../enum' import type { InitialState } from '.' export enum ProcessType { NODE = '1' } const setElements = (state, elements: Elements) => ({ ...state, elements: Array.isArray(elements) ? elements : [] }) const setFlowNode = (state, payload) => { const res = { ...state } if (payload instanceof Map) { res.flowData = payload return res } const { id, node } = payload if (!id) return state res.flowData.set(id, node) return res } const setFlowInstance = (state, flowInstance) => { if (flowInstance) { return { ...state, flowInstance } } return state } const removeFlowNode = (state, node) => { const { id, newElements } = node const res = { ...state } res.elements = newElements if (res.flowData.get(id)) { res.flowData.delete(id) } return res } const setFlowProps = (state, props) => { if (!isNullOrUnDef(props)) { return { ...state, ...props } } return state } const openModal = (state, node) => { return node?.id ? { ...state, modalConfig: { visible: true, nodeType: node.type, nodeID: node.id } } : state } const closeModal = state => ({ ...state, modalConfig: { visible: false, nodeType: null, nodeID: null } }) const onStoreLoad = (state, payload) => ({ ...state, ...payload }) // 管理所有处理函数 const handlerMap = { [Actions.SET_FLOW_NODE]: setFlowNode, [Actions.REMOVE_FLOW_NODE]: removeFlowNode, [Actions.OPEN_MODAL]: openModal, [Actions.CLOSE_MODAL]: closeModal, [Actions.SET_ELEMENTS]: setElements, [Actions.SET_FLOW_INSTANCE]: setFlowInstance, [Actions.SET_FOLW_PROPS]: setFlowProps, [Actions.INIT_FLOW_CONTEXT]: onStoreLoad } const reducer = (state: InitialState, action: Actions) => { const { type, payload } = action const handler = handlerMap[type] const res = typeof handler === 'function' && handler(state, payload) return res || state } export default reducer