use-config.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { useCallback } from 'react'
  2. import produce from 'immer'
  3. import type { Var } from '../../types'
  4. import { VarType } from '../../types'
  5. import { getVarType } from '../_base/components/variable/utils'
  6. import useNodeInfo from '../_base/hooks/use-node-info'
  7. import { LogicalOperator } from './types'
  8. import type { Condition, IfElseNodeType } from './types'
  9. import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'
  10. import {
  11. useIsChatMode,
  12. useNodesReadOnly,
  13. useWorkflow,
  14. } from '@/app/components/workflow/hooks'
  15. const useConfig = (id: string, payload: IfElseNodeType) => {
  16. const { nodesReadOnly: readOnly } = useNodesReadOnly()
  17. const { getBeforeNodesInSameBranch } = useWorkflow()
  18. const {
  19. parentNode,
  20. } = useNodeInfo(id)
  21. const isChatMode = useIsChatMode()
  22. const beforeNodes = getBeforeNodesInSameBranch(id)
  23. const { inputs, setInputs } = useNodeCrud<IfElseNodeType>(id, payload)
  24. const handleConditionsChange = useCallback((newConditions: Condition[]) => {
  25. const newInputs = produce(inputs, (draft) => {
  26. draft.conditions = newConditions
  27. })
  28. setInputs(newInputs)
  29. }, [inputs, setInputs])
  30. const handleAddCondition = useCallback(() => {
  31. const newInputs = produce(inputs, (draft) => {
  32. draft.conditions.push({
  33. id: `${Date.now()}`,
  34. variable_selector: [],
  35. comparison_operator: undefined,
  36. value: '',
  37. })
  38. })
  39. setInputs(newInputs)
  40. }, [inputs, setInputs])
  41. const handleLogicalOperatorToggle = useCallback(() => {
  42. const newInputs = produce(inputs, (draft) => {
  43. draft.logical_operator = draft.logical_operator === LogicalOperator.and ? LogicalOperator.or : LogicalOperator.and
  44. })
  45. setInputs(newInputs)
  46. }, [inputs, setInputs])
  47. const filterVar = useCallback((varPayload: Var) => {
  48. return varPayload.type !== VarType.arrayFile
  49. }, [])
  50. const varTypesList = (inputs.conditions || []).map((condition) => {
  51. return getVarType({
  52. parentNode,
  53. valueSelector: condition.variable_selector,
  54. availableNodes: beforeNodes,
  55. isChatMode,
  56. })
  57. })
  58. return {
  59. readOnly,
  60. inputs,
  61. handleConditionsChange,
  62. handleAddCondition,
  63. handleLogicalOperatorToggle,
  64. varTypesList,
  65. filterVar,
  66. }
  67. }
  68. export default useConfig