-
Notifications
You must be signed in to change notification settings - Fork 0
/
Graph.ts
473 lines (435 loc) · 14.4 KB
/
Graph.ts
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
import * as Common from "cubitt-common";
import * as Collections from "typescript-collections";
import {AbstractElement} from "./AbstractElement";
import {NodeElement} from "./NodeElement";
import {EdgeElement} from "./EdgeElement";
import {ModelElement} from "./ModelElement";
import {ConnectorElement} from "./ConnectorElement";
import {GraphInterface} from "./GraphInterface";
import {ElementType} from "./ElementType";
/**
* Graph containing nodes, connectors, edges and models
*
* NOTICE: this class is used internally in the Project class, always use the Project class
*/
export class Graph implements GraphInterface {
private elements: Common.Dictionary<AbstractElement>;
constructor() {
this.elements = {};
}
/**
* Returns an element given an GUID
*
* @param id GUID representing an element identifier
*/
public getElement(id: Common.Guid): AbstractElement {
let elem = this.elements[id.toString()];
/* istanbul ignore if */
if (elem === undefined) {
/* istanbul ignore next */
throw new Error("Element with GUID " + id.toString() + " not found");
}
return elem;
}
/**
* @inheritdoc
*/
public hasElement(id: Common.Guid): boolean {
return this.elements[id.toString()] !== undefined;
}
/**
* @inheritdoc
*/
public hasModel(id: Common.Guid): boolean {
let elem = this.elements[id.toString()];
return elem !== undefined && elem.getType() === ElementType.Model;
}
/**
* @inheritdoc
*/
public hasNode(id: Common.Guid): boolean {
let elem = this.elements[id.toString()];
return elem !== undefined && elem.getType() === ElementType.Node;
}
/**
* @inheritdoc
*/
public hasConnector(id: Common.Guid): boolean {
let elem = this.elements[id.toString()];
return elem !== undefined && elem.getType() === ElementType.Connector;
}
/**
* @inheritdoc
*/
public hasEdge(id: Common.Guid): boolean {
let elem = this.elements[id.toString()];
return elem !== undefined && elem.getType() === ElementType.Edge;
}
/**
* Removes an element from the graph, WARNING: does not perform a cascading delete (i.e. no removal of orphan edges)
*
* @param id Identifier of the element to remove
* @param ofType Only delete the element if it is of the matching Type, if undefined, this check will be skipped
*/
public deleteElement(id: Common.Guid, ofType?: ElementType): void {
if (ofType === undefined) {
delete this.elements[id.toString()];
} else {
let elem = this.elements[id.toString()];
if (elem !== undefined) {
// It's fine if the elem did not exist (the endresult is the same)
/* istanbul ignore if */
if (elem.getType() !== ofType) {
throw new Error("Attempted to delete a " + elem.getType() + " with delete" + ofType.toString());
}
elem.delete(this);
}
}
}
/**
* @inheritdoc
*/
public addNode(id: Common.Guid, type: string, modelId: Common.Guid, properties: Common.Dictionary<any>): void {
/* istanbul ignore if */
if (this.hasElement(id)) {
throw new Error("An Element with GUID " + id.toString() + " already exists");
}
let model = this.elements[modelId.toString()];
/* istanbul ignore if */
if (model === undefined) {
throw new Error("No model with GUID " + modelId + " could be found");
}
/* istanbul ignore if */
if (model.getType() !== ElementType.Model) {
throw new Error("GUID " + modelId.toString() + " does not belong to a model");
}
/* istanbul ignore if */
if (properties === null || properties === undefined) {
properties = {};
}
properties["type"] = type;
let node = new NodeElement(id, properties);
node.addParentModelNeighbour(modelId);
model.addChildNodeNeighbour(id);
this.elements[node.Id.toString()] = node;
}
/**
* @inheritdoc
*/
public addEdge(id: Common.Guid, type: string, modelId: Common.Guid, startConnectorId: Common.Guid, endConnectorId: Common.Guid, properties: Common.Dictionary<any> = {}) {
// Validate GUID
/* istanbul ignore if */
if (this.hasElement(id)) {
throw new Error("An Element with GUID " + id.toString() + " already exists");
}
// Validate modelID
let model = this.elements[modelId.toString()];
/* istanbul ignore if */
if (model === undefined) {
throw new Error("No model with GUID " + modelId + " could be found");
}
/* istanbul ignore if */
if (model.getType() !== ElementType.Model) {
throw new Error("Element with GUID " + modelId.toString() + " is not a Model");
}
// Validate startConnector
let startConnector = this.elements[startConnectorId.toString()];
/* istanbul ignore if */
if (startConnector === undefined) {
throw new Error("No startConnector with GUID " + startConnectorId + " could be found");
}
/* istanbul ignore if */
if (startConnector.getType() !== ElementType.Connector) {
throw new Error("Invalid startConnectorId, " + startConnectorId + " does not belong to a connector");
}
// Validate endConnectorId
let endConnector = this.elements[endConnectorId.toString()];
/* istanbul ignore if */
if (endConnector === undefined) {
throw new Error("No endConnector with GUID " + endConnectorId + " could be found");
}
/* istanbul ignore if */
if (endConnector.getType() !== ElementType.Connector) {
throw new Error("Invalid endConnectorId, " + endConnectorId + " does not belong to a connector");
}
/* istanbul ignore if */
if (properties === null || properties === undefined) {
properties = {};
}
properties["type"] = type;
let edge = new EdgeElement(id, properties);
edge.addStartConnector(startConnectorId);
edge.addEndConnector(endConnectorId);
startConnector.addChildEdgeNeighbour(id);
endConnector.addChildEdgeNeighbour(id);
model.addChildEdgeNeighbour(id);
edge.addParentModelNeighbour(modelId);
this.elements[id.toString()] = edge;
}
/**
* @inheritdoc
*/
public addConnector(id: Common.Guid, type: string, nodeId: Common.Guid, properties: Common.Dictionary<any>) {
// Validate GUID
/* istanbul ignore if */
if (this.hasElement(id)) {
throw new Error("An Element with GUID " + id.toString() + " already exists");
}
// Validate nodeId exists
let node = this.elements[nodeId.toString()];
/* istanbul ignore if */
if (node === undefined) {
throw new Error("No node with GUID " + nodeId + " could be found");
}
/* istanbul ignore if */
if (node.getType() !== ElementType.Node) {
throw new Error("Invalid nodeId, " + nodeId + " does not belong to a Node");
}
/* istanbul ignore if */
if (properties === null || properties === undefined) {
properties = {};
}
properties["type"] = type;
let connector = new ConnectorElement(id, properties);
node.addChildConnectorNeighbour(id);
connector.addParentNodeNeighbour(nodeId);
this.elements[id.toString()] = connector;
}
/**
* @inheritdoc
*/
public addModel(id: Common.Guid, type: string, properties: Common.Dictionary<any>, parentId?: Common.Guid) {
// Validate GUID
/* istanbul ignore if */
if (this.hasElement(id)) {
throw new Error("An Element with GUID " + id.toString() + " already exists");
}
// If parentId is set validate it
if (parentId !== null && parentId !== undefined) {
// Validate if there is an node or edge with the provided GUID
/* istanbul ignore if */
if ((this.hasNode(parentId) || this.hasEdge(parentId)) === false) {
throw new Error("No Node or Edge with GUID " + parentId.toString() + " could be found");
}
}
/* istanbul ignore if */
if (properties === null || properties === undefined) {
properties = {};
}
properties["type"] = type;
let model = new ModelElement(id, properties);
// Attach it to parent if available
if (parentId !== null && parentId !== undefined) {
let parent = this.getElement(parentId);
parent.addChildModelNeighbour(id);
if (this.hasEdge(parentId)) {
model.addParentEdgeNeighbour(parentId);
}
if (this.hasNode(parentId)) {
model.addParentNodeNeighbour(parentId);
}
}
this.elements[id.toString()] = model;
}
/**
* @inheritdoc
*/
public setProperty(id: Common.Guid, name: string, value: any) {
/* istanbul ignore if */
if (this.hasElement(id) === false) {
throw new Error("An Element with GUID " + id.toString() + " could not be found");
}
this.elements[id.toString()].setProperty(name, value);
}
/**
* @inheritdoc
*/
public deleteNode(id: Common.Guid) {
this.deleteElement(id, ElementType.Node);
}
/**
* @inheritdoc
*/
public deleteEdge(id: Common.Guid) {
this.deleteElement(id, ElementType.Edge);
}
/**
* @inheritdoc
*/
public deleteConnector(id: Common.Guid) {
this.deleteElement(id, ElementType.Connector);
}
/**
* @inheritdoc
*/
public deleteModel(id: Common.Guid) {
this.deleteElement(id, ElementType.Model);
}
/**
* @inheritdoc
*/
public deleteProperty(id: Common.Guid, name: string): void {
let elem = this.elements[id.toString()];
/* istanbul ignore if */
if (elem === undefined) {
throw new Error("Element not found");
}
elem.deleteProperty(name);
}
/**
* @inheritdoc
*/
public deserialize(jsonObject: Object): GraphInterface {
let graph = new Graph();
let models = jsonObject["models"];
let queue: Collections.Queue<Object> = new Collections.Queue<Object>();
let inQueue: Common.Dictionary<Boolean> = {};
// Find root models
for (let modelKey in models) {
let model = models[modelKey];
if (Object.keys(model.neighbours.nodes.parent).length === 0 && Object.keys(model.neighbours.edges.parent).length === 0) {
queue.enqueue({ "type": "model", "element": model.id.toString() });
inQueue[model.id.toString()] = true;
}
}
while (queue.isEmpty() === false) {
let obj = queue.dequeue();
let type = obj["type"];
let elemId = obj["element"];
let elem = jsonObject[type + "s"][elemId.toString()];
let properties = this.propertiesFromJSON(elem["properties"]);
switch (type) {
case "model":
if (elem["neighbours"]["nodes"]["parent"].length > 0) {
graph.addModel(Common.Guid.parse(elem.id), properties["type"], properties, Common.Guid.parse(elem["neighbours"]["nodes"]["parent"][0]));
} else if (elem["neighbours"]["edges"]["parent"].length > 0) {
graph.addModel(Common.Guid.parse(elem.id), properties["type"], properties, Common.Guid.parse(elem["neighbours"]["edges"]["parent"][0]));
} else {
graph.addModel(Common.Guid.parse(elem.id), properties["type"], properties);
}
break;
case "node":
graph.addNode(Common.Guid.parse(elem.id), properties["type"], Common.Guid.parse(elem["neighbours"]["models"]["parent"][0]), properties);
// Add Connectors
let connectors = elem["neighbours"]["connectors"]["child"];
for (let connectorKey of connectors) {
let connector = jsonObject["connectors"][connectorKey];
let id = Common.Guid.parse(connector["id"]);
let connectorProperties = this.propertiesFromJSON(connector["properties"]);
graph.addConnector(id, connectorProperties["type"], Common.Guid.parse(elem.id), connectorProperties);
inQueue[id.toString()] = true;
let edgeIds = connector["neighbours"]["edges"]["child"];
let edges: string[] = [];
for (let edgeId of edgeIds) {
let edge = jsonObject["edges"][edgeId];
let isInQueue = true;
for (let connectorId of edge["neighbours"]["connectors"]["parent"]) {
if (inQueue[connectorId] !== true) {
isInQueue = false;
}
}
if (isInQueue === true) {
edges.push(edgeId);
}
}
this.enqueueChildElement("edge", edges, queue, inQueue);
continue;
}
break;
case "edge":
graph.addEdge(
Common.Guid.parse(elem.id),
properties["type"],
Common.Guid.parse(elem["neighbours"]["models"]["parent"][0]),
Common.Guid.parse(elem["neighbours"]["connectors"]["parent"][0]),
Common.Guid.parse(elem["neighbours"]["connectors"]["parent"][1]),
properties
);
break;
/* istanbul ignore next */
default:
throw new Error("Invalid element type");
}
// Enqueue child elements, we directly add the connectors when processing the node
this.enqueueChildElement("model", elem["neighbours"]["models"]["child"], queue, inQueue);
this.enqueueChildElement("node", elem["neighbours"]["nodes"]["child"], queue, inQueue);
}
return graph;
}
/**
* Iterate over the child elements to add them
*
* @param type Type of the child elements
* @param children the Children to iterate over
* @param queue The queue to add elements to
* @param inQueue register which elements are processed
*/
private enqueueChildElement(type: string, children: string[], queue: Collections.Queue<Object>, inQueue: Common.Dictionary<Boolean>) {
for (let childElem of children) {
/* istanbul ignore else */
if (inQueue[childElem] !== true) {
queue.enqueue({ "type": type, "element": childElem });
inQueue[childElem] = true;
}
}
}
/**
* Creates a Property dictionary from JSON
*
* @param jsonProperties JSON object that contains the properties
*/
private propertiesFromJSON(jsonProperties: Object): Common.Dictionary<any> {
let properties: Common.Dictionary<any> = {};
for (let propertyKey in jsonProperties) {
properties[propertyKey] = jsonProperties[propertyKey];
}
return properties;
}
/**
* @inheritdoc
*/
public serialize() {
let graph = {
"models": {},
"nodes": {},
"edges": {},
"connectors": {}
};
let elements = this.elements;
for (let key in elements) {
let elem = elements[key];
let obj = {
"id": elem.Id.toString(),
"properties": elem.getProperties(),
"neighbours": {
"models": {
"parent": elem.getParentModelNeighbours().map(g => g.toString()),
"child": elem.getChildModelNeighbours().map(g => g.toString())
},
"nodes": {
"parent": elem.getParentNodeNeighbours().map(g => g.toString()),
"child": elem.getChildNodeNeighbours().map(g => g.toString())
},
"edges": {
"parent": elem.getParentEdgeNeighbours().map(g => g.toString()),
"child": elem.getChildEdgeNeighbours().map(g => g.toString())
},
"connectors": {
"parent": elem.getParentConnectorNeighbours().map(g => g.toString()),
"child": elem.getChildConnectorNeighbours().map(g => g.toString())
}
}
};
if (elem.getType() === ElementType.Node) {
graph.nodes[elem.Id.toString()] = obj;
} else if (elem.getType() === ElementType.Edge) {
graph.edges[elem.Id.toString()] = obj;
} else if (elem.getType() === ElementType.Connector) {
graph.connectors[elem.Id.toString()] = obj;
} else {
graph.models[elem.Id.toString()] = obj;
}
}
return graph;
}
}