use-workflow-interactions.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. import {
  2. useCallback,
  3. useState,
  4. } from 'react'
  5. import { useTranslation } from 'react-i18next'
  6. import { useReactFlow, useStoreApi } from 'reactflow'
  7. import produce from 'immer'
  8. import { useStore, useWorkflowStore } from '../store'
  9. import {
  10. CUSTOM_NODE, DSL_EXPORT_CHECK,
  11. WORKFLOW_DATA_UPDATE,
  12. } from '../constants'
  13. import type { Node, WorkflowDataUpdater } from '../types'
  14. import { ControlMode } from '../types'
  15. import {
  16. getLayoutByDagre,
  17. initialEdges,
  18. initialNodes,
  19. } from '../utils'
  20. import {
  21. useNodesReadOnly,
  22. useSelectionInteractions,
  23. useWorkflowReadOnly,
  24. } from '../hooks'
  25. import { useEdgesInteractions } from './use-edges-interactions'
  26. import { useNodesInteractions } from './use-nodes-interactions'
  27. import { useNodesSyncDraft } from './use-nodes-sync-draft'
  28. import { WorkflowHistoryEvent, useWorkflowHistory } from './use-workflow-history'
  29. import { useEventEmitterContextContext } from '@/context/event-emitter'
  30. import { fetchWorkflowDraft } from '@/service/workflow'
  31. import { exportAppConfig } from '@/service/apps'
  32. import { useToastContext } from '@/app/components/base/toast'
  33. import { useStore as useAppStore } from '@/app/components/app/store'
  34. export const useWorkflowInteractions = () => {
  35. const workflowStore = useWorkflowStore()
  36. const { handleNodeCancelRunningStatus } = useNodesInteractions()
  37. const { handleEdgeCancelRunningStatus } = useEdgesInteractions()
  38. const handleCancelDebugAndPreviewPanel = useCallback(() => {
  39. workflowStore.setState({
  40. showDebugAndPreviewPanel: false,
  41. workflowRunningData: undefined,
  42. })
  43. handleNodeCancelRunningStatus()
  44. handleEdgeCancelRunningStatus()
  45. }, [workflowStore, handleNodeCancelRunningStatus, handleEdgeCancelRunningStatus])
  46. return {
  47. handleCancelDebugAndPreviewPanel,
  48. }
  49. }
  50. export const useWorkflowMoveMode = () => {
  51. const setControlMode = useStore(s => s.setControlMode)
  52. const {
  53. getNodesReadOnly,
  54. } = useNodesReadOnly()
  55. const { handleSelectionCancel } = useSelectionInteractions()
  56. const handleModePointer = useCallback(() => {
  57. if (getNodesReadOnly())
  58. return
  59. setControlMode(ControlMode.Pointer)
  60. }, [getNodesReadOnly, setControlMode])
  61. const handleModeHand = useCallback(() => {
  62. if (getNodesReadOnly())
  63. return
  64. setControlMode(ControlMode.Hand)
  65. handleSelectionCancel()
  66. }, [getNodesReadOnly, setControlMode, handleSelectionCancel])
  67. return {
  68. handleModePointer,
  69. handleModeHand,
  70. }
  71. }
  72. export const useWorkflowOrganize = () => {
  73. const workflowStore = useWorkflowStore()
  74. const store = useStoreApi()
  75. const reactflow = useReactFlow()
  76. const { getNodesReadOnly } = useNodesReadOnly()
  77. const { saveStateToHistory } = useWorkflowHistory()
  78. const { handleSyncWorkflowDraft } = useNodesSyncDraft()
  79. const handleLayout = useCallback(async () => {
  80. if (getNodesReadOnly())
  81. return
  82. workflowStore.setState({ nodeAnimation: true })
  83. const {
  84. getNodes,
  85. edges,
  86. setNodes,
  87. } = store.getState()
  88. const { setViewport } = reactflow
  89. const nodes = getNodes()
  90. const layout = getLayoutByDagre(nodes, edges)
  91. const rankMap = {} as Record<string, Node>
  92. nodes.forEach((node) => {
  93. if (!node.parentId && node.type === CUSTOM_NODE) {
  94. const rank = layout.node(node.id).rank!
  95. if (!rankMap[rank]) {
  96. rankMap[rank] = node
  97. }
  98. else {
  99. if (rankMap[rank].position.y > node.position.y)
  100. rankMap[rank] = node
  101. }
  102. }
  103. })
  104. const newNodes = produce(nodes, (draft) => {
  105. draft.forEach((node) => {
  106. if (!node.parentId && node.type === CUSTOM_NODE) {
  107. const nodeWithPosition = layout.node(node.id)
  108. node.position = {
  109. x: nodeWithPosition.x - node.width! / 2,
  110. y: nodeWithPosition.y - node.height! / 2 + rankMap[nodeWithPosition.rank!].height! / 2,
  111. }
  112. }
  113. })
  114. })
  115. setNodes(newNodes)
  116. const zoom = 0.7
  117. setViewport({
  118. x: 0,
  119. y: 0,
  120. zoom,
  121. })
  122. saveStateToHistory(WorkflowHistoryEvent.LayoutOrganize)
  123. setTimeout(() => {
  124. handleSyncWorkflowDraft()
  125. })
  126. }, [getNodesReadOnly, store, reactflow, workflowStore, handleSyncWorkflowDraft, saveStateToHistory])
  127. return {
  128. handleLayout,
  129. }
  130. }
  131. export const useWorkflowZoom = () => {
  132. const { handleSyncWorkflowDraft } = useNodesSyncDraft()
  133. const { getWorkflowReadOnly } = useWorkflowReadOnly()
  134. const {
  135. zoomIn,
  136. zoomOut,
  137. zoomTo,
  138. fitView,
  139. } = useReactFlow()
  140. const handleFitView = useCallback(() => {
  141. if (getWorkflowReadOnly())
  142. return
  143. fitView()
  144. handleSyncWorkflowDraft()
  145. }, [getWorkflowReadOnly, fitView, handleSyncWorkflowDraft])
  146. const handleBackToOriginalSize = useCallback(() => {
  147. if (getWorkflowReadOnly())
  148. return
  149. zoomTo(1)
  150. handleSyncWorkflowDraft()
  151. }, [getWorkflowReadOnly, zoomTo, handleSyncWorkflowDraft])
  152. const handleSizeToHalf = useCallback(() => {
  153. if (getWorkflowReadOnly())
  154. return
  155. zoomTo(0.5)
  156. handleSyncWorkflowDraft()
  157. }, [getWorkflowReadOnly, zoomTo, handleSyncWorkflowDraft])
  158. const handleZoomOut = useCallback(() => {
  159. if (getWorkflowReadOnly())
  160. return
  161. zoomOut()
  162. handleSyncWorkflowDraft()
  163. }, [getWorkflowReadOnly, zoomOut, handleSyncWorkflowDraft])
  164. const handleZoomIn = useCallback(() => {
  165. if (getWorkflowReadOnly())
  166. return
  167. zoomIn()
  168. handleSyncWorkflowDraft()
  169. }, [getWorkflowReadOnly, zoomIn, handleSyncWorkflowDraft])
  170. return {
  171. handleFitView,
  172. handleBackToOriginalSize,
  173. handleSizeToHalf,
  174. handleZoomOut,
  175. handleZoomIn,
  176. }
  177. }
  178. export const useWorkflowUpdate = () => {
  179. const reactflow = useReactFlow()
  180. const workflowStore = useWorkflowStore()
  181. const { eventEmitter } = useEventEmitterContextContext()
  182. const handleUpdateWorkflowCanvas = useCallback((payload: WorkflowDataUpdater) => {
  183. const {
  184. nodes,
  185. edges,
  186. viewport,
  187. } = payload
  188. const { setViewport } = reactflow
  189. eventEmitter?.emit({
  190. type: WORKFLOW_DATA_UPDATE,
  191. payload: {
  192. nodes: initialNodes(nodes, edges),
  193. edges: initialEdges(edges, nodes),
  194. },
  195. } as any)
  196. setViewport(viewport)
  197. }, [eventEmitter, reactflow])
  198. const handleRefreshWorkflowDraft = useCallback(() => {
  199. const {
  200. appId,
  201. setSyncWorkflowDraftHash,
  202. setIsSyncingWorkflowDraft,
  203. setEnvironmentVariables,
  204. setEnvSecrets,
  205. setConversationVariables,
  206. } = workflowStore.getState()
  207. setIsSyncingWorkflowDraft(true)
  208. fetchWorkflowDraft(`/apps/${appId}/workflows/draft`).then((response) => {
  209. handleUpdateWorkflowCanvas(response.graph as WorkflowDataUpdater)
  210. setSyncWorkflowDraftHash(response.hash)
  211. setEnvSecrets((response.environment_variables || []).filter(env => env.value_type === 'secret').reduce((acc, env) => {
  212. acc[env.id] = env.value
  213. return acc
  214. }, {} as Record<string, string>))
  215. setEnvironmentVariables(response.environment_variables?.map(env => env.value_type === 'secret' ? { ...env, value: '[__HIDDEN__]' } : env) || [])
  216. // #TODO chatVar sync#
  217. setConversationVariables(response.conversation_variables || [])
  218. }).finally(() => setIsSyncingWorkflowDraft(false))
  219. }, [handleUpdateWorkflowCanvas, workflowStore])
  220. return {
  221. handleUpdateWorkflowCanvas,
  222. handleRefreshWorkflowDraft,
  223. }
  224. }
  225. export const useDSL = () => {
  226. const { t } = useTranslation()
  227. const { notify } = useToastContext()
  228. const { eventEmitter } = useEventEmitterContextContext()
  229. const [exporting, setExporting] = useState(false)
  230. const { doSyncWorkflowDraft } = useNodesSyncDraft()
  231. const appDetail = useAppStore(s => s.appDetail)
  232. const handleExportDSL = useCallback(async (include = false) => {
  233. if (!appDetail)
  234. return
  235. if (exporting)
  236. return
  237. try {
  238. setExporting(true)
  239. await doSyncWorkflowDraft()
  240. const { data } = await exportAppConfig({
  241. appID: appDetail.id,
  242. include,
  243. })
  244. const a = document.createElement('a')
  245. const file = new Blob([data], { type: 'application/yaml' })
  246. a.href = URL.createObjectURL(file)
  247. a.download = `${appDetail.name}.yml`
  248. a.click()
  249. }
  250. catch (e) {
  251. notify({ type: 'error', message: t('app.exportFailed') })
  252. }
  253. finally {
  254. setExporting(false)
  255. }
  256. }, [appDetail, notify, t, doSyncWorkflowDraft, exporting])
  257. const exportCheck = useCallback(async () => {
  258. if (!appDetail)
  259. return
  260. try {
  261. const workflowDraft = await fetchWorkflowDraft(`/apps/${appDetail?.id}/workflows/draft`)
  262. const list = (workflowDraft.environment_variables || []).filter(env => env.value_type === 'secret')
  263. if (list.length === 0) {
  264. handleExportDSL()
  265. return
  266. }
  267. eventEmitter?.emit({
  268. type: DSL_EXPORT_CHECK,
  269. payload: {
  270. data: list,
  271. },
  272. } as any)
  273. }
  274. catch (e) {
  275. notify({ type: 'error', message: t('app.exportFailed') })
  276. }
  277. }, [appDetail, eventEmitter, handleExportDSL, notify, t])
  278. return {
  279. exportCheck,
  280. handleExportDSL,
  281. }
  282. }