reducer.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import { isNullOrUnDef } from '@/utils/is'
  2. import type { Elements } from 'react-flow-renderer'
  3. import { Actions } from '../enum'
  4. import type { InitialState } from '.'
  5. export enum ProcessType {
  6. NODE = '1'
  7. }
  8. const setElements = (state, elements: Elements) => ({
  9. ...state,
  10. elements: Array.isArray(elements) ? elements : []
  11. })
  12. const setFlowNode = (state, payload) => {
  13. const res = { ...state }
  14. if (payload instanceof Map) {
  15. res.flowData = payload
  16. return res
  17. }
  18. const { id, node } = payload
  19. if (!id) return state
  20. res.flowData.set(id, node)
  21. return res
  22. }
  23. const setFlowInstance = (state, flowInstance) => {
  24. if (flowInstance) {
  25. return { ...state, flowInstance }
  26. }
  27. return state
  28. }
  29. const removeFlowNode = (state, node) => {
  30. const { id, newElements } = node
  31. const res = { ...state }
  32. if (res.flowData.get(id)) {
  33. res.elements = newElements
  34. res.flowData.delete(id)
  35. }
  36. return res
  37. }
  38. const setFlowProps = (state, props) => {
  39. if (!isNullOrUnDef(props)) {
  40. return { ...state, ...props }
  41. }
  42. return state
  43. }
  44. const openModal = (state, node) => {
  45. return node?.id
  46. ? {
  47. ...state,
  48. modalConfig: {
  49. visible: true,
  50. nodeType: node.type,
  51. nodeID: node.id
  52. }
  53. }
  54. : state
  55. }
  56. const closeModal = state => ({
  57. ...state,
  58. modalConfig: {
  59. visible: false,
  60. nodeType: null,
  61. nodeID: null
  62. }
  63. })
  64. // 管理所有处理函数
  65. const handlerMap = {
  66. [Actions.SET_FLOW_NODE]: setFlowNode,
  67. [Actions.REMOVE_FLOW_NODE]: removeFlowNode,
  68. [Actions.OPEN_MODAL]: openModal,
  69. [Actions.CLOSE_MODAL]: closeModal,
  70. [Actions.SET_ELEMENTS]: setElements,
  71. [Actions.SET_FLOW_INSTANCE]: setFlowInstance,
  72. [Actions.SET_FOLW_PROPS]: setFlowProps
  73. }
  74. const reducer = (state: InitialState, action: Actions) => {
  75. const { type, payload } = action
  76. const handler = handlerMap[type]
  77. const res = typeof handler === 'function' && handler(state, payload)
  78. return res || state
  79. }
  80. export default reducer