File size: 2,190 Bytes
4304c6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { useCallback } from 'react'
import produce from 'immer'
import type { Var } from '../../types'
import { VarType } from '../../types'
import { getVarType } from '../_base/components/variable/utils'
import { LogicalOperator } from './types'
import type { Condition, IfElseNodeType } from './types'
import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'
import {
  useIsChatMode,
  useNodesReadOnly,
  useWorkflow,
} from '@/app/components/workflow/hooks'

const useConfig = (id: string, payload: IfElseNodeType) => {
  const { nodesReadOnly: readOnly } = useNodesReadOnly()
  const { getBeforeNodesInSameBranch } = useWorkflow()
  const isChatMode = useIsChatMode()
  const availableNodes = getBeforeNodesInSameBranch(id)

  const { inputs, setInputs } = useNodeCrud<IfElseNodeType>(id, payload)

  const handleConditionsChange = useCallback((newConditions: Condition[]) => {
    const newInputs = produce(inputs, (draft) => {
      draft.conditions = newConditions
    })
    setInputs(newInputs)
  }, [inputs, setInputs])

  const handleAddCondition = useCallback(() => {
    const newInputs = produce(inputs, (draft) => {
      draft.conditions.push({
        id: `${Date.now()}`,
        variable_selector: [],
        comparison_operator: undefined,
        value: '',
      })
    })
    setInputs(newInputs)
  }, [inputs, setInputs])

  const handleLogicalOperatorToggle = useCallback(() => {
    const newInputs = produce(inputs, (draft) => {
      draft.logical_operator = draft.logical_operator === LogicalOperator.and ? LogicalOperator.or : LogicalOperator.and
    })
    setInputs(newInputs)
  }, [inputs, setInputs])

  const filterVar = useCallback((varPayload: Var) => {
    return varPayload.type !== VarType.arrayFile
  }, [])

  const varTypesList = (inputs.conditions || []).map((condition) => {
    return getVarType(condition.variable_selector, availableNodes, isChatMode)
  })

  return {
    readOnly,
    inputs,
    handleConditionsChange,
    handleAddCondition,
    handleLogicalOperatorToggle,
    varTypesList,
    filterVar,
  }
}

export default useConfig