use-nodes-interactions.ts 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  1. import type { MouseEvent } from 'react'
  2. import { useCallback, useRef } from 'react'
  3. import { useTranslation } from 'react-i18next'
  4. import produce from 'immer'
  5. import type {
  6. NodeDragHandler,
  7. NodeMouseHandler,
  8. OnConnect,
  9. OnConnectEnd,
  10. OnConnectStart,
  11. ResizeParamsWithDirection,
  12. } from 'reactflow'
  13. import {
  14. getConnectedEdges,
  15. getOutgoers,
  16. useReactFlow,
  17. useStoreApi,
  18. } from 'reactflow'
  19. import { unionBy } from 'lodash-es'
  20. import type { ToolDefaultValue } from '../block-selector/types'
  21. import type {
  22. Edge,
  23. Node,
  24. OnNodeAdd,
  25. } from '../types'
  26. import { BlockEnum } from '../types'
  27. import { useWorkflowStore } from '../store'
  28. import {
  29. CUSTOM_EDGE,
  30. ITERATION_CHILDREN_Z_INDEX,
  31. ITERATION_PADDING,
  32. NODES_INITIAL_DATA,
  33. NODE_WIDTH_X_OFFSET,
  34. X_OFFSET,
  35. Y_OFFSET,
  36. } from '../constants'
  37. import {
  38. genNewNodeTitleFromOld,
  39. generateNewNode,
  40. getNodesConnectedSourceOrTargetHandleIdsMap,
  41. getTopLeftNodePosition,
  42. } from '../utils'
  43. import { CUSTOM_NOTE_NODE } from '../note-node/constants'
  44. import type { IterationNodeType } from '../nodes/iteration/types'
  45. import { CUSTOM_ITERATION_START_NODE } from '../nodes/iteration-start/constants'
  46. import type { VariableAssignerNodeType } from '../nodes/variable-assigner/types'
  47. import { useNodeIterationInteractions } from '../nodes/iteration/use-interactions'
  48. import { useWorkflowHistoryStore } from '../workflow-history-store'
  49. import { useNodesSyncDraft } from './use-nodes-sync-draft'
  50. import { useHelpline } from './use-helpline'
  51. import {
  52. useNodesReadOnly,
  53. useWorkflow,
  54. useWorkflowReadOnly,
  55. } from './use-workflow'
  56. import { WorkflowHistoryEvent, useWorkflowHistory } from './use-workflow-history'
  57. export const useNodesInteractions = () => {
  58. const { t } = useTranslation()
  59. const store = useStoreApi()
  60. const workflowStore = useWorkflowStore()
  61. const reactflow = useReactFlow()
  62. const { store: workflowHistoryStore } = useWorkflowHistoryStore()
  63. const { handleSyncWorkflowDraft } = useNodesSyncDraft()
  64. const {
  65. checkNestedParallelLimit,
  66. getAfterNodesInSameBranch,
  67. } = useWorkflow()
  68. const { getNodesReadOnly } = useNodesReadOnly()
  69. const { getWorkflowReadOnly } = useWorkflowReadOnly()
  70. const { handleSetHelpline } = useHelpline()
  71. const {
  72. handleNodeIterationChildDrag,
  73. handleNodeIterationChildrenCopy,
  74. } = useNodeIterationInteractions()
  75. const dragNodeStartPosition = useRef({ x: 0, y: 0 } as { x: number; y: number })
  76. const { saveStateToHistory, undo, redo } = useWorkflowHistory()
  77. const handleNodeDragStart = useCallback<NodeDragHandler>((_, node) => {
  78. workflowStore.setState({ nodeAnimation: false })
  79. if (getNodesReadOnly())
  80. return
  81. if (node.type === CUSTOM_ITERATION_START_NODE || node.type === CUSTOM_NOTE_NODE)
  82. return
  83. dragNodeStartPosition.current = { x: node.position.x, y: node.position.y }
  84. }, [workflowStore, getNodesReadOnly])
  85. const handleNodeDrag = useCallback<NodeDragHandler>((e, node: Node) => {
  86. if (getNodesReadOnly())
  87. return
  88. if (node.type === CUSTOM_ITERATION_START_NODE)
  89. return
  90. const {
  91. getNodes,
  92. setNodes,
  93. } = store.getState()
  94. e.stopPropagation()
  95. const nodes = getNodes()
  96. const { restrictPosition } = handleNodeIterationChildDrag(node)
  97. const {
  98. showHorizontalHelpLineNodes,
  99. showVerticalHelpLineNodes,
  100. } = handleSetHelpline(node)
  101. const showHorizontalHelpLineNodesLength = showHorizontalHelpLineNodes.length
  102. const showVerticalHelpLineNodesLength = showVerticalHelpLineNodes.length
  103. const newNodes = produce(nodes, (draft) => {
  104. const currentNode = draft.find(n => n.id === node.id)!
  105. if (showVerticalHelpLineNodesLength > 0)
  106. currentNode.position.x = showVerticalHelpLineNodes[0].position.x
  107. else if (restrictPosition.x !== undefined)
  108. currentNode.position.x = restrictPosition.x
  109. else
  110. currentNode.position.x = node.position.x
  111. if (showHorizontalHelpLineNodesLength > 0)
  112. currentNode.position.y = showHorizontalHelpLineNodes[0].position.y
  113. else if (restrictPosition.y !== undefined)
  114. currentNode.position.y = restrictPosition.y
  115. else
  116. currentNode.position.y = node.position.y
  117. })
  118. setNodes(newNodes)
  119. }, [store, getNodesReadOnly, handleSetHelpline, handleNodeIterationChildDrag])
  120. const handleNodeDragStop = useCallback<NodeDragHandler>((_, node) => {
  121. const {
  122. setHelpLineHorizontal,
  123. setHelpLineVertical,
  124. } = workflowStore.getState()
  125. if (getNodesReadOnly())
  126. return
  127. const { x, y } = dragNodeStartPosition.current
  128. if (!(x === node.position.x && y === node.position.y)) {
  129. setHelpLineHorizontal()
  130. setHelpLineVertical()
  131. handleSyncWorkflowDraft()
  132. if (x !== 0 && y !== 0) {
  133. // selecting a note will trigger a drag stop event with x and y as 0
  134. saveStateToHistory(WorkflowHistoryEvent.NodeDragStop)
  135. }
  136. }
  137. }, [workflowStore, getNodesReadOnly, saveStateToHistory, handleSyncWorkflowDraft])
  138. const handleNodeEnter = useCallback<NodeMouseHandler>((_, node) => {
  139. if (getNodesReadOnly())
  140. return
  141. if (node.type === CUSTOM_NOTE_NODE || node.type === CUSTOM_ITERATION_START_NODE)
  142. return
  143. const {
  144. getNodes,
  145. setNodes,
  146. edges,
  147. setEdges,
  148. } = store.getState()
  149. const nodes = getNodes()
  150. const {
  151. connectingNodePayload,
  152. setEnteringNodePayload,
  153. } = workflowStore.getState()
  154. if (connectingNodePayload) {
  155. if (connectingNodePayload.nodeId === node.id)
  156. return
  157. const connectingNode: Node = nodes.find(n => n.id === connectingNodePayload.nodeId)!
  158. const sameLevel = connectingNode.parentId === node.parentId
  159. if (sameLevel) {
  160. setEnteringNodePayload({
  161. nodeId: node.id,
  162. nodeData: node.data as VariableAssignerNodeType,
  163. })
  164. const fromType = connectingNodePayload.handleType
  165. const newNodes = produce(nodes, (draft) => {
  166. draft.forEach((n) => {
  167. if (n.id === node.id && fromType === 'source' && (node.data.type === BlockEnum.VariableAssigner || node.data.type === BlockEnum.VariableAggregator)) {
  168. if (!node.data.advanced_settings?.group_enabled)
  169. n.data._isEntering = true
  170. }
  171. if (n.id === node.id && fromType === 'target' && (connectingNode.data.type === BlockEnum.VariableAssigner || connectingNode.data.type === BlockEnum.VariableAggregator) && node.data.type !== BlockEnum.IfElse && node.data.type !== BlockEnum.QuestionClassifier)
  172. n.data._isEntering = true
  173. })
  174. })
  175. setNodes(newNodes)
  176. }
  177. }
  178. const newEdges = produce(edges, (draft) => {
  179. const connectedEdges = getConnectedEdges([node], edges)
  180. connectedEdges.forEach((edge) => {
  181. const currentEdge = draft.find(e => e.id === edge.id)
  182. if (currentEdge)
  183. currentEdge.data._connectedNodeIsHovering = true
  184. })
  185. })
  186. setEdges(newEdges)
  187. const connectedEdges = getConnectedEdges([node], edges).filter(edge => edge.target === node.id)
  188. const targetNodes: Node[] = []
  189. for (let i = 0; i < connectedEdges.length; i++) {
  190. const sourceConnectedEdges = getConnectedEdges([{ id: connectedEdges[i].source } as Node], edges).filter(edge => edge.source === connectedEdges[i].source && edge.sourceHandle === connectedEdges[i].sourceHandle)
  191. targetNodes.push(...sourceConnectedEdges.map(edge => nodes.find(n => n.id === edge.target)!))
  192. }
  193. const uniqTargetNodes = unionBy(targetNodes, 'id')
  194. if (uniqTargetNodes.length > 1) {
  195. const newNodes = produce(nodes, (draft) => {
  196. draft.forEach((n) => {
  197. if (uniqTargetNodes.some(targetNode => n.id === targetNode.id))
  198. n.data._inParallelHovering = true
  199. })
  200. })
  201. setNodes(newNodes)
  202. }
  203. }, [store, workflowStore, getNodesReadOnly])
  204. const handleNodeLeave = useCallback<NodeMouseHandler>((_, node) => {
  205. if (getNodesReadOnly())
  206. return
  207. if (node.type === CUSTOM_NOTE_NODE || node.type === CUSTOM_ITERATION_START_NODE)
  208. return
  209. const {
  210. setEnteringNodePayload,
  211. } = workflowStore.getState()
  212. setEnteringNodePayload(undefined)
  213. const {
  214. getNodes,
  215. setNodes,
  216. edges,
  217. setEdges,
  218. } = store.getState()
  219. const newNodes = produce(getNodes(), (draft) => {
  220. draft.forEach((node) => {
  221. node.data._isEntering = false
  222. node.data._inParallelHovering = false
  223. })
  224. })
  225. setNodes(newNodes)
  226. const newEdges = produce(edges, (draft) => {
  227. draft.forEach((edge) => {
  228. edge.data._connectedNodeIsHovering = false
  229. })
  230. })
  231. setEdges(newEdges)
  232. }, [store, workflowStore, getNodesReadOnly])
  233. const handleNodeSelect = useCallback((nodeId: string, cancelSelection?: boolean) => {
  234. const {
  235. getNodes,
  236. setNodes,
  237. edges,
  238. setEdges,
  239. } = store.getState()
  240. const nodes = getNodes()
  241. const selectedNode = nodes.find(node => node.data.selected)
  242. if (!cancelSelection && selectedNode?.id === nodeId)
  243. return
  244. const newNodes = produce(nodes, (draft) => {
  245. draft.forEach((node) => {
  246. if (node.id === nodeId)
  247. node.data.selected = !cancelSelection
  248. else
  249. node.data.selected = false
  250. })
  251. })
  252. setNodes(newNodes)
  253. const connectedEdges = getConnectedEdges([{ id: nodeId } as Node], edges).map(edge => edge.id)
  254. const newEdges = produce(edges, (draft) => {
  255. draft.forEach((edge) => {
  256. if (connectedEdges.includes(edge.id)) {
  257. edge.data = {
  258. ...edge.data,
  259. _connectedNodeIsSelected: !cancelSelection,
  260. }
  261. }
  262. else {
  263. edge.data = {
  264. ...edge.data,
  265. _connectedNodeIsSelected: false,
  266. }
  267. }
  268. })
  269. })
  270. setEdges(newEdges)
  271. handleSyncWorkflowDraft()
  272. }, [store, handleSyncWorkflowDraft])
  273. const handleNodeClick = useCallback<NodeMouseHandler>((_, node) => {
  274. if (node.type === CUSTOM_ITERATION_START_NODE)
  275. return
  276. handleNodeSelect(node.id)
  277. }, [handleNodeSelect])
  278. const handleNodeConnect = useCallback<OnConnect>(({
  279. source,
  280. sourceHandle,
  281. target,
  282. targetHandle,
  283. }) => {
  284. if (source === target)
  285. return
  286. if (getNodesReadOnly())
  287. return
  288. const {
  289. getNodes,
  290. setNodes,
  291. edges,
  292. setEdges,
  293. } = store.getState()
  294. const nodes = getNodes()
  295. const targetNode = nodes.find(node => node.id === target!)
  296. const sourceNode = nodes.find(node => node.id === source!)
  297. if (targetNode?.parentId !== sourceNode?.parentId)
  298. return
  299. if (sourceNode?.type === CUSTOM_NOTE_NODE || targetNode?.type === CUSTOM_NOTE_NODE)
  300. return
  301. if (edges.find(edge => edge.source === source && edge.sourceHandle === sourceHandle && edge.target === target && edge.targetHandle === targetHandle))
  302. return
  303. const newEdge = {
  304. id: `${source}-${sourceHandle}-${target}-${targetHandle}`,
  305. type: CUSTOM_EDGE,
  306. source: source!,
  307. target: target!,
  308. sourceHandle,
  309. targetHandle,
  310. data: {
  311. sourceType: nodes.find(node => node.id === source)!.data.type,
  312. targetType: nodes.find(node => node.id === target)!.data.type,
  313. isInIteration: !!targetNode?.parentId,
  314. iteration_id: targetNode?.parentId,
  315. },
  316. zIndex: targetNode?.parentId ? ITERATION_CHILDREN_Z_INDEX : 0,
  317. }
  318. const nodesConnectedSourceOrTargetHandleIdsMap = getNodesConnectedSourceOrTargetHandleIdsMap(
  319. [
  320. { type: 'add', edge: newEdge },
  321. ],
  322. nodes,
  323. )
  324. const newNodes = produce(nodes, (draft: Node[]) => {
  325. draft.forEach((node) => {
  326. if (nodesConnectedSourceOrTargetHandleIdsMap[node.id]) {
  327. node.data = {
  328. ...node.data,
  329. ...nodesConnectedSourceOrTargetHandleIdsMap[node.id],
  330. }
  331. }
  332. })
  333. })
  334. const newEdges = produce(edges, (draft) => {
  335. draft.push(newEdge)
  336. })
  337. if (checkNestedParallelLimit(newNodes, newEdges, targetNode?.parentId)) {
  338. setNodes(newNodes)
  339. setEdges(newEdges)
  340. handleSyncWorkflowDraft()
  341. saveStateToHistory(WorkflowHistoryEvent.NodeConnect)
  342. }
  343. else {
  344. const {
  345. setConnectingNodePayload,
  346. setEnteringNodePayload,
  347. } = workflowStore.getState()
  348. setConnectingNodePayload(undefined)
  349. setEnteringNodePayload(undefined)
  350. }
  351. }, [getNodesReadOnly, store, workflowStore, handleSyncWorkflowDraft, saveStateToHistory, checkNestedParallelLimit])
  352. const handleNodeConnectStart = useCallback<OnConnectStart>((_, { nodeId, handleType, handleId }) => {
  353. if (getNodesReadOnly())
  354. return
  355. if (nodeId && handleType) {
  356. const { setConnectingNodePayload } = workflowStore.getState()
  357. const { getNodes } = store.getState()
  358. const node = getNodes().find(n => n.id === nodeId)!
  359. if (node.type === CUSTOM_NOTE_NODE)
  360. return
  361. if (node.data.type === BlockEnum.VariableAggregator || node.data.type === BlockEnum.VariableAssigner) {
  362. if (handleType === 'target')
  363. return
  364. }
  365. setConnectingNodePayload({
  366. nodeId,
  367. nodeType: node.data.type,
  368. handleType,
  369. handleId,
  370. })
  371. }
  372. }, [store, workflowStore, getNodesReadOnly])
  373. const handleNodeConnectEnd = useCallback<OnConnectEnd>((e: any) => {
  374. if (getNodesReadOnly())
  375. return
  376. const {
  377. connectingNodePayload,
  378. setConnectingNodePayload,
  379. enteringNodePayload,
  380. setEnteringNodePayload,
  381. } = workflowStore.getState()
  382. if (connectingNodePayload && enteringNodePayload) {
  383. const {
  384. setShowAssignVariablePopup,
  385. hoveringAssignVariableGroupId,
  386. } = workflowStore.getState()
  387. const { screenToFlowPosition } = reactflow
  388. const {
  389. getNodes,
  390. setNodes,
  391. } = store.getState()
  392. const nodes = getNodes()
  393. const fromHandleType = connectingNodePayload.handleType
  394. const fromHandleId = connectingNodePayload.handleId
  395. const fromNode = nodes.find(n => n.id === connectingNodePayload.nodeId)!
  396. const toNode = nodes.find(n => n.id === enteringNodePayload.nodeId)!
  397. const toParentNode = nodes.find(n => n.id === toNode.parentId)
  398. if (fromNode.parentId !== toNode.parentId)
  399. return
  400. const { x, y } = screenToFlowPosition({ x: e.x, y: e.y })
  401. if (fromHandleType === 'source' && (toNode.data.type === BlockEnum.VariableAssigner || toNode.data.type === BlockEnum.VariableAggregator)) {
  402. const groupEnabled = toNode.data.advanced_settings?.group_enabled
  403. const firstGroupId = toNode.data.advanced_settings?.groups[0].groupId
  404. let handleId = 'target'
  405. if (groupEnabled) {
  406. if (hoveringAssignVariableGroupId)
  407. handleId = hoveringAssignVariableGroupId
  408. else
  409. handleId = firstGroupId
  410. }
  411. const newNodes = produce(nodes, (draft) => {
  412. draft.forEach((node) => {
  413. if (node.id === toNode.id) {
  414. node.data._showAddVariablePopup = true
  415. node.data._holdAddVariablePopup = true
  416. }
  417. })
  418. })
  419. setNodes(newNodes)
  420. setShowAssignVariablePopup({
  421. nodeId: fromNode.id,
  422. nodeData: fromNode.data,
  423. variableAssignerNodeId: toNode.id,
  424. variableAssignerNodeData: toNode.data,
  425. variableAssignerNodeHandleId: handleId,
  426. parentNode: toParentNode,
  427. x: x - toNode.positionAbsolute!.x,
  428. y: y - toNode.positionAbsolute!.y,
  429. })
  430. handleNodeConnect({
  431. source: fromNode.id,
  432. sourceHandle: fromHandleId,
  433. target: toNode.id,
  434. targetHandle: 'target',
  435. })
  436. }
  437. }
  438. setConnectingNodePayload(undefined)
  439. setEnteringNodePayload(undefined)
  440. }, [store, handleNodeConnect, getNodesReadOnly, workflowStore, reactflow])
  441. const handleNodeDelete = useCallback((nodeId: string) => {
  442. if (getNodesReadOnly())
  443. return
  444. const {
  445. getNodes,
  446. setNodes,
  447. edges,
  448. setEdges,
  449. } = store.getState()
  450. const nodes = getNodes()
  451. const currentNodeIndex = nodes.findIndex(node => node.id === nodeId)
  452. const currentNode = nodes[currentNodeIndex]
  453. if (!currentNode)
  454. return
  455. if (currentNode.data.type === BlockEnum.Start)
  456. return
  457. if (currentNode.data.type === BlockEnum.Iteration) {
  458. const iterationChildren = nodes.filter(node => node.parentId === currentNode.id)
  459. if (iterationChildren.length) {
  460. if (currentNode.data._isBundled) {
  461. iterationChildren.forEach((child) => {
  462. handleNodeDelete(child.id)
  463. })
  464. return handleNodeDelete(nodeId)
  465. }
  466. else {
  467. if (iterationChildren.length === 1) {
  468. handleNodeDelete(iterationChildren[0].id)
  469. handleNodeDelete(nodeId)
  470. return
  471. }
  472. const { setShowConfirm, showConfirm } = workflowStore.getState()
  473. if (!showConfirm) {
  474. setShowConfirm({
  475. title: t('workflow.nodes.iteration.deleteTitle'),
  476. desc: t('workflow.nodes.iteration.deleteDesc') || '',
  477. onConfirm: () => {
  478. iterationChildren.forEach((child) => {
  479. handleNodeDelete(child.id)
  480. })
  481. handleNodeDelete(nodeId)
  482. handleSyncWorkflowDraft()
  483. setShowConfirm(undefined)
  484. },
  485. })
  486. return
  487. }
  488. }
  489. }
  490. }
  491. const connectedEdges = getConnectedEdges([{ id: nodeId } as Node], edges)
  492. const nodesConnectedSourceOrTargetHandleIdsMap = getNodesConnectedSourceOrTargetHandleIdsMap(connectedEdges.map(edge => ({ type: 'remove', edge })), nodes)
  493. const newNodes = produce(nodes, (draft: Node[]) => {
  494. draft.forEach((node) => {
  495. if (nodesConnectedSourceOrTargetHandleIdsMap[node.id]) {
  496. node.data = {
  497. ...node.data,
  498. ...nodesConnectedSourceOrTargetHandleIdsMap[node.id],
  499. }
  500. }
  501. if (node.id === currentNode.parentId)
  502. node.data._children = node.data._children?.filter(child => child !== nodeId)
  503. })
  504. draft.splice(currentNodeIndex, 1)
  505. })
  506. setNodes(newNodes)
  507. const newEdges = produce(edges, (draft) => {
  508. return draft.filter(edge => !connectedEdges.find(connectedEdge => connectedEdge.id === edge.id))
  509. })
  510. setEdges(newEdges)
  511. handleSyncWorkflowDraft()
  512. if (currentNode.type === CUSTOM_NOTE_NODE)
  513. saveStateToHistory(WorkflowHistoryEvent.NoteDelete)
  514. else
  515. saveStateToHistory(WorkflowHistoryEvent.NodeDelete)
  516. }, [getNodesReadOnly, store, handleSyncWorkflowDraft, saveStateToHistory, workflowStore, t])
  517. const handleNodeAdd = useCallback<OnNodeAdd>((
  518. {
  519. nodeType,
  520. sourceHandle = 'source',
  521. targetHandle = 'target',
  522. toolDefaultValue,
  523. },
  524. {
  525. prevNodeId,
  526. prevNodeSourceHandle,
  527. nextNodeId,
  528. nextNodeTargetHandle,
  529. },
  530. ) => {
  531. if (getNodesReadOnly())
  532. return
  533. const {
  534. getNodes,
  535. setNodes,
  536. edges,
  537. setEdges,
  538. } = store.getState()
  539. const nodes = getNodes()
  540. const nodesWithSameType = nodes.filter(node => node.data.type === nodeType)
  541. const {
  542. newNode,
  543. newIterationStartNode,
  544. } = generateNewNode({
  545. data: {
  546. ...NODES_INITIAL_DATA[nodeType],
  547. title: nodesWithSameType.length > 0 ? `${t(`workflow.blocks.${nodeType}`)} ${nodesWithSameType.length + 1}` : t(`workflow.blocks.${nodeType}`),
  548. ...(toolDefaultValue || {}),
  549. selected: true,
  550. _showAddVariablePopup: (nodeType === BlockEnum.VariableAssigner || nodeType === BlockEnum.VariableAggregator) && !!prevNodeId,
  551. _holdAddVariablePopup: false,
  552. },
  553. position: {
  554. x: 0,
  555. y: 0,
  556. },
  557. })
  558. if (prevNodeId && !nextNodeId) {
  559. const prevNodeIndex = nodes.findIndex(node => node.id === prevNodeId)
  560. const prevNode = nodes[prevNodeIndex]
  561. const outgoers = getOutgoers(prevNode, nodes, edges).sort((a, b) => a.position.y - b.position.y)
  562. const lastOutgoer = outgoers[outgoers.length - 1]
  563. newNode.data._connectedTargetHandleIds = [targetHandle]
  564. newNode.data._connectedSourceHandleIds = []
  565. newNode.position = {
  566. x: lastOutgoer ? lastOutgoer.position.x : prevNode.position.x + prevNode.width! + X_OFFSET,
  567. y: lastOutgoer ? lastOutgoer.position.y + lastOutgoer.height! + Y_OFFSET : prevNode.position.y,
  568. }
  569. newNode.parentId = prevNode.parentId
  570. newNode.extent = prevNode.extent
  571. if (prevNode.parentId) {
  572. newNode.data.isInIteration = true
  573. newNode.data.iteration_id = prevNode.parentId
  574. newNode.zIndex = ITERATION_CHILDREN_Z_INDEX
  575. if (newNode.data.type === BlockEnum.Answer || newNode.data.type === BlockEnum.Tool || newNode.data.type === BlockEnum.Assigner) {
  576. const parentIterNodeIndex = nodes.findIndex(node => node.id === prevNode.parentId)
  577. const iterNodeData: IterationNodeType = nodes[parentIterNodeIndex].data
  578. iterNodeData._isShowTips = true
  579. }
  580. }
  581. const newEdge: Edge = {
  582. id: `${prevNodeId}-${prevNodeSourceHandle}-${newNode.id}-${targetHandle}`,
  583. type: CUSTOM_EDGE,
  584. source: prevNodeId,
  585. sourceHandle: prevNodeSourceHandle,
  586. target: newNode.id,
  587. targetHandle,
  588. data: {
  589. sourceType: prevNode.data.type,
  590. targetType: newNode.data.type,
  591. isInIteration: !!prevNode.parentId,
  592. iteration_id: prevNode.parentId,
  593. _connectedNodeIsSelected: true,
  594. },
  595. zIndex: prevNode.parentId ? ITERATION_CHILDREN_Z_INDEX : 0,
  596. }
  597. const nodesConnectedSourceOrTargetHandleIdsMap = getNodesConnectedSourceOrTargetHandleIdsMap(
  598. [
  599. { type: 'add', edge: newEdge },
  600. ],
  601. nodes,
  602. )
  603. const newNodes = produce(nodes, (draft: Node[]) => {
  604. draft.forEach((node) => {
  605. node.data.selected = false
  606. if (nodesConnectedSourceOrTargetHandleIdsMap[node.id]) {
  607. node.data = {
  608. ...node.data,
  609. ...nodesConnectedSourceOrTargetHandleIdsMap[node.id],
  610. }
  611. }
  612. if (node.data.type === BlockEnum.Iteration && prevNode.parentId === node.id)
  613. node.data._children?.push(newNode.id)
  614. })
  615. draft.push(newNode)
  616. if (newIterationStartNode)
  617. draft.push(newIterationStartNode)
  618. })
  619. if (newNode.data.type === BlockEnum.VariableAssigner || newNode.data.type === BlockEnum.VariableAggregator) {
  620. const { setShowAssignVariablePopup } = workflowStore.getState()
  621. setShowAssignVariablePopup({
  622. nodeId: prevNode.id,
  623. nodeData: prevNode.data,
  624. variableAssignerNodeId: newNode.id,
  625. variableAssignerNodeData: (newNode.data as VariableAssignerNodeType),
  626. variableAssignerNodeHandleId: targetHandle,
  627. parentNode: nodes.find(node => node.id === newNode.parentId),
  628. x: -25,
  629. y: 44,
  630. })
  631. }
  632. const newEdges = produce(edges, (draft) => {
  633. draft.forEach((item) => {
  634. item.data = {
  635. ...item.data,
  636. _connectedNodeIsSelected: false,
  637. }
  638. })
  639. draft.push(newEdge)
  640. })
  641. if (checkNestedParallelLimit(newNodes, newEdges, prevNode.parentId)) {
  642. setNodes(newNodes)
  643. setEdges(newEdges)
  644. }
  645. else {
  646. return false
  647. }
  648. }
  649. if (!prevNodeId && nextNodeId) {
  650. const nextNodeIndex = nodes.findIndex(node => node.id === nextNodeId)
  651. const nextNode = nodes[nextNodeIndex]!
  652. if ((nodeType !== BlockEnum.IfElse) && (nodeType !== BlockEnum.QuestionClassifier))
  653. newNode.data._connectedSourceHandleIds = [sourceHandle]
  654. newNode.data._connectedTargetHandleIds = []
  655. newNode.position = {
  656. x: nextNode.position.x,
  657. y: nextNode.position.y,
  658. }
  659. newNode.parentId = nextNode.parentId
  660. newNode.extent = nextNode.extent
  661. if (nextNode.parentId) {
  662. newNode.data.isInIteration = true
  663. newNode.data.iteration_id = nextNode.parentId
  664. newNode.zIndex = ITERATION_CHILDREN_Z_INDEX
  665. }
  666. let newEdge
  667. if ((nodeType !== BlockEnum.IfElse) && (nodeType !== BlockEnum.QuestionClassifier)) {
  668. newEdge = {
  669. id: `${newNode.id}-${sourceHandle}-${nextNodeId}-${nextNodeTargetHandle}`,
  670. type: CUSTOM_EDGE,
  671. source: newNode.id,
  672. sourceHandle,
  673. target: nextNodeId,
  674. targetHandle: nextNodeTargetHandle,
  675. data: {
  676. sourceType: newNode.data.type,
  677. targetType: nextNode.data.type,
  678. isInIteration: !!nextNode.parentId,
  679. iteration_id: nextNode.parentId,
  680. _connectedNodeIsSelected: true,
  681. },
  682. zIndex: nextNode.parentId ? ITERATION_CHILDREN_Z_INDEX : 0,
  683. }
  684. }
  685. let nodesConnectedSourceOrTargetHandleIdsMap: Record<string, any>
  686. if (newEdge) {
  687. nodesConnectedSourceOrTargetHandleIdsMap = getNodesConnectedSourceOrTargetHandleIdsMap(
  688. [
  689. { type: 'add', edge: newEdge },
  690. ],
  691. nodes,
  692. )
  693. }
  694. const afterNodesInSameBranch = getAfterNodesInSameBranch(nextNodeId!)
  695. const afterNodesInSameBranchIds = afterNodesInSameBranch.map(node => node.id)
  696. const newNodes = produce(nodes, (draft) => {
  697. draft.forEach((node) => {
  698. node.data.selected = false
  699. if (afterNodesInSameBranchIds.includes(node.id))
  700. node.position.x += NODE_WIDTH_X_OFFSET
  701. if (nodesConnectedSourceOrTargetHandleIdsMap?.[node.id]) {
  702. node.data = {
  703. ...node.data,
  704. ...nodesConnectedSourceOrTargetHandleIdsMap[node.id],
  705. }
  706. }
  707. if (node.data.type === BlockEnum.Iteration && nextNode.parentId === node.id)
  708. node.data._children?.push(newNode.id)
  709. if (node.data.type === BlockEnum.Iteration && node.data.start_node_id === nextNodeId) {
  710. node.data.start_node_id = newNode.id
  711. node.data.startNodeType = newNode.data.type
  712. }
  713. })
  714. draft.push(newNode)
  715. if (newIterationStartNode)
  716. draft.push(newIterationStartNode)
  717. })
  718. if (newEdge) {
  719. const newEdges = produce(edges, (draft) => {
  720. draft.forEach((item) => {
  721. item.data = {
  722. ...item.data,
  723. _connectedNodeIsSelected: false,
  724. }
  725. })
  726. draft.push(newEdge)
  727. })
  728. if (checkNestedParallelLimit(newNodes, newEdges, nextNode.parentId)) {
  729. setNodes(newNodes)
  730. setEdges(newEdges)
  731. }
  732. else {
  733. return false
  734. }
  735. }
  736. else {
  737. if (checkNestedParallelLimit(newNodes, edges))
  738. setNodes(newNodes)
  739. else
  740. return false
  741. }
  742. }
  743. if (prevNodeId && nextNodeId) {
  744. const prevNode = nodes.find(node => node.id === prevNodeId)!
  745. const nextNode = nodes.find(node => node.id === nextNodeId)!
  746. newNode.data._connectedTargetHandleIds = [targetHandle]
  747. newNode.data._connectedSourceHandleIds = [sourceHandle]
  748. newNode.position = {
  749. x: nextNode.position.x,
  750. y: nextNode.position.y,
  751. }
  752. newNode.parentId = prevNode.parentId
  753. newNode.extent = prevNode.extent
  754. if (prevNode.parentId) {
  755. newNode.data.isInIteration = true
  756. newNode.data.iteration_id = prevNode.parentId
  757. newNode.zIndex = ITERATION_CHILDREN_Z_INDEX
  758. }
  759. const currentEdgeIndex = edges.findIndex(edge => edge.source === prevNodeId && edge.target === nextNodeId)
  760. const newPrevEdge = {
  761. id: `${prevNodeId}-${prevNodeSourceHandle}-${newNode.id}-${targetHandle}`,
  762. type: CUSTOM_EDGE,
  763. source: prevNodeId,
  764. sourceHandle: prevNodeSourceHandle,
  765. target: newNode.id,
  766. targetHandle,
  767. data: {
  768. sourceType: prevNode.data.type,
  769. targetType: newNode.data.type,
  770. isInIteration: !!prevNode.parentId,
  771. iteration_id: prevNode.parentId,
  772. _connectedNodeIsSelected: true,
  773. },
  774. zIndex: prevNode.parentId ? ITERATION_CHILDREN_Z_INDEX : 0,
  775. }
  776. let newNextEdge: Edge | null = null
  777. if (nodeType !== BlockEnum.IfElse && nodeType !== BlockEnum.QuestionClassifier) {
  778. newNextEdge = {
  779. id: `${newNode.id}-${sourceHandle}-${nextNodeId}-${nextNodeTargetHandle}`,
  780. type: CUSTOM_EDGE,
  781. source: newNode.id,
  782. sourceHandle,
  783. target: nextNodeId,
  784. targetHandle: nextNodeTargetHandle,
  785. data: {
  786. sourceType: newNode.data.type,
  787. targetType: nextNode.data.type,
  788. isInIteration: !!nextNode.parentId,
  789. iteration_id: nextNode.parentId,
  790. _connectedNodeIsSelected: true,
  791. },
  792. zIndex: nextNode.parentId ? ITERATION_CHILDREN_Z_INDEX : 0,
  793. }
  794. }
  795. const nodesConnectedSourceOrTargetHandleIdsMap = getNodesConnectedSourceOrTargetHandleIdsMap(
  796. [
  797. { type: 'remove', edge: edges[currentEdgeIndex] },
  798. { type: 'add', edge: newPrevEdge },
  799. ...(newNextEdge ? [{ type: 'add', edge: newNextEdge }] : []),
  800. ],
  801. [...nodes, newNode],
  802. )
  803. const afterNodesInSameBranch = getAfterNodesInSameBranch(nextNodeId!)
  804. const afterNodesInSameBranchIds = afterNodesInSameBranch.map(node => node.id)
  805. const newNodes = produce(nodes, (draft) => {
  806. draft.forEach((node) => {
  807. node.data.selected = false
  808. if (nodesConnectedSourceOrTargetHandleIdsMap[node.id]) {
  809. node.data = {
  810. ...node.data,
  811. ...nodesConnectedSourceOrTargetHandleIdsMap[node.id],
  812. }
  813. }
  814. if (afterNodesInSameBranchIds.includes(node.id))
  815. node.position.x += NODE_WIDTH_X_OFFSET
  816. if (node.data.type === BlockEnum.Iteration && prevNode.parentId === node.id)
  817. node.data._children?.push(newNode.id)
  818. })
  819. draft.push(newNode)
  820. if (newIterationStartNode)
  821. draft.push(newIterationStartNode)
  822. })
  823. setNodes(newNodes)
  824. if (newNode.data.type === BlockEnum.VariableAssigner || newNode.data.type === BlockEnum.VariableAggregator) {
  825. const { setShowAssignVariablePopup } = workflowStore.getState()
  826. setShowAssignVariablePopup({
  827. nodeId: prevNode.id,
  828. nodeData: prevNode.data,
  829. variableAssignerNodeId: newNode.id,
  830. variableAssignerNodeData: newNode.data as VariableAssignerNodeType,
  831. variableAssignerNodeHandleId: targetHandle,
  832. parentNode: nodes.find(node => node.id === newNode.parentId),
  833. x: -25,
  834. y: 44,
  835. })
  836. }
  837. const newEdges = produce(edges, (draft) => {
  838. draft.splice(currentEdgeIndex, 1)
  839. draft.forEach((item) => {
  840. item.data = {
  841. ...item.data,
  842. _connectedNodeIsSelected: false,
  843. }
  844. })
  845. draft.push(newPrevEdge)
  846. if (newNextEdge)
  847. draft.push(newNextEdge)
  848. })
  849. setEdges(newEdges)
  850. }
  851. handleSyncWorkflowDraft()
  852. saveStateToHistory(WorkflowHistoryEvent.NodeAdd)
  853. }, [getNodesReadOnly, store, t, handleSyncWorkflowDraft, saveStateToHistory, workflowStore, getAfterNodesInSameBranch, checkNestedParallelLimit])
  854. const handleNodeChange = useCallback((
  855. currentNodeId: string,
  856. nodeType: BlockEnum,
  857. sourceHandle: string,
  858. toolDefaultValue?: ToolDefaultValue,
  859. ) => {
  860. if (getNodesReadOnly())
  861. return
  862. const {
  863. getNodes,
  864. setNodes,
  865. edges,
  866. setEdges,
  867. } = store.getState()
  868. const nodes = getNodes()
  869. const currentNode = nodes.find(node => node.id === currentNodeId)!
  870. const connectedEdges = getConnectedEdges([currentNode], edges)
  871. const nodesWithSameType = nodes.filter(node => node.data.type === nodeType)
  872. const {
  873. newNode: newCurrentNode,
  874. newIterationStartNode,
  875. } = generateNewNode({
  876. data: {
  877. ...NODES_INITIAL_DATA[nodeType],
  878. title: nodesWithSameType.length > 0 ? `${t(`workflow.blocks.${nodeType}`)} ${nodesWithSameType.length + 1}` : t(`workflow.blocks.${nodeType}`),
  879. ...(toolDefaultValue || {}),
  880. _connectedSourceHandleIds: [],
  881. _connectedTargetHandleIds: [],
  882. selected: currentNode.data.selected,
  883. isInIteration: currentNode.data.isInIteration,
  884. iteration_id: currentNode.data.iteration_id,
  885. },
  886. position: {
  887. x: currentNode.position.x,
  888. y: currentNode.position.y,
  889. },
  890. parentId: currentNode.parentId,
  891. extent: currentNode.extent,
  892. zIndex: currentNode.zIndex,
  893. })
  894. const nodesConnectedSourceOrTargetHandleIdsMap = getNodesConnectedSourceOrTargetHandleIdsMap(
  895. [
  896. ...connectedEdges.map(edge => ({ type: 'remove', edge })),
  897. ],
  898. nodes,
  899. )
  900. const newNodes = produce(nodes, (draft) => {
  901. draft.forEach((node) => {
  902. node.data.selected = false
  903. if (nodesConnectedSourceOrTargetHandleIdsMap[node.id]) {
  904. node.data = {
  905. ...node.data,
  906. ...nodesConnectedSourceOrTargetHandleIdsMap[node.id],
  907. }
  908. }
  909. })
  910. const index = draft.findIndex(node => node.id === currentNodeId)
  911. draft.splice(index, 1, newCurrentNode)
  912. if (newIterationStartNode)
  913. draft.push(newIterationStartNode)
  914. })
  915. setNodes(newNodes)
  916. const newEdges = produce(edges, (draft) => {
  917. const filtered = draft.filter(edge => !connectedEdges.find(connectedEdge => connectedEdge.id === edge.id))
  918. return filtered
  919. })
  920. setEdges(newEdges)
  921. handleSyncWorkflowDraft()
  922. saveStateToHistory(WorkflowHistoryEvent.NodeChange)
  923. }, [getNodesReadOnly, store, t, handleSyncWorkflowDraft, saveStateToHistory])
  924. const handleNodeCancelRunningStatus = useCallback(() => {
  925. const {
  926. getNodes,
  927. setNodes,
  928. } = store.getState()
  929. const nodes = getNodes()
  930. const newNodes = produce(nodes, (draft) => {
  931. draft.forEach((node) => {
  932. node.data._runningStatus = undefined
  933. })
  934. })
  935. setNodes(newNodes)
  936. }, [store])
  937. const handleNodesCancelSelected = useCallback(() => {
  938. const {
  939. getNodes,
  940. setNodes,
  941. } = store.getState()
  942. const nodes = getNodes()
  943. const newNodes = produce(nodes, (draft) => {
  944. draft.forEach((node) => {
  945. node.data.selected = false
  946. })
  947. })
  948. setNodes(newNodes)
  949. }, [store])
  950. const handleNodeContextMenu = useCallback((e: MouseEvent, node: Node) => {
  951. if (node.type === CUSTOM_NOTE_NODE || node.type === CUSTOM_ITERATION_START_NODE)
  952. return
  953. e.preventDefault()
  954. const container = document.querySelector('#workflow-container')
  955. const { x, y } = container!.getBoundingClientRect()
  956. workflowStore.setState({
  957. nodeMenu: {
  958. top: e.clientY - y,
  959. left: e.clientX - x,
  960. nodeId: node.id,
  961. },
  962. })
  963. handleNodeSelect(node.id)
  964. }, [workflowStore, handleNodeSelect])
  965. const handleNodesCopy = useCallback((nodeId?: string) => {
  966. if (getNodesReadOnly())
  967. return
  968. const { setClipboardElements } = workflowStore.getState()
  969. const {
  970. getNodes,
  971. } = store.getState()
  972. const nodes = getNodes()
  973. if (nodeId) {
  974. // If nodeId is provided, copy that specific node
  975. const nodeToCopy = nodes.find(node => node.id === nodeId && node.data.type !== BlockEnum.Start && node.type !== CUSTOM_ITERATION_START_NODE)
  976. if (nodeToCopy)
  977. setClipboardElements([nodeToCopy])
  978. }
  979. else {
  980. // If no nodeId is provided, fall back to the current behavior
  981. const bundledNodes = nodes.filter(node => node.data._isBundled && node.data.type !== BlockEnum.Start && !node.data.isInIteration)
  982. if (bundledNodes.length) {
  983. setClipboardElements(bundledNodes)
  984. return
  985. }
  986. const selectedNode = nodes.find(node => node.data.selected && node.data.type !== BlockEnum.Start)
  987. if (selectedNode)
  988. setClipboardElements([selectedNode])
  989. }
  990. }, [getNodesReadOnly, store, workflowStore])
  991. const handleNodesPaste = useCallback(() => {
  992. if (getNodesReadOnly())
  993. return
  994. const {
  995. clipboardElements,
  996. mousePosition,
  997. } = workflowStore.getState()
  998. const {
  999. getNodes,
  1000. setNodes,
  1001. } = store.getState()
  1002. const nodesToPaste: Node[] = []
  1003. const nodes = getNodes()
  1004. if (clipboardElements.length) {
  1005. const { x, y } = getTopLeftNodePosition(clipboardElements)
  1006. const { screenToFlowPosition } = reactflow
  1007. const currentPosition = screenToFlowPosition({ x: mousePosition.pageX, y: mousePosition.pageY })
  1008. const offsetX = currentPosition.x - x
  1009. const offsetY = currentPosition.y - y
  1010. clipboardElements.forEach((nodeToPaste, index) => {
  1011. const nodeType = nodeToPaste.data.type
  1012. const {
  1013. newNode,
  1014. newIterationStartNode,
  1015. } = generateNewNode({
  1016. type: nodeToPaste.type,
  1017. data: {
  1018. ...NODES_INITIAL_DATA[nodeType],
  1019. ...nodeToPaste.data,
  1020. selected: false,
  1021. _isBundled: false,
  1022. _connectedSourceHandleIds: [],
  1023. _connectedTargetHandleIds: [],
  1024. title: genNewNodeTitleFromOld(nodeToPaste.data.title),
  1025. },
  1026. position: {
  1027. x: nodeToPaste.position.x + offsetX,
  1028. y: nodeToPaste.position.y + offsetY,
  1029. },
  1030. extent: nodeToPaste.extent,
  1031. zIndex: nodeToPaste.zIndex,
  1032. })
  1033. newNode.id = newNode.id + index
  1034. // This new node is movable and can be placed anywhere
  1035. let newChildren: Node[] = []
  1036. if (nodeToPaste.data.type === BlockEnum.Iteration) {
  1037. newIterationStartNode!.parentId = newNode.id;
  1038. (newNode.data as IterationNodeType).start_node_id = newIterationStartNode!.id
  1039. newChildren = handleNodeIterationChildrenCopy(nodeToPaste.id, newNode.id)
  1040. newChildren.forEach((child) => {
  1041. newNode.data._children?.push(child.id)
  1042. })
  1043. newChildren.push(newIterationStartNode!)
  1044. }
  1045. nodesToPaste.push(newNode)
  1046. if (newChildren.length)
  1047. nodesToPaste.push(...newChildren)
  1048. })
  1049. setNodes([...nodes, ...nodesToPaste])
  1050. saveStateToHistory(WorkflowHistoryEvent.NodePaste)
  1051. handleSyncWorkflowDraft()
  1052. }
  1053. }, [getNodesReadOnly, workflowStore, store, reactflow, saveStateToHistory, handleSyncWorkflowDraft, handleNodeIterationChildrenCopy])
  1054. const handleNodesDuplicate = useCallback((nodeId?: string) => {
  1055. if (getNodesReadOnly())
  1056. return
  1057. handleNodesCopy(nodeId)
  1058. handleNodesPaste()
  1059. }, [getNodesReadOnly, handleNodesCopy, handleNodesPaste])
  1060. const handleNodesDelete = useCallback(() => {
  1061. if (getNodesReadOnly())
  1062. return
  1063. const {
  1064. getNodes,
  1065. edges,
  1066. } = store.getState()
  1067. const nodes = getNodes()
  1068. const bundledNodes = nodes.filter(node => node.data._isBundled && node.data.type !== BlockEnum.Start)
  1069. if (bundledNodes.length) {
  1070. bundledNodes.forEach(node => handleNodeDelete(node.id))
  1071. return
  1072. }
  1073. const edgeSelected = edges.some(edge => edge.selected)
  1074. if (edgeSelected)
  1075. return
  1076. const selectedNode = nodes.find(node => node.data.selected && node.data.type !== BlockEnum.Start)
  1077. if (selectedNode)
  1078. handleNodeDelete(selectedNode.id)
  1079. }, [store, getNodesReadOnly, handleNodeDelete])
  1080. const handleNodeResize = useCallback((nodeId: string, params: ResizeParamsWithDirection) => {
  1081. if (getNodesReadOnly())
  1082. return
  1083. const {
  1084. getNodes,
  1085. setNodes,
  1086. } = store.getState()
  1087. const { x, y, width, height } = params
  1088. const nodes = getNodes()
  1089. const currentNode = nodes.find(n => n.id === nodeId)!
  1090. const childrenNodes = nodes.filter(n => currentNode.data._children?.includes(n.id))
  1091. let rightNode: Node
  1092. let bottomNode: Node
  1093. childrenNodes.forEach((n) => {
  1094. if (rightNode) {
  1095. if (n.position.x + n.width! > rightNode.position.x + rightNode.width!)
  1096. rightNode = n
  1097. }
  1098. else {
  1099. rightNode = n
  1100. }
  1101. if (bottomNode) {
  1102. if (n.position.y + n.height! > bottomNode.position.y + bottomNode.height!)
  1103. bottomNode = n
  1104. }
  1105. else {
  1106. bottomNode = n
  1107. }
  1108. })
  1109. if (rightNode! && bottomNode!) {
  1110. if (width < rightNode!.position.x + rightNode.width! + ITERATION_PADDING.right)
  1111. return
  1112. if (height < bottomNode.position.y + bottomNode.height! + ITERATION_PADDING.bottom)
  1113. return
  1114. }
  1115. const newNodes = produce(nodes, (draft) => {
  1116. draft.forEach((n) => {
  1117. if (n.id === nodeId) {
  1118. n.data.width = width
  1119. n.data.height = height
  1120. n.width = width
  1121. n.height = height
  1122. n.position.x = x
  1123. n.position.y = y
  1124. }
  1125. })
  1126. })
  1127. setNodes(newNodes)
  1128. handleSyncWorkflowDraft()
  1129. saveStateToHistory(WorkflowHistoryEvent.NodeResize)
  1130. }, [getNodesReadOnly, store, handleSyncWorkflowDraft, saveStateToHistory])
  1131. const handleNodeDisconnect = useCallback((nodeId: string) => {
  1132. if (getNodesReadOnly())
  1133. return
  1134. const {
  1135. getNodes,
  1136. setNodes,
  1137. edges,
  1138. setEdges,
  1139. } = store.getState()
  1140. const nodes = getNodes()
  1141. const currentNode = nodes.find(node => node.id === nodeId)!
  1142. const connectedEdges = getConnectedEdges([currentNode], edges)
  1143. const nodesConnectedSourceOrTargetHandleIdsMap = getNodesConnectedSourceOrTargetHandleIdsMap(
  1144. connectedEdges.map(edge => ({ type: 'remove', edge })),
  1145. nodes,
  1146. )
  1147. const newNodes = produce(nodes, (draft: Node[]) => {
  1148. draft.forEach((node) => {
  1149. if (nodesConnectedSourceOrTargetHandleIdsMap[node.id]) {
  1150. node.data = {
  1151. ...node.data,
  1152. ...nodesConnectedSourceOrTargetHandleIdsMap[node.id],
  1153. }
  1154. }
  1155. })
  1156. })
  1157. setNodes(newNodes)
  1158. const newEdges = produce(edges, (draft) => {
  1159. return draft.filter(edge => !connectedEdges.find(connectedEdge => connectedEdge.id === edge.id))
  1160. })
  1161. setEdges(newEdges)
  1162. handleSyncWorkflowDraft()
  1163. saveStateToHistory(WorkflowHistoryEvent.EdgeDelete)
  1164. }, [store, getNodesReadOnly, handleSyncWorkflowDraft, saveStateToHistory])
  1165. const handleHistoryBack = useCallback(() => {
  1166. if (getNodesReadOnly() || getWorkflowReadOnly())
  1167. return
  1168. const { setEdges, setNodes } = store.getState()
  1169. undo()
  1170. const { edges, nodes } = workflowHistoryStore.getState()
  1171. if (edges.length === 0 && nodes.length === 0)
  1172. return
  1173. setEdges(edges)
  1174. setNodes(nodes)
  1175. }, [store, undo, workflowHistoryStore, getNodesReadOnly, getWorkflowReadOnly])
  1176. const handleHistoryForward = useCallback(() => {
  1177. if (getNodesReadOnly() || getWorkflowReadOnly())
  1178. return
  1179. const { setEdges, setNodes } = store.getState()
  1180. redo()
  1181. const { edges, nodes } = workflowHistoryStore.getState()
  1182. if (edges.length === 0 && nodes.length === 0)
  1183. return
  1184. setEdges(edges)
  1185. setNodes(nodes)
  1186. }, [redo, store, workflowHistoryStore, getNodesReadOnly, getWorkflowReadOnly])
  1187. return {
  1188. handleNodeDragStart,
  1189. handleNodeDrag,
  1190. handleNodeDragStop,
  1191. handleNodeEnter,
  1192. handleNodeLeave,
  1193. handleNodeSelect,
  1194. handleNodeClick,
  1195. handleNodeConnect,
  1196. handleNodeConnectStart,
  1197. handleNodeConnectEnd,
  1198. handleNodeDelete,
  1199. handleNodeChange,
  1200. handleNodeAdd,
  1201. handleNodeCancelRunningStatus,
  1202. handleNodesCancelSelected,
  1203. handleNodeContextMenu,
  1204. handleNodesCopy,
  1205. handleNodesPaste,
  1206. handleNodesDuplicate,
  1207. handleNodesDelete,
  1208. handleNodeResize,
  1209. handleNodeDisconnect,
  1210. handleHistoryBack,
  1211. handleHistoryForward,
  1212. }
  1213. }