hooks.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { useCallback } from 'react'
  2. import {
  3. useNodes,
  4. } from 'reactflow'
  5. import { uniqBy } from 'lodash-es'
  6. import {
  7. useIsChatMode,
  8. useWorkflow,
  9. useWorkflowVariables,
  10. } from '../../hooks'
  11. import type {
  12. Node,
  13. Var,
  14. } from '../../types'
  15. import { AssignerNodeInputType, WriteMode } from './types'
  16. export const useGetAvailableVars = () => {
  17. const nodes: Node[] = useNodes()
  18. const { getBeforeNodesInSameBranchIncludeParent } = useWorkflow()
  19. const { getNodeAvailableVars } = useWorkflowVariables()
  20. const isChatMode = useIsChatMode()
  21. const getAvailableVars = useCallback((nodeId: string, handleId: string, filterVar: (v: Var) => boolean, hideEnv = false) => {
  22. const availableNodes: Node[] = []
  23. const currentNode = nodes.find(node => node.id === nodeId)!
  24. if (!currentNode)
  25. return []
  26. const beforeNodes = getBeforeNodesInSameBranchIncludeParent(nodeId)
  27. availableNodes.push(...beforeNodes)
  28. const parentNode = nodes.find(node => node.id === currentNode.parentId)
  29. if (hideEnv) {
  30. return getNodeAvailableVars({
  31. parentNode,
  32. beforeNodes: uniqBy(availableNodes, 'id').filter(node => node.id !== nodeId),
  33. isChatMode,
  34. hideEnv,
  35. hideChatVar: hideEnv,
  36. filterVar,
  37. })
  38. .map(node => ({
  39. ...node,
  40. vars: node.isStartNode ? node.vars.filter(v => !v.variable.startsWith('sys.')) : node.vars,
  41. }))
  42. .filter(item => item.vars.length > 0)
  43. }
  44. return getNodeAvailableVars({
  45. parentNode,
  46. beforeNodes: uniqBy(availableNodes, 'id').filter(node => node.id !== nodeId),
  47. isChatMode,
  48. filterVar,
  49. })
  50. }, [nodes, getBeforeNodesInSameBranchIncludeParent, getNodeAvailableVars, isChatMode])
  51. return getAvailableVars
  52. }
  53. export const useHandleAddOperationItem = () => {
  54. return useCallback((list: any[]) => {
  55. const newItem = {
  56. variable_selector: [],
  57. write_mode: WriteMode.overwrite,
  58. input_type: AssignerNodeInputType.variable,
  59. value: '',
  60. }
  61. return [...list, newItem]
  62. }, [])
  63. }