forked from kousun12/eternal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Graph.js
170 lines (148 loc) · 4.84 KB
/
Graph.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
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
//@flow
import { get, flatten, uniqBy, fromPairs, mapValues } from 'lodash';
import Edge from 'models/Edge';
import NodeBase from 'models/NodeBase';
import type { NodeInSpace, Pos } from 'types';
import type { AnyNode, NodeSerialization } from 'models/NodeBase';
import type { EdgeSerialization } from 'models/Edge';
import { uuid } from 'utils/string';
import type { PosMemo } from 'redux/ducks/graph';
type MetaData = { zoom?: number };
export type GraphSerialization = {
name?: string,
description?: string,
nodes: NodeSerialization<any>[],
edges: EdgeSerialization[],
meta?: MetaData,
};
export default class Graph {
id: string;
name: string = 'untitled';
description: string = '';
meta: MetaData = {};
nodes: NodeInSpace[] = [];
_nodesById: { [string]: NodeInSpace } = {};
edges: Edge[] = [];
constructor(
nodes?: NodeInSpace[] = [],
edges?: Edge[] = [],
name?: string = 'untitled',
description?: string = '',
meta: MetaData = {}
) {
this.id = uuid();
(nodes || []).forEach(nis => this.addNode(nis.node, nis.pos));
(edges || []).forEach(this.addEdge);
this.name = name;
this.description = description || '';
this.meta = meta;
}
nodeWithId: string => ?NodeInSpace = id => this._nodesById[id];
nodeWithIdF: string => NodeInSpace = id => {
const n = this.nodeWithId(id);
if (!n) throw new Error('not found');
return n;
};
addNode: (AnyNode, Pos) => NodeInSpace = (node, pos) => {
const nis = { node, pos };
this._nodesById[node.id] = nis;
this.nodes.push(nis);
node.onAddToGraph();
return nis;
};
setNodes: (NodeInSpace[]) => Graph = nodes => {
this.nodes = nodes;
this._nodesById = fromPairs(nodes.map(n => [n.node.id, n]));
return this;
};
updatePositions = (pos: PosMemo) => {
this.nodes.forEach(nis => {
const p = pos[nis.node.id];
if (p) {
nis.pos = p;
}
});
};
nodeIds = (): string[] => Object.keys(this._nodesById);
nodePositions = (): PosMemo => mapValues(this._nodesById, 'pos');
removeNode: AnyNode => Graph = node => {
node.inputs.forEach(this.removeEdge);
node.outputs.forEach(this.removeEdge);
node.willBeRemoved();
this.setNodes(this.nodes.filter(n => n.node.id !== node.id));
return this;
};
addEdge: Edge => void = edge => {
this.edges.push(edge);
edge.from.addOutput(edge);
edge.to.addInput(edge);
};
removeEdge: Edge => void = edge => {
this.edges = this.edges.filter(e => e.id !== edge.id);
edge.from.removeOutput(edge);
edge.to.removeInput(edge);
};
serialize: (string, ?MetaData) => GraphSerialization = (name, meta) => {
return {
name,
nodes: this.nodes.map(n => n.node.serialize(n.pos.x, n.pos.y)),
edges: this.edges.map(e => e.serialize()),
...(meta && { meta }),
description: this.description || '',
};
};
setName = (name: string) => { this.name = name }
duplicate: (NodeInSpace[]) => NodeInSpace[] = nodes => {
const ids = nodes.map(nis => nis.node.id);
const newNodes = nodes.map(nis =>
this.addNode(NodeBase.duplicate(nis.node), { x: nis.pos.x + 50, y: nis.pos.y + 50 })
);
uniqBy(flatten(nodes.map(nis => nis.node.inputs.concat(nis.node.outputs))), 'id').forEach(e => {
const fIdx = ids.indexOf(e.from.id);
const tIdx = ids.indexOf(e.to.id);
if (fIdx !== -1 && tIdx !== -1) {
this.addEdge(new Edge(newNodes[fIdx].node, newNodes[tIdx].node, e.fromPort, e.toPort));
}
});
return newNodes;
};
dispose = () => {
this.edges.forEach(this.removeEdge);
this.nodes.map(n => n.node).forEach(this.removeNode);
this.edges = [];
this.nodes = [];
this._nodesById = {};
if (get(window, '$graph.id') === this.id) {
window['$graph'] = null;
}
};
static load(json: GraphSerialization): Graph {
const nodesInSpace = json.nodes.map(n => ({ node: NodeBase.load(n), pos: { x: n.x, y: n.y } }));
const nodes = nodesInSpace.map(nis => nis.node);
const edges = json.edges.map(j => Edge.load(j, nodes));
const name = json.name || 'untitled';
const desc = json.description || '';
const meta = json.meta || {};
return new Graph(nodesInSpace, edges, name, desc, meta);
}
static empty(): GraphSerialization {
return { name: 'untitled', edges: [], nodes: [] };
}
static serialization(frm: any): ?GraphSerialization {
return typeof frm === 'object' && frm.edges && frm.nodes ? frm : null;
}
static fromFile(file: File, handler: GraphSerialization => void) {
const fileReader = new FileReader();
fileReader.onload = () => {
const result = fileReader.result;
if (typeof result === 'string') {
try {
handler(JSON.parse(result));
} catch (e) {
console.error('could not load graph', e);
}
}
};
fileReader.readAsText(file);
}
}