This repository has been archived by the owner on Jun 4, 2019. It is now read-only.
/
canvas.service.ts
311 lines (265 loc) · 9.97 KB
/
canvas.service.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
/**
* @license
* Copyright 2017 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Injectable, EventEmitter, ChangeDetectorRef, Output } from '@angular/core';
import { CanvasConstants } from '@dataservices/virtualization/view-editor/view-canvas/canvas-constants';
import { CanvasNode, CanvasLink, CanvasGraph } from '@dataservices/virtualization/view-editor/view-canvas/models';
import { ViewCanvasEvent } from "@dataservices/virtualization/view-editor/view-canvas/event/view-canvas-event";
import { ViewCanvasEventType } from "@dataservices/virtualization/view-editor/view-canvas/event/view-canvas-event-type.enum";
import { Command } from "@dataservices/virtualization/view-editor/command/command";
import * as d3 from 'd3';
import * as _ from "lodash";
@Injectable()
export class CanvasService {
/**
* An event fired when the state of the canvas has changed.
*
* @type {EventEmitter<ViewCanvasEvent>}
*/
@Output() public canvasEvent: EventEmitter< ViewCanvasEvent > = new EventEmitter();
private canvasGraph: CanvasGraph;
private viewReference: ChangeDetectorRef;
/**
* This service will provide methods to enable user interaction with elements
* while maintaining the d3 simulations physics
*/
constructor() {
// Nothing to do
}
/**
* The interactable graph.
* This method does not interact with the document, purely physical calculations with d3
*/
public newCanvasGraph(options: { width: number, height: number }, changeDetectorRef: ChangeDetectorRef): CanvasGraph {
this.viewReference = changeDetectorRef;
this.canvasGraph = new CanvasGraph(this, options);
this.canvasGraph.nodesSelected.subscribe((nodes) => {
const selection = [];
if (nodes) {
nodes.forEach((node) => {
selection.push(node.decodedId + Command.identDivider + node.decodePayload);
});
}
const event = ViewCanvasEvent.create(ViewCanvasEventType.CANVAS_SELECTION_CHANGED, selection);
this.canvasEvent.emit(event);
});
/**
* Binding change detection check on each tick
* This along with an onPush change detection strategy should enforce checking only when relevant!
* This improves scripting computation duration, consistently.
* Also, it makes sense to avoid unnecessary checks when we are dealing only with simulations data binding.
*/
this.canvasGraph.ticker.subscribe((d) => {
this.viewReference.markForCheck();
});
return this.canvasGraph;
}
private stopPropagation(): void {
// Stop propagration of click event to parent svg
d3.event.stopPropagation();
// Stop shift-left-click shortcut being fired (firefox opens a new tab/window)
d3.event.preventDefault();
}
/**
* Callback for the command icon when the command has been depressed or not
*/
private commandIconChangeCallback(nodeId: string, commandType: string, depressed: boolean): void {
console.log(" commandIconChangeCallback: " + nodeId + " " + commandType + " " + depressed);
const selection = d3.select('#' + nodeId + '-' + commandType);
selection.attr('xlink:href', this.commandIcon(commandType, depressed));
this.stopPropagation();
}
private addNodeCallback(source: CanvasNode): void {
let eventType = null;
const args = [];
if (source.type === CanvasConstants.SOURCE_TYPE) {
eventType = ViewCanvasEventType.CREATE_COMPOSITION;
args.push(source.decodedId);
args.push(source.decodePayload);
} else if (source.type === CanvasConstants.COMPOSITION_TYPE)
eventType = ViewCanvasEventType.CREATE_SOURCE;
const selectionEvent = ViewCanvasEvent.create(ViewCanvasEventType.CANVAS_SELECTION_CHANGED, args);
this.canvasEvent.emit(selectionEvent);
const event = ViewCanvasEvent.create(eventType, args);
this.canvasEvent.emit(event);
//
// //
// // Ensure all nodes have been unfixed
// // to allow the graph to properly relayout
// //
// this.canvasGraph.unfixNodes();
//
// //
// // Fix the source node
// //
// source.setFixed(true);
//
// let type = null;
// if (source.type === CanvasConstants.SOURCE_TYPE)
// type = CanvasConstants.COMPOSITION_TYPE;
// else
// type = CanvasConstants.SOURCE_TYPE;
//
// const tgtId = this.createNode(type, '<<ToBeImplemented>>');
// const srcId = source.id;
//
// //
// // Create the link and update the graph
// //
// this.createLink(srcId, tgtId, true);
this.stopPropagation();
}
private removeNodeCallback(node: CanvasNode): void {
const args = [];
//
// Send the decoded id and payload so that it can be parsed
// and the source path extracted from it if required
//
args.push(node.decodedId);
args.push(node.decodePayload);
const selectionEvent = ViewCanvasEvent.create(ViewCanvasEventType.CANVAS_SELECTION_CHANGED, args);
this.canvasEvent.emit(selectionEvent);
const event = ViewCanvasEvent.create(ViewCanvasEventType.DELETE_NODE, args);
this.canvasEvent.emit(event);
this.stopPropagation();
}
public nodes(): CanvasNode[] {
if (!this.canvasGraph)
return new Array<CanvasNode>();
return this.canvasGraph.nodes;
}
public links(): CanvasLink[] {
if (!this.canvasGraph)
return new Array<CanvasLink>();
return this.canvasGraph.links;
}
public clear(): void {
if (this.canvasGraph == null)
return;
this.canvasGraph.clear();
}
/**
* Makes sure both the canvas graph and the
* view are up to date and all events have
* been wired up.
*/
public update(refreshGraph: boolean, options?: any): void {
if (this.canvasGraph && refreshGraph) {
if (options !== undefined)
this.canvasGraph.setOptions(options);
this.canvasGraph.refresh();
}
if (this.viewReference)
this.viewReference.detectChanges();
const svg = d3.select(CanvasConstants.CSS_GRAPH_ID);
const svgGroup = svg.select('g');
//
// Create zoom / pan behaviour
//
const zoom = d3.zoom()
.scaleExtent([0.1, 3])
.on('zoom', () => {
svgGroup.attr("transform", d3.event.transform);
});
//
// Add mouse click listener and zoom listener to graph
//
svg
.on('click', () => this.canvasGraph.selectionCallback(null))
.call(zoom);
//
// Add mouse selection listener on each node
//
const nodeSelection = d3.selectAll(CanvasConstants.CSS_NODE_VISUAL_GROUP_CLASS);
nodeSelection
.data(this.canvasGraph.nodes)
.on('click', (cn) => this.canvasGraph.selectionCallback(cn));
//
// Add mouse listener on each plus button
//
const plusSelection = d3.selectAll(CanvasConstants.CSS_NODE_VISUAL_TOOLS_PLUS_CLASS);
plusSelection
.data(this.canvasGraph.nodes)
.on('mousedown', (cn) => this.commandIconChangeCallback(cn.id, 'plus', true))
.on('mouseup', (cn) => this.commandIconChangeCallback(cn.id, 'plus', false))
.on('click', (src) => this.addNodeCallback(src));
//
// Add mouse listener on each minus button
//
const minusSelection = d3.selectAll(CanvasConstants.CSS_NODE_VISUAL_TOOLS_MINUS_CLASS);
minusSelection
.data(this.canvasGraph.nodes)
.on('mousedown', (cn) => this.commandIconChangeCallback(cn.id, 'minus', true))
.on('mouseup', (cn) => this.commandIconChangeCallback(cn.id, 'minus', false))
.on('click', (cn) => this.removeNodeCallback(cn));
}
/**
* Find the bounding box of the element associated with
* the given canvas node. The box represents the outer
* perimeter of the drawn element, including x, y, width and height
*/
public boundingBox(elementId: string): any {
if (_.isEmpty(elementId))
return null;
const selection = d3.select('#' + elementId);
if (selection)
return (selection.node() as SVGGraphicsElement).getBBox();
return null;
}
/**
* @returns the icon for the command type provided. If depressed then
* returns the depressed version of the icon
*/
public commandIcon(cmdType: string, depressed: boolean): string {
if (depressed)
return "/assets/iconfinder/Aha-soft/" + cmdType + "-depressed.png";
return "/assets/iconfinder/Aha-soft/" + cmdType + ".png";
}
/**
* Create a new node and add it to the graph
*/
public createNode(id: string, payload: string, type: string, label: string, refresh?: boolean): string {
if (! this.canvasGraph)
throw new Error("A canvas graph is required before creating a node");
const canvasNode = this.canvasGraph.addNode(id, payload, type, label, refresh);
return canvasNode.id;
}
/**
* Delete the node with the given id
*/
public deleteNode(nodeId: string, refresh?: boolean): void {
if (! this.canvasGraph)
throw new Error("A canvas graph is required before removing a node");
if (nodeId.includes(Command.identDivider)) {
//
// identifier has been delivered as plaintext
// while the node identifiers are encoded
//
nodeId = CanvasNode.encodeId(nodeId);
const idParts = nodeId.split(Command.identDivider);
nodeId = idParts[0];
}
this.canvasGraph.removeNode(nodeId, refresh);
}
/**
* Create a new link and add it to the graph
*/
public createLink(source: string, target: string, refresh?: boolean): void {
if (! this.canvasGraph)
throw new Error("A canvas graph is required before creating a node");
this.canvasGraph.addLink(source, target, refresh);
}
}