use-node-data-update.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { useCallback } from 'react'
  2. import produce from 'immer'
  3. import { useStoreApi } from 'reactflow'
  4. import { useNodesSyncDraft } from './use-nodes-sync-draft'
  5. import { useNodesReadOnly } from './use-workflow'
  6. type NodeDataUpdatePayload = {
  7. id: string
  8. data: Record<string, any>
  9. }
  10. export const useNodeDataUpdate = () => {
  11. const store = useStoreApi()
  12. const { handleSyncWorkflowDraft } = useNodesSyncDraft()
  13. const { getNodesReadOnly } = useNodesReadOnly()
  14. const handleNodeDataUpdate = useCallback(({ id, data }: NodeDataUpdatePayload) => {
  15. const {
  16. getNodes,
  17. setNodes,
  18. } = store.getState()
  19. const newNodes = produce(getNodes(), (draft) => {
  20. const currentNode = draft.find(node => node.id === id)!
  21. if (currentNode)
  22. currentNode.data = { ...currentNode.data, ...data }
  23. })
  24. setNodes(newNodes)
  25. }, [store])
  26. const handleNodeDataUpdateWithSyncDraft = useCallback((payload: NodeDataUpdatePayload) => {
  27. if (getNodesReadOnly())
  28. return
  29. handleNodeDataUpdate(payload)
  30. handleSyncWorkflowDraft()
  31. }, [handleSyncWorkflowDraft, handleNodeDataUpdate, getNodesReadOnly])
  32. return {
  33. handleNodeDataUpdate,
  34. handleNodeDataUpdateWithSyncDraft,
  35. }
  36. }