-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.js
68 lines (66 loc) · 1.48 KB
/
store.js
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
// store.js
import { create } from "zustand"
import { addEdge, applyNodeChanges, applyEdgeChanges } from "reactflow"
export const useStore = create((set, get) => ({
nodes: [],
edges: [],
getNodeID: (type) => {
const newIDs = { ...get().nodeIDs }
if (newIDs[type] === undefined) {
newIDs[type] = 0
}
newIDs[type] += 1
set({ nodeIDs: newIDs })
return `${type}-${newIDs[type]}`
},
addNode: (node) => {
set({
nodes: [...get().nodes, node],
})
},
removeNode: (nodeId) => {
set({
nodes: get().nodes.filter((node) => node.id !== nodeId),
edges: get().edges.filter(
(edge) => edge.source !== nodeId && edge.target !== nodeId
),
})
},
removeEdge: (edgeId) => {
set({
edges: get().edges.filter((edge) => edge.id !== edgeId),
})
},
onNodesChange: (changes) => {
set({
nodes: applyNodeChanges(changes, get().nodes),
})
},
onEdgesChange: (changes) => {
set({
edges: applyEdgeChanges(changes, get().edges),
})
},
onConnect: (connection) => {
set({
edges: addEdge(
{
...connection,
type: "custom",
animated: true,
},
get().edges
),
})
},
updateNodeField: (nodeId, fieldName, fieldValue) => {
set({
nodes: get().nodes.map((node) => {
if (node.id === nodeId) {
node.data = { ...node.data, [fieldName]: fieldValue }
}
return node
}),
})
},
}))