File size: 1,893 Bytes
64b1da0
 
 
 
 
 
 
 
4a1cf8b
64b1da0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useCallback } from 'react';
import { Operator } from './constant';
import useGraphStore from './store';

const ExcludedNodesMap = {
  // exclude some nodes downstream of the classification node
  [Operator.Categorize]: [Operator.Categorize, Operator.Answer, Operator.Begin],
  [Operator.Relevant]: [Operator.Begin],
  [Operator.Generate]: [Operator.Begin],
};

export const useBuildFormSelectOptions = (
  operatorName: Operator,
  selfId?: string, // exclude the current node
) => {
  const nodes = useGraphStore((state) => state.nodes);

  const buildCategorizeToOptions = useCallback(
    (toList: string[]) => {
      const excludedNodes: Operator[] = ExcludedNodesMap[operatorName] ?? [];
      return nodes
        .filter(
          (x) =>
            excludedNodes.every((y) => y !== x.data.label) &&
            x.id !== selfId &&
            !toList.some((y) => y === x.id), // filter out selected values ​​in other to fields from the current drop-down box options
        )
        .map((x) => ({ label: x.data.name, value: x.id }));
    },
    [nodes, operatorName, selfId],
  );

  return buildCategorizeToOptions;
};

export const useHandleFormSelectChange = (nodeId?: string) => {
  const { addEdge, deleteEdgeBySourceAndSourceHandle } = useGraphStore(
    (state) => state,
  );
  const handleSelectChange = useCallback(
    (name?: string) => (value?: string) => {
      if (nodeId && name) {
        if (value) {
          addEdge({
            source: nodeId,
            target: value,
            sourceHandle: name,
            targetHandle: null,
          });
        } else {
          // clear selected value
          deleteEdgeBySourceAndSourceHandle({
            source: nodeId,
            sourceHandle: name,
          });
        }
      }
    },
    [addEdge, nodeId, deleteEdgeBySourceAndSourceHandle],
  );

  return { handleSelectChange };
};