reducer.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. res.elements = newElements
  33. if (res.flowData.get(id)) {
  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. const onStoreLoad = (state, payload) => ({
  65. ...state,
  66. ...payload
  67. })
  68. // 管理所有处理函数
  69. const handlerMap = {
  70. [Actions.SET_FLOW_NODE]: setFlowNode,
  71. [Actions.REMOVE_FLOW_NODE]: removeFlowNode,
  72. [Actions.OPEN_MODAL]: openModal,
  73. [Actions.CLOSE_MODAL]: closeModal,
  74. [Actions.SET_ELEMENTS]: setElements,
  75. [Actions.SET_FLOW_INSTANCE]: setFlowInstance,
  76. [Actions.SET_FOLW_PROPS]: setFlowProps,
  77. [Actions.INIT_FLOW_CONTEXT]: onStoreLoad
  78. }
  79. const reducer = (state: InitialState, action: Actions) => {
  80. const { type, payload } = action
  81. const handler = handlerMap[type]
  82. const res = typeof handler === 'function' && handler(state, payload)
  83. return res || state
  84. }
  85. export default reducer