-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtrackGraphState.ts
More file actions
104 lines (78 loc) · 2.35 KB
/
trackGraphState.ts
File metadata and controls
104 lines (78 loc) · 2.35 KB
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
import type { GraphState } from "@magic/graph/collab/types"
import type { GEdge, GNode } from "@magic/graph/types"
/**
* maps the room id to the live version of the graph for that room
*/
const roomIdToGraphState: Record<string, GraphState> = {}
export const trackGraphState = () => {
let roomId: string
const setRoomId = (newRoomId: string) => {
roomId = newRoomId
}
const getRoomId = () => {
if (!roomId) console.warn('room id not set')
return roomId
}
const getGraphState = () => {
return roomIdToGraphState[getRoomId()]
}
const setGraphState = (graphState: GraphState) => {
roomIdToGraphState[getRoomId()] = graphState
}
const deleteGraphState = () => {
delete roomIdToGraphState[getRoomId()]
}
const updateEdge = (edgeId: GEdge['id'], edge: Partial<GEdge>) => {
const graphState = roomIdToGraphState[getRoomId()]
if (!graphState) return
const edgeIndex = graphState.edges.findIndex((e) => e.id === edgeId)
if (edgeIndex === -1) return
graphState.edges[edgeIndex] = {
...graphState.edges[edgeIndex],
...edge
}
}
const updateNode = (nodeId: GEdge['id'], node: Partial<GNode>) => {
const graphState = roomIdToGraphState[getRoomId()]
if (!graphState) return
const nodeIndex = graphState.nodes.findIndex((n) => n.id === nodeId)
if (nodeIndex === -1) return
graphState.nodes[nodeIndex] = {
...graphState.nodes[nodeIndex],
...node
}
}
const removeEdge = (edgeId: GEdge['id']) => {
const graphState = roomIdToGraphState[getRoomId()]
if (!graphState) return
graphState.edges = graphState.edges.filter((e) => e.id !== edgeId)
}
const removeNode = (nodeId: GEdge['id']) => {
const graphState = roomIdToGraphState[getRoomId()]
if (!graphState) return
graphState.nodes = graphState.nodes.filter((n) => n.id !== nodeId)
}
const addEdge = (edge: GEdge) => {
const graphState = roomIdToGraphState[getRoomId()]
if (!graphState) return
graphState.edges.push(edge)
}
const addNode = (node: GNode) => {
const graphState = roomIdToGraphState[getRoomId()]
if (!graphState) return
graphState.nodes.push(node)
}
return {
getRoomId,
setRoomId,
getGraphState,
setGraphState,
deleteGraphState,
addNode,
removeNode,
updateNode,
addEdge,
removeEdge,
updateEdge,
}
}