index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. 'use client'
  2. import type { FC } from 'react'
  3. import {
  4. memo,
  5. useCallback,
  6. useEffect,
  7. useMemo,
  8. useRef,
  9. useState,
  10. } from 'react'
  11. import { setAutoFreeze } from 'immer'
  12. import {
  13. useEventListener,
  14. useKeyPress,
  15. } from 'ahooks'
  16. import ReactFlow, {
  17. Background,
  18. ReactFlowProvider,
  19. SelectionMode,
  20. useEdgesState,
  21. useNodesState,
  22. useOnViewportChange,
  23. useReactFlow,
  24. useStoreApi,
  25. } from 'reactflow'
  26. import type {
  27. Viewport,
  28. } from 'reactflow'
  29. import 'reactflow/dist/style.css'
  30. import './style.css'
  31. import type {
  32. Edge,
  33. EnvironmentVariable,
  34. Node,
  35. } from './types'
  36. import { WorkflowContextProvider } from './context'
  37. import {
  38. useDSL,
  39. useEdgesInteractions,
  40. useNodesInteractions,
  41. useNodesReadOnly,
  42. useNodesSyncDraft,
  43. usePanelInteractions,
  44. useSelectionInteractions,
  45. useWorkflow,
  46. useWorkflowInit,
  47. useWorkflowReadOnly,
  48. useWorkflowStartRun,
  49. useWorkflowUpdate,
  50. } from './hooks'
  51. import Header from './header'
  52. import CustomNode from './nodes'
  53. import CustomNoteNode from './note-node'
  54. import { CUSTOM_NOTE_NODE } from './note-node/constants'
  55. import Operator from './operator'
  56. import CustomEdge from './custom-edge'
  57. import CustomConnectionLine from './custom-connection-line'
  58. import Panel from './panel'
  59. import Features from './features'
  60. import HelpLine from './help-line'
  61. import CandidateNode from './candidate-node'
  62. import PanelContextmenu from './panel-contextmenu'
  63. import NodeContextmenu from './node-contextmenu'
  64. import SyncingDataModal from './syncing-data-modal'
  65. import UpdateDSLModal from './update-dsl-modal'
  66. import DSLExportConfirmModal from './dsl-export-confirm-modal'
  67. import {
  68. useStore,
  69. useWorkflowStore,
  70. } from './store'
  71. import {
  72. getKeyboardKeyCodeBySystem,
  73. initialEdges,
  74. initialNodes,
  75. isEventTargetInputArea,
  76. } from './utils'
  77. import {
  78. CUSTOM_NODE,
  79. DSL_EXPORT_CHECK,
  80. ITERATION_CHILDREN_Z_INDEX,
  81. WORKFLOW_DATA_UPDATE,
  82. } from './constants'
  83. import { WorkflowHistoryProvider, useWorkflowHistoryStore } from './workflow-history-store'
  84. import Loading from '@/app/components/base/loading'
  85. import { FeaturesProvider } from '@/app/components/base/features'
  86. import type { Features as FeaturesData } from '@/app/components/base/features/types'
  87. import { useFeaturesStore } from '@/app/components/base/features/hooks'
  88. import { useEventEmitterContextContext } from '@/context/event-emitter'
  89. import Confirm from '@/app/components/base/confirm'
  90. const nodeTypes = {
  91. [CUSTOM_NODE]: CustomNode,
  92. [CUSTOM_NOTE_NODE]: CustomNoteNode,
  93. }
  94. const edgeTypes = {
  95. [CUSTOM_NODE]: CustomEdge,
  96. }
  97. type WorkflowProps = {
  98. nodes: Node[]
  99. edges: Edge[]
  100. viewport?: Viewport
  101. }
  102. const Workflow: FC<WorkflowProps> = memo(({
  103. nodes: originalNodes,
  104. edges: originalEdges,
  105. viewport,
  106. }) => {
  107. const workflowContainerRef = useRef<HTMLDivElement>(null)
  108. const workflowStore = useWorkflowStore()
  109. const reactflow = useReactFlow()
  110. const featuresStore = useFeaturesStore()
  111. const [nodes, setNodes] = useNodesState(originalNodes)
  112. const [edges, setEdges] = useEdgesState(originalEdges)
  113. const showFeaturesPanel = useStore(state => state.showFeaturesPanel)
  114. const controlMode = useStore(s => s.controlMode)
  115. const nodeAnimation = useStore(s => s.nodeAnimation)
  116. const showConfirm = useStore(s => s.showConfirm)
  117. const showImportDSLModal = useStore(s => s.showImportDSLModal)
  118. const {
  119. setShowConfirm,
  120. setControlPromptEditorRerenderKey,
  121. setShowImportDSLModal,
  122. setSyncWorkflowDraftHash,
  123. } = workflowStore.getState()
  124. const {
  125. handleSyncWorkflowDraft,
  126. syncWorkflowDraftWhenPageClose,
  127. } = useNodesSyncDraft()
  128. const { workflowReadOnly } = useWorkflowReadOnly()
  129. const { nodesReadOnly } = useNodesReadOnly()
  130. const [secretEnvList, setSecretEnvList] = useState<EnvironmentVariable[]>([])
  131. const { eventEmitter } = useEventEmitterContextContext()
  132. eventEmitter?.useSubscription((v: any) => {
  133. if (v.type === WORKFLOW_DATA_UPDATE) {
  134. setNodes(v.payload.nodes)
  135. setEdges(v.payload.edges)
  136. if (v.payload.viewport)
  137. reactflow.setViewport(v.payload.viewport)
  138. if (v.payload.features && featuresStore) {
  139. const { setFeatures } = featuresStore.getState()
  140. setFeatures(v.payload.features)
  141. }
  142. if (v.payload.hash)
  143. setSyncWorkflowDraftHash(v.payload.hash)
  144. setTimeout(() => setControlPromptEditorRerenderKey(Date.now()))
  145. }
  146. if (v.type === DSL_EXPORT_CHECK)
  147. setSecretEnvList(v.payload.data as EnvironmentVariable[])
  148. })
  149. useEffect(() => {
  150. setAutoFreeze(false)
  151. return () => {
  152. setAutoFreeze(true)
  153. }
  154. }, [])
  155. useEffect(() => {
  156. return () => {
  157. handleSyncWorkflowDraft(true, true)
  158. }
  159. }, [])
  160. const { handleRefreshWorkflowDraft } = useWorkflowUpdate()
  161. const handleSyncWorkflowDraftWhenPageClose = useCallback(() => {
  162. if (document.visibilityState === 'hidden')
  163. syncWorkflowDraftWhenPageClose()
  164. else if (document.visibilityState === 'visible')
  165. setTimeout(() => handleRefreshWorkflowDraft(), 500)
  166. }, [syncWorkflowDraftWhenPageClose, handleRefreshWorkflowDraft])
  167. useEffect(() => {
  168. document.addEventListener('visibilitychange', handleSyncWorkflowDraftWhenPageClose)
  169. return () => {
  170. document.removeEventListener('visibilitychange', handleSyncWorkflowDraftWhenPageClose)
  171. }
  172. }, [handleSyncWorkflowDraftWhenPageClose])
  173. useEventListener('keydown', (e) => {
  174. if ((e.key === 'd' || e.key === 'D') && (e.ctrlKey || e.metaKey))
  175. e.preventDefault()
  176. if ((e.key === 'z' || e.key === 'Z') && (e.ctrlKey || e.metaKey))
  177. e.preventDefault()
  178. if ((e.key === 'y' || e.key === 'Y') && (e.ctrlKey || e.metaKey))
  179. e.preventDefault()
  180. if ((e.key === 's' || e.key === 'S') && (e.ctrlKey || e.metaKey))
  181. e.preventDefault()
  182. })
  183. useEventListener('mousemove', (e) => {
  184. const containerClientRect = workflowContainerRef.current?.getBoundingClientRect()
  185. if (containerClientRect) {
  186. workflowStore.setState({
  187. mousePosition: {
  188. pageX: e.clientX,
  189. pageY: e.clientY,
  190. elementX: e.clientX - containerClientRect.left,
  191. elementY: e.clientY - containerClientRect.top,
  192. },
  193. })
  194. }
  195. })
  196. const {
  197. handleNodeDragStart,
  198. handleNodeDrag,
  199. handleNodeDragStop,
  200. handleNodeEnter,
  201. handleNodeLeave,
  202. handleNodeClick,
  203. handleNodeConnect,
  204. handleNodeConnectStart,
  205. handleNodeConnectEnd,
  206. handleNodeContextMenu,
  207. handleNodesCopy,
  208. handleNodesPaste,
  209. handleNodesDuplicate,
  210. handleNodesDelete,
  211. handleHistoryBack,
  212. handleHistoryForward,
  213. } = useNodesInteractions()
  214. const {
  215. handleEdgeEnter,
  216. handleEdgeLeave,
  217. handleEdgeDelete,
  218. handleEdgesChange,
  219. } = useEdgesInteractions()
  220. const {
  221. handleSelectionStart,
  222. handleSelectionChange,
  223. handleSelectionDrag,
  224. } = useSelectionInteractions()
  225. const {
  226. handlePaneContextMenu,
  227. handlePaneContextmenuCancel,
  228. } = usePanelInteractions()
  229. const {
  230. isValidConnection,
  231. } = useWorkflow()
  232. const { handleStartWorkflowRun } = useWorkflowStartRun()
  233. const {
  234. exportCheck,
  235. handleExportDSL,
  236. } = useDSL()
  237. useOnViewportChange({
  238. onEnd: () => {
  239. handleSyncWorkflowDraft()
  240. },
  241. })
  242. const { shortcutsEnabled: workflowHistoryShortcutsEnabled } = useWorkflowHistoryStore()
  243. useKeyPress(['delete', 'backspace'], (e) => {
  244. if (isEventTargetInputArea(e.target as HTMLElement))
  245. return
  246. handleNodesDelete()
  247. })
  248. useKeyPress(['delete', 'backspace'], handleEdgeDelete)
  249. useKeyPress(`${getKeyboardKeyCodeBySystem('ctrl')}.c`, (e) => {
  250. if (isEventTargetInputArea(e.target as HTMLElement))
  251. return
  252. handleNodesCopy()
  253. }, { exactMatch: true, useCapture: true })
  254. useKeyPress(`${getKeyboardKeyCodeBySystem('ctrl')}.v`, (e) => {
  255. if (isEventTargetInputArea(e.target as HTMLElement))
  256. return
  257. handleNodesPaste()
  258. }, { exactMatch: true, useCapture: true })
  259. useKeyPress(`${getKeyboardKeyCodeBySystem('ctrl')}.d`, handleNodesDuplicate, { exactMatch: true, useCapture: true })
  260. useKeyPress(`${getKeyboardKeyCodeBySystem('alt')}.r`, handleStartWorkflowRun, { exactMatch: true, useCapture: true })
  261. useKeyPress(`${getKeyboardKeyCodeBySystem('alt')}.r`, handleStartWorkflowRun, { exactMatch: true, useCapture: true })
  262. useKeyPress(
  263. `${getKeyboardKeyCodeBySystem('ctrl')}.z`,
  264. () => workflowHistoryShortcutsEnabled && handleHistoryBack(),
  265. { exactMatch: true, useCapture: true },
  266. )
  267. useKeyPress(
  268. [`${getKeyboardKeyCodeBySystem('ctrl')}.y`, `${getKeyboardKeyCodeBySystem('ctrl')}.shift.z`],
  269. () => workflowHistoryShortcutsEnabled && handleHistoryForward(),
  270. { exactMatch: true, useCapture: true },
  271. )
  272. const store = useStoreApi()
  273. if (process.env.NODE_ENV === 'development') {
  274. store.getState().onError = (code, message) => {
  275. if (code === '002')
  276. return
  277. console.warn(message)
  278. }
  279. }
  280. return (
  281. <div
  282. id='workflow-container'
  283. className={`
  284. relative w-full min-w-[960px] h-full bg-[#F0F2F7]
  285. ${workflowReadOnly && 'workflow-panel-animation'}
  286. ${nodeAnimation && 'workflow-node-animation'}
  287. `}
  288. ref={workflowContainerRef}
  289. >
  290. <SyncingDataModal />
  291. <CandidateNode />
  292. <Header />
  293. <Panel />
  294. <Operator handleRedo={handleHistoryForward} handleUndo={handleHistoryBack} />
  295. {
  296. showFeaturesPanel && <Features />
  297. }
  298. <PanelContextmenu />
  299. <NodeContextmenu />
  300. <HelpLine />
  301. {
  302. !!showConfirm && (
  303. <Confirm
  304. isShow
  305. onCancel={() => setShowConfirm(undefined)}
  306. onConfirm={showConfirm.onConfirm}
  307. title={showConfirm.title}
  308. content={showConfirm.desc}
  309. />
  310. )
  311. }
  312. {
  313. showImportDSLModal && (
  314. <UpdateDSLModal
  315. onCancel={() => setShowImportDSLModal(false)}
  316. onBackup={exportCheck}
  317. onImport={handlePaneContextmenuCancel}
  318. />
  319. )
  320. }
  321. {
  322. secretEnvList.length > 0 && (
  323. <DSLExportConfirmModal
  324. envList={secretEnvList}
  325. onConfirm={handleExportDSL}
  326. onClose={() => setSecretEnvList([])}
  327. />
  328. )
  329. }
  330. <ReactFlow
  331. nodeTypes={nodeTypes}
  332. edgeTypes={edgeTypes}
  333. nodes={nodes}
  334. edges={edges}
  335. onNodeDragStart={handleNodeDragStart}
  336. onNodeDrag={handleNodeDrag}
  337. onNodeDragStop={handleNodeDragStop}
  338. onNodeMouseEnter={handleNodeEnter}
  339. onNodeMouseLeave={handleNodeLeave}
  340. onNodeClick={handleNodeClick}
  341. onNodeContextMenu={handleNodeContextMenu}
  342. onConnect={handleNodeConnect}
  343. onConnectStart={handleNodeConnectStart}
  344. onConnectEnd={handleNodeConnectEnd}
  345. onEdgeMouseEnter={handleEdgeEnter}
  346. onEdgeMouseLeave={handleEdgeLeave}
  347. onEdgesChange={handleEdgesChange}
  348. onSelectionStart={handleSelectionStart}
  349. onSelectionChange={handleSelectionChange}
  350. onSelectionDrag={handleSelectionDrag}
  351. onPaneContextMenu={handlePaneContextMenu}
  352. connectionLineComponent={CustomConnectionLine}
  353. connectionLineContainerStyle={{ zIndex: ITERATION_CHILDREN_Z_INDEX }}
  354. defaultViewport={viewport}
  355. multiSelectionKeyCode={null}
  356. deleteKeyCode={null}
  357. nodesDraggable={!nodesReadOnly}
  358. nodesConnectable={!nodesReadOnly}
  359. nodesFocusable={!nodesReadOnly}
  360. edgesFocusable={!nodesReadOnly}
  361. panOnDrag={controlMode === 'hand' && !workflowReadOnly}
  362. zoomOnPinch={!workflowReadOnly}
  363. zoomOnScroll={!workflowReadOnly}
  364. zoomOnDoubleClick={!workflowReadOnly}
  365. isValidConnection={isValidConnection}
  366. selectionKeyCode={null}
  367. selectionMode={SelectionMode.Partial}
  368. selectionOnDrag={controlMode === 'pointer' && !workflowReadOnly}
  369. minZoom={0.25}
  370. >
  371. <Background
  372. gap={[14, 14]}
  373. size={2}
  374. color='#E4E5E7'
  375. />
  376. </ReactFlow>
  377. </div>
  378. )
  379. })
  380. Workflow.displayName = 'Workflow'
  381. const WorkflowWrap = memo(() => {
  382. const {
  383. data,
  384. isLoading,
  385. } = useWorkflowInit()
  386. const nodesData = useMemo(() => {
  387. if (data)
  388. return initialNodes(data.graph.nodes, data.graph.edges)
  389. return []
  390. }, [data])
  391. const edgesData = useMemo(() => {
  392. if (data)
  393. return initialEdges(data.graph.edges, data.graph.nodes)
  394. return []
  395. }, [data])
  396. if (!data || isLoading) {
  397. return (
  398. <div className='flex justify-center items-center relative w-full h-full bg-[#F0F2F7]'>
  399. <Loading />
  400. </div>
  401. )
  402. }
  403. const features = data.features || {}
  404. const initialFeatures: FeaturesData = {
  405. file: {
  406. image: {
  407. enabled: !!features.file_upload?.image.enabled,
  408. number_limits: features.file_upload?.image.number_limits || 3,
  409. transfer_methods: features.file_upload?.image.transfer_methods || ['local_file', 'remote_url'],
  410. },
  411. },
  412. opening: {
  413. enabled: !!features.opening_statement,
  414. opening_statement: features.opening_statement,
  415. suggested_questions: features.suggested_questions,
  416. },
  417. suggested: features.suggested_questions_after_answer || { enabled: false },
  418. speech2text: features.speech_to_text || { enabled: false },
  419. text2speech: features.text_to_speech || { enabled: false },
  420. citation: features.retriever_resource || { enabled: false },
  421. moderation: features.sensitive_word_avoidance || { enabled: false },
  422. }
  423. return (
  424. <ReactFlowProvider>
  425. <WorkflowHistoryProvider
  426. nodes={nodesData}
  427. edges={edgesData} >
  428. <FeaturesProvider features={initialFeatures}>
  429. <Workflow
  430. nodes={nodesData}
  431. edges={edgesData}
  432. viewport={data?.graph.viewport}
  433. />
  434. </FeaturesProvider>
  435. </WorkflowHistoryProvider>
  436. </ReactFlowProvider>
  437. )
  438. })
  439. WorkflowWrap.displayName = 'WorkflowWrap'
  440. const WorkflowContainer = () => {
  441. return (
  442. <WorkflowContextProvider>
  443. <WorkflowWrap />
  444. </WorkflowContextProvider>
  445. )
  446. }
  447. export default memo(WorkflowContainer)