use-config.ts 2.1 KB

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