File size: 14,913 Bytes
b1ea792 be99f83 b1ea792 be99f83 3d90fa3 4f06073 a83cbb2 bdb8bf3 2bdad3e a83cbb2 be99f83 b1ea792 be99f83 2653e84 b1ea792 be99f83 b1ea792 be99f83 970e973 4f06073 b1ea792 be99f83 b1ea792 36669dc db19895 f8510ae 4f06073 06a1fe2 a83cbb2 2bdad3e be99f83 ddd1aa2 2bdad3e 916a392 b1ea792 db19895 c298fc4 2bdad3e 2653e84 a83cbb2 2653e84 be99f83 8207a08 ddd1aa2 3d90fa3 b1ea792 ddd1aa2 2653e84 b1ea792 ddd1aa2 f8510ae ddd1aa2 f8510ae ddd1aa2 b1ea792 ddd1aa2 970e973 b1ea792 ddd1aa2 c298fc4 4a674c0 c298fc4 2bdad3e 36669dc db19895 3d90fa3 db19895 36669dc f8510ae 4f06073 f8510ae 3d90fa3 8828184 4f06073 8828184 3d90fa3 f8510ae 06a1fe2 64b1da0 f8510ae 64b1da0 8828184 64b1da0 06a1fe2 f8510ae 06a1fe2 a83cbb2 2bdad3e 4a674c0 2bdad3e 4a674c0 bdb8bf3 2bdad3e 4a674c0 2bdad3e b1ea792 2bdad3e ddd1aa2 4f06073 f8510ae 3d90fa3 f8510ae 3d90fa3 f8510ae 3d90fa3 8828184 4f06073 8828184 3d90fa3 f8510ae ddd1aa2 916a392 36669dc 916a392 36669dc 916a392 36669dc ddd1aa2 2bdad3e ddd1aa2 4f06073 f859b0d ddd1aa2 f859b0d be99f83 f859b0d ddd1aa2 f859b0d ddd1aa2 4f06073 db19895 2653e84 a83cbb2 3d90fa3 ddd1aa2 be99f83 8207a08 |
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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 |
import { RAGFlowNodeType } from '@/interfaces/database/flow';
import type {} from '@redux-devtools/extension';
import {
Connection,
Edge,
EdgeChange,
OnConnect,
OnEdgesChange,
OnNodesChange,
OnSelectionChangeFunc,
OnSelectionChangeParams,
addEdge,
applyEdgeChanges,
applyNodeChanges,
} from '@xyflow/react';
import { omit } from 'lodash';
import differenceWith from 'lodash/differenceWith';
import intersectionWith from 'lodash/intersectionWith';
import lodashSet from 'lodash/set';
import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import { Operator, SwitchElseTo } from './constant';
import {
duplicateNodeForm,
generateDuplicateNode,
generateNodeNamesWithIncreasingIndex,
getOperatorIndex,
isEdgeEqual,
} from './utils';
export type RFState = {
nodes: RAGFlowNodeType[];
edges: Edge[];
selectedNodeIds: string[];
selectedEdgeIds: string[];
clickedNodeId: string; // currently selected node
onNodesChange: OnNodesChange<RAGFlowNodeType>;
onEdgesChange: OnEdgesChange;
onConnect: OnConnect;
setNodes: (nodes: RAGFlowNodeType[]) => void;
setEdges: (edges: Edge[]) => void;
setEdgesByNodeId: (nodeId: string, edges: Edge[]) => void;
updateNodeForm: (
nodeId: string,
values: any,
path?: (string | number)[],
) => RAGFlowNodeType[];
onSelectionChange: OnSelectionChangeFunc;
addNode: (nodes: RAGFlowNodeType) => void;
getNode: (id?: string | null) => RAGFlowNodeType | undefined;
addEdge: (connection: Connection) => void;
getEdge: (id: string) => Edge | undefined;
updateFormDataOnConnect: (connection: Connection) => void;
updateSwitchFormData: (
source: string,
sourceHandle?: string | null,
target?: string | null,
) => void;
deletePreviousEdgeOfClassificationNode: (connection: Connection) => void;
duplicateNode: (id: string, name: string) => void;
duplicateIterationNode: (id: string, name: string) => void;
deleteEdge: () => void;
deleteEdgeById: (id: string) => void;
deleteNodeById: (id: string) => void;
deleteIterationNodeById: (id: string) => void;
deleteEdgeBySourceAndSourceHandle: (connection: Partial<Connection>) => void;
findNodeByName: (operatorName: Operator) => RAGFlowNodeType | undefined;
updateMutableNodeFormItem: (id: string, field: string, value: any) => void;
getOperatorTypeFromId: (id?: string | null) => string | undefined;
getParentIdById: (id?: string | null) => string | undefined;
updateNodeName: (id: string, name: string) => void;
generateNodeName: (name: string) => string;
setClickedNodeId: (id?: string) => void;
};
// this is our useStore hook that we can use in our components to get parts of the store and call actions
const useGraphStore = create<RFState>()(
devtools(
immer((set, get) => ({
nodes: [] as RAGFlowNodeType[],
edges: [] as Edge[],
selectedNodeIds: [] as string[],
selectedEdgeIds: [] as string[],
clickedNodeId: '',
onNodesChange: (changes) => {
set({
nodes: applyNodeChanges(changes, get().nodes),
});
},
onEdgesChange: (changes: EdgeChange[]) => {
set({
edges: applyEdgeChanges(changes, get().edges),
});
},
onConnect: (connection: Connection) => {
const {
deletePreviousEdgeOfClassificationNode,
updateFormDataOnConnect,
} = get();
set({
edges: addEdge(connection, get().edges),
});
deletePreviousEdgeOfClassificationNode(connection);
updateFormDataOnConnect(connection);
},
onSelectionChange: ({ nodes, edges }: OnSelectionChangeParams) => {
set({
selectedEdgeIds: edges.map((x) => x.id),
selectedNodeIds: nodes.map((x) => x.id),
});
},
setNodes: (nodes: RAGFlowNodeType[]) => {
set({ nodes });
},
setEdges: (edges: Edge[]) => {
set({ edges });
},
setEdgesByNodeId: (nodeId: string, currentDownstreamEdges: Edge[]) => {
const { edges, setEdges } = get();
// the previous downstream edge of this node
const previousDownstreamEdges = edges.filter(
(x) => x.source === nodeId,
);
const isDifferent =
previousDownstreamEdges.length !== currentDownstreamEdges.length ||
!previousDownstreamEdges.every((x) =>
currentDownstreamEdges.some(
(y) =>
y.source === x.source &&
y.target === x.target &&
y.sourceHandle === x.sourceHandle,
),
) ||
!currentDownstreamEdges.every((x) =>
previousDownstreamEdges.some(
(y) =>
y.source === x.source &&
y.target === x.target &&
y.sourceHandle === x.sourceHandle,
),
);
const intersectionDownstreamEdges = intersectionWith(
previousDownstreamEdges,
currentDownstreamEdges,
isEdgeEqual,
);
if (isDifferent) {
// other operator's edges
const irrelevantEdges = edges.filter((x) => x.source !== nodeId);
// the added downstream edges
const selfAddedDownstreamEdges = differenceWith(
currentDownstreamEdges,
intersectionDownstreamEdges,
isEdgeEqual,
);
setEdges([
...irrelevantEdges,
...intersectionDownstreamEdges,
...selfAddedDownstreamEdges,
]);
}
},
addNode: (node: RAGFlowNodeType) => {
set({ nodes: get().nodes.concat(node) });
},
getNode: (id?: string | null) => {
return get().nodes.find((x) => x.id === id);
},
getOperatorTypeFromId: (id?: string | null) => {
return get().getNode(id)?.data?.label;
},
getParentIdById: (id?: string | null) => {
return get().getNode(id)?.parentId;
},
addEdge: (connection: Connection) => {
set({
edges: addEdge(connection, get().edges),
});
get().deletePreviousEdgeOfClassificationNode(connection);
// TODO: This may not be reasonable. You need to choose between listening to changes in the form.
get().updateFormDataOnConnect(connection);
},
getEdge: (id: string) => {
return get().edges.find((x) => x.id === id);
},
updateFormDataOnConnect: (connection: Connection) => {
const { getOperatorTypeFromId, updateNodeForm, updateSwitchFormData } =
get();
const { source, target, sourceHandle } = connection;
const operatorType = getOperatorTypeFromId(source);
if (source) {
switch (operatorType) {
case Operator.Relevant:
updateNodeForm(source, { [sourceHandle as string]: target });
break;
case Operator.Categorize:
if (sourceHandle)
updateNodeForm(source, target, [
'category_description',
sourceHandle,
'to',
]);
break;
case Operator.Switch: {
updateSwitchFormData(source, sourceHandle, target);
break;
}
default:
break;
}
}
},
deletePreviousEdgeOfClassificationNode: (connection: Connection) => {
// Delete the edge on the classification node or relevant node anchor when the anchor is connected to other nodes
const { edges, getOperatorTypeFromId, deleteEdgeById } = get();
// the node containing the anchor
const anchoredNodes = [
Operator.Categorize,
Operator.Relevant,
Operator.Switch,
];
if (
anchoredNodes.some(
(x) => x === getOperatorTypeFromId(connection.source),
)
) {
const previousEdge = edges.find(
(x) =>
x.source === connection.source &&
x.sourceHandle === connection.sourceHandle &&
x.target !== connection.target,
);
if (previousEdge) {
deleteEdgeById(previousEdge.id);
}
}
},
duplicateNode: (id: string, name: string) => {
const { getNode, addNode, generateNodeName, duplicateIterationNode } =
get();
const node = getNode(id);
if (node?.data.label === Operator.Iteration) {
duplicateIterationNode(id, name);
return;
}
addNode({
...(node || {}),
data: {
...duplicateNodeForm(node?.data),
name: generateNodeName(name),
},
...generateDuplicateNode(node?.position, node?.data?.label),
});
},
duplicateIterationNode: (id: string, name: string) => {
const { getNode, generateNodeName, nodes } = get();
const node = getNode(id);
const iterationNode: RAGFlowNodeType = {
...(node || {}),
data: {
...(node?.data || { label: Operator.Iteration, form: {} }),
name: generateNodeName(name),
},
...generateDuplicateNode(node?.position, node?.data?.label),
};
const children = nodes
.filter((x) => x.parentId === node?.id)
.map((x) => ({
...(x || {}),
data: {
...duplicateNodeForm(x?.data),
name: generateNodeName(x.data.name),
},
...omit(generateDuplicateNode(x?.position, x?.data?.label), [
'position',
]),
parentId: iterationNode.id,
}));
set({ nodes: nodes.concat(iterationNode, ...children) });
},
deleteEdge: () => {
const { edges, selectedEdgeIds } = get();
set({
edges: edges.filter((edge) =>
selectedEdgeIds.every((x) => x !== edge.id),
),
});
},
deleteEdgeById: (id: string) => {
const {
edges,
updateNodeForm,
getOperatorTypeFromId,
updateSwitchFormData,
} = get();
const currentEdge = edges.find((x) => x.id === id);
if (currentEdge) {
const { source, sourceHandle } = currentEdge;
const operatorType = getOperatorTypeFromId(source);
// After deleting the edge, set the corresponding field in the node's form field to undefined
switch (operatorType) {
case Operator.Relevant:
updateNodeForm(source, {
[sourceHandle as string]: undefined,
});
break;
case Operator.Categorize:
if (sourceHandle)
updateNodeForm(source, undefined, [
'category_description',
sourceHandle,
'to',
]);
break;
case Operator.Switch: {
updateSwitchFormData(source, sourceHandle, undefined);
break;
}
default:
break;
}
}
set({
edges: edges.filter((edge) => edge.id !== id),
});
},
deleteEdgeBySourceAndSourceHandle: ({
source,
sourceHandle,
}: Partial<Connection>) => {
const { edges } = get();
const nextEdges = edges.filter(
(edge) =>
edge.source !== source || edge.sourceHandle !== sourceHandle,
);
set({
edges: nextEdges,
});
},
deleteNodeById: (id: string) => {
const { nodes, edges } = get();
set({
nodes: nodes.filter((node) => node.id !== id),
edges: edges
.filter((edge) => edge.source !== id)
.filter((edge) => edge.target !== id),
});
},
deleteIterationNodeById: (id: string) => {
const { nodes, edges } = get();
const children = nodes.filter((node) => node.parentId === id);
set({
nodes: nodes.filter((node) => node.id !== id && node.parentId !== id),
edges: edges.filter(
(edge) =>
edge.source !== id &&
edge.target !== id &&
!children.some(
(child) => edge.source === child.id && edge.target === child.id,
),
),
});
},
findNodeByName: (name: Operator) => {
return get().nodes.find((x) => x.data.label === name);
},
updateNodeForm: (
nodeId: string,
values: any,
path: (string | number)[] = [],
) => {
const nextNodes = get().nodes.map((node) => {
if (node.id === nodeId) {
let nextForm: Record<string, unknown> = { ...node.data.form };
if (path.length === 0) {
nextForm = Object.assign(nextForm, values);
} else {
lodashSet(nextForm, path, values);
}
return {
...node,
data: {
...node.data,
form: nextForm,
},
} as any;
}
return node;
});
set({
nodes: nextNodes,
});
return nextNodes;
},
updateSwitchFormData: (source, sourceHandle, target) => {
const { updateNodeForm } = get();
if (sourceHandle) {
if (sourceHandle === SwitchElseTo) {
updateNodeForm(source, target, [SwitchElseTo]);
} else {
const operatorIndex = getOperatorIndex(sourceHandle);
if (operatorIndex) {
updateNodeForm(source, target, [
'conditions',
Number(operatorIndex) - 1, // The index is the conditions form index
'to',
]);
}
}
}
},
updateMutableNodeFormItem: (id: string, field: string, value: any) => {
const { nodes } = get();
const idx = nodes.findIndex((x) => x.id === id);
if (idx) {
lodashSet(nodes, [idx, 'data', 'form', field], value);
}
},
updateNodeName: (id, name) => {
if (id) {
set({
nodes: get().nodes.map((node) => {
if (node.id === id) {
node.data.name = name;
}
return node;
}),
});
}
},
setClickedNodeId: (id?: string) => {
set({ clickedNodeId: id });
},
generateNodeName: (name: string) => {
const { nodes } = get();
return generateNodeNamesWithIncreasingIndex(name, nodes);
},
})),
{ name: 'graph' },
),
);
export default useGraphStore;
|