-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathcytoscape-undo-redo.js
685 lines (576 loc) · 26 KB
/
cytoscape-undo-redo.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
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
;(function () {
'use strict';
// registers the extension on a cytoscape lib ref
var register = function (cytoscape) {
if (!cytoscape) {
return;
} // can't register if cytoscape unspecified
// Get scratch pad reserved for this extension on the given element or the core if 'name' parameter is not set,
// if the 'name' parameter is set then return the related property in the scratch instead of the whole scratchpad
function getScratch (eleOrCy, name) {
if (eleOrCy.scratch("_undoRedo") === undefined) {
eleOrCy.scratch("_undoRedo", {});
}
var scratchPad = eleOrCy.scratch("_undoRedo");
return ( name === undefined ) ? scratchPad : scratchPad[name];
}
// Set the a field (described by 'name' parameter) of scratchPad (that is reserved for this extension
// on an element or the core) to the given value (by 'val' parameter)
function setScratch (eleOrCy, name, val) {
var scratchPad = getScratch(eleOrCy);
scratchPad[name] = val;
eleOrCy.scratch("_undoRedo", scratchPad);
}
// Generate an instance of the extension for the given cy instance
function generateInstance (cy) {
var instance = {};
instance.options = {
isDebug: false, // Debug mode for console messages
actions: {},// actions to be added
undoableDrag: true, // Whether dragging nodes are undoable can be a function as well
stackSizeLimit: undefined, // Size limit of undo stack, note that the size of redo stack cannot exceed size of undo stack
beforeUndo: function () { // callback before undo is triggered.
},
afterUndo: function () { // callback after undo is triggered.
},
beforeRedo: function () { // callback before redo is triggered.
},
afterRedo: function () { // callback after redo is triggered.
},
ready: function () {
}
};
instance.actions = {};
instance.undoStack = [];
instance.redoStack = [];
//resets undo and redo stacks
instance.reset = function(undos, redos)
{
this.undoStack = undos || [];
this.redoStack = redos || [];
}
// Undo last action
instance.undo = function () {
if (!this.isUndoStackEmpty()) {
var action = this.undoStack.pop();
cy.trigger("beforeUndo", [action.name, action.args]);
var res = this.actions[action.name]._undo(action.args);
this.redoStack.push({
name: action.name,
args: res
});
cy.trigger("afterUndo", [action.name, action.args, res]);
return res;
} else if (this.options.isDebug) {
console.log("Undoing cannot be done because undo stack is empty!");
}
};
// Redo last action
instance.redo = function () {
if (!this.isRedoStackEmpty()) {
var action = this.redoStack.pop();
cy.trigger(action.firstTime ? "beforeDo" : "beforeRedo", [action.name, action.args]);
if (!action.args)
action.args = {};
action.args.firstTime = action.firstTime ? true : false;
var res = this.actions[action.name]._do(action.args);
this.undoStack.push({
name: action.name,
args: res
});
if (this.options.stackSizeLimit != undefined && this.undoStack.length > this.options.stackSizeLimit ) {
this.undoStack.shift();
}
cy.trigger(action.firstTime ? "afterDo" : "afterRedo", [action.name, action.args, res]);
return res;
} else if (this.options.isDebug) {
console.log("Redoing cannot be done because redo stack is empty!");
}
};
// Calls registered function with action name actionName via actionFunction(args)
instance.do = function (actionName, args) {
this.redoStack.length = 0;
this.redoStack.push({
name: actionName,
args: args,
firstTime: true
});
return this.redo();
};
// Undo all actions in undo stack
instance.undoAll = function() {
while( !this.isUndoStackEmpty() ) {
this.undo();
}
};
// Redo all actions in redo stack
instance.redoAll = function() {
while( !this.isRedoStackEmpty() ) {
this.redo();
}
};
// Register action with its undo function & action name.
instance.action = function (actionName, _do, _undo) {
this.actions[actionName] = {
_do: _do,
_undo: _undo
};
return this;
};
// Removes action stated with actionName param
instance.removeAction = function (actionName) {
delete this.actions[actionName];
};
// Gets whether undo stack is empty
instance.isUndoStackEmpty = function () {
return (this.undoStack.length === 0);
};
// Gets whether redo stack is empty
instance.isRedoStackEmpty = function () {
return (this.redoStack.length === 0);
};
// Gets actions (with their args) in undo stack
instance.getUndoStack = function () {
return this.undoStack;
};
// Gets actions (with their args) in redo stack
instance.getRedoStack = function () {
return this.redoStack;
};
return instance;
}
// design implementation
cytoscape("core", "undoRedo", function (options, dontInit) {
var cy = this;
var instance = getScratch(cy, 'instance') || generateInstance(cy);
setScratch(cy, 'instance', instance);
if (options) {
for (var key in options)
if (instance.options.hasOwnProperty(key))
instance.options[key] = options[key];
if (options.actions)
for (var key in options.actions)
instance.actions[key] = options.actions[key];
}
if (!getScratch(cy, 'isInitialized') && !dontInit) {
var defActions = defaultActions(cy);
for (var key in defActions)
instance.actions[key] = defActions[key];
setDragUndo(cy, instance.options.undoableDrag);
setScratch(cy, 'isInitialized', true);
}
instance.options.ready();
return instance;
});
function setDragUndo(cy, undoable) {
var lastMouseDownNodeInfo = null;
cy.on("grab", "node", function () {
if (typeof undoable === 'function' ? undoable.call(this) : undoable) {
lastMouseDownNodeInfo = {};
lastMouseDownNodeInfo.lastMouseDownPosition = {
x: this.position("x"),
y: this.position("y")
};
lastMouseDownNodeInfo.node = this;
}
});
cy.on("free", "node", function () {
var instance = getScratch(cy, 'instance');
if (typeof undoable === 'function' ? undoable.call(this) : undoable) {
if (lastMouseDownNodeInfo == null) {
return;
}
var node = lastMouseDownNodeInfo.node;
var lastMouseDownPosition = lastMouseDownNodeInfo.lastMouseDownPosition;
var mouseUpPosition = {
x: node.position("x"),
y: node.position("y")
};
if (mouseUpPosition.x != lastMouseDownPosition.x ||
mouseUpPosition.y != lastMouseDownPosition.y) {
var positionDiff = {
x: mouseUpPosition.x - lastMouseDownPosition.x,
y: mouseUpPosition.y - lastMouseDownPosition.y
};
var nodes;
if (node.selected()) {
nodes = cy.nodes(":visible").filter(":selected");
}
else {
nodes = cy.collection([node]);
}
var param = {
positionDiff: positionDiff,
nodes: nodes, move: false
};
instance.do("drag", param);
lastMouseDownNodeInfo = null;
}
}
});
}
// Default actions
function defaultActions(cy) {
function getTopMostNodes(nodes) {
var nodesMap = {};
for (var i = 0; i < nodes.length; i++) {
nodesMap[nodes[i].id()] = true;
}
var roots = nodes.filter(function (ele, i) {
if(typeof ele === "number") {
ele = i;
}
var parent = ele.parent()[0];
while(parent != null){
if(nodesMap[parent.id()]){
return false;
}
parent = parent.parent()[0];
}
return true;
});
return roots;
}
function moveNodes(positionDiff, nodes, notCalcTopMostNodes) {
var topMostNodes = notCalcTopMostNodes?nodes:getTopMostNodes(nodes);
for (var i = 0; i < topMostNodes.length; i++) {
var node = topMostNodes[i];
var oldX = node.position("x");
var oldY = node.position("y");
//Only simple nodes are moved since the movement of compounds caused the position to be moved twice
if (!node.isParent())
{
node.position({
x: oldX + positionDiff.x,
y: oldY + positionDiff.y
});
}
var children = node.children();
moveNodes(positionDiff, children, true);
}
}
function getEles(_eles) {
return (typeof _eles === "string") ? cy.$(_eles) : _eles;
}
function restoreEles(_eles) {
return getEles(_eles).restore();
}
function returnToPositions(positions) {
var currentPositions = {};
cy.nodes().not(":parent").positions(function (ele, i) {
if(typeof ele === "number") {
ele = i;
}
currentPositions[ele.id()] = {
x: ele.position("x"),
y: ele.position("y")
};
var pos = positions[ele.id()];
return {
x: pos.x,
y: pos.y
};
});
return currentPositions;
}
function getNodePositions() {
var positions = {};
var nodes = cy.nodes();
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
positions[node.id()] = {
x: node.position("x"),
y: node.position("y")
};
}
return positions;
}
function changeParentOld(param) {
var result = {
};
// If this is first time we should move the node to its new parent and relocate it by given posDiff params
// else we should remove the moved eles and restore the eles to restore
if (param.firstTime) {
var newParentId = param.parentData == undefined ? null : param.parentData;
// These eles includes the nodes and their connected edges and will be removed in nodes.move().
// They should be restored in undo
var withDescendant = param.nodes.union(param.nodes.descendants());
result.elesToRestore = withDescendant.union(withDescendant.connectedEdges());
// These are the eles created by nodes.move(), they should be removed in undo.
result.movedEles = param.nodes.move({"parent": newParentId});
var posDiff = {
x: param.posDiffX,
y: param.posDiffY
};
moveNodes(posDiff, result.movedEles);
}
else {
result.elesToRestore = param.movedEles.remove();
result.movedEles = param.elesToRestore.restore();
}
if (param.callback) {
result.callback = param.callback; // keep the provided callback so it can be reused after undo/redo
param.callback(result.movedEles); // apply the callback on newly created elements
}
return result;
}
function changeParentNew(param) {
var result = {
};
// If this is first time we should move the node to its new parent and relocate it by given posDiff params
// else we should remove the moved eles and restore the eles to restore
if (param.firstTime) {
var newParentId = param.parentData == undefined ? null : param.parentData;
// These eles includes the nodes and their connected edges and will be removed in nodes.move().
// They should be restored in undo
var withDescendant = param.nodes.union(param.nodes.descendants());
var parentData = {};
withDescendant.forEach(function(ele){
if(ele.parent().id())
parentData[ele.id()] = ele.parent();
else
parentData[ele.id()] = null;
});
var positionData = {};
withDescendant.forEach(function(ele){
positionData[ele.id()] = {};
positionData[ele.id()].x = ele.position('x');
positionData[ele.id()].y = ele.position('y');
});
result.oldParent = parentData;
result.oldPosition = positionData;
result.newParent = newParentId;
result.movedEles = withDescendant;
param.nodes.move({"parent": newParentId}).nodes();
var posDiff = {
x: param.posDiffX,
y: param.posDiffY
};
moveNodes(posDiff, result.movedEles);
}
else {
result.oldParent = {};
param.movedEles.forEach(function(ele){
if(ele.parent().id())
result.oldParent[ele.id()] = ele.parent();
else
result.oldParent[ele.id()] = null;
});
result.oldPosition = {};
param.movedEles.forEach(function(ele){
result.oldPosition[ele.id()] = {};
result.oldPosition[ele.id()].x = ele.position("x");
result.oldPosition[ele.id()].y = ele.position("y");
});
result.newParent = param.oldParent;
result.movedEles = param.movedEles;
result.movedEles.forEach(function(ele){
if(typeof result.newParent !== 'object')
ele.move({'parent': result.newParent});
else if(result.newParent[ele.id()] == null)
ele.move({'parent': null});
else
ele.move({'parent': result.newParent[ele.id()].id()});
ele.position(param.oldPosition[ele.id()]);
});
}
if (param.callback) {
result.callback = param.callback; // keep the provided callback so it can be reused after undo/redo
param.callback(result.movedEles); // apply the callback on newly created elements
}
return result;
}
// function registered in the defaultActions below
// to be used like .do('batch', actionList)
// allows to apply any quantity of registered action in one go
// the whole batch can be undone/redone with one key press
function batch (actionList, doOrUndo) {
var tempStack = []; // corresponds to the results of every action queued in actionList
var instance = getScratch(cy, 'instance'); // get extension instance through cy
var actions = instance.actions;
// here we need to check in advance if all the actions provided really correspond to available functions
// if one of the action cannot be executed, the whole batch is corrupted because we can't go back after
for (var i = 0; i < actionList.length; i++) {
var action = actionList[i];
if (!actions.hasOwnProperty(action.name)) {
throw "Action " + action.name + " does not exist as an undoable function";
}
}
for (var i = 0; i < actionList.length; i++) {
var action = actionList[i];
// firstTime property is automatically injected into actionList by the do() function
// we use that to pass it down to the actions in the batch
action.param.firstTime = actionList.firstTime;
var actionResult;
if (doOrUndo == "undo") {
actionResult = actions[action.name]._undo(action.param);
}
else {
actionResult = actions[action.name]._do(action.param);
}
tempStack.unshift({
name: action.name,
param: actionResult
});
}
return tempStack;
};
return {
"add": {
_do: function (eles) {
return eles.firstTime ? cy.add(eles) : restoreEles(eles);
},
_undo: cy.remove
},
"remove": {
_do: cy.remove,
_undo: restoreEles
},
"restore": {
_do: restoreEles,
_undo: cy.remove
},
"select": {
_do: function (_eles) {
return getEles(_eles).select();
},
_undo: function (_eles) {
return getEles(_eles).unselect();
}
},
"unselect": {
_do: function (_eles) {
return getEles(_eles).unselect();
},
_undo: function (_eles) {
return getEles(_eles).select();
}
},
"move": {
_do: function (args) {
var eles = getEles(args.eles);
var nodes = eles.nodes();
var edges = eles.edges();
var oldNodesParents = [];
var oldEdgesSources = [];
var oldEdgesTargets = [];
nodes.forEach(function(node){
oldNodesParents.push(node.parent().length > 1 ? node.parent().id() : null);
});
edges.forEach(function(edge){
oldEdgesSources.push(edge.source().id());
oldEdgesTargets.push(edge.target().id());
})
return {
oldNodesParents: oldNodesParents,
newNodes: nodes.move(args.location),
oldEdgesSources: oldEdgesSources,
oldEdgesTargets: oldEdgesTargets,
newEdges: edges.move(args.location)
};
},
_undo: function (eles) {
var newEles = cy.collection();
var location = {};
if (eles.newNodes.length > 0) {
location.parent = eles.newNodes[0].parent().id();
for (var i = 0; i < eles.newNodes.length; i++) {
var newNode = eles.newNodes[i].move({
parent: eles.oldNodesParents[i]
});
newEles = newEles.union(newNode);
}
} else {
location.source = eles.newEdges[0].source().id();
location.target = eles.newEdges[0].target().id();
for (var i = 0; i < eles.newEdges.length; i++) {
var newEdge = eles.newEdges[i].move({
source: eles.oldEdgesSources[i],
target: eles.oldEdgesTargets[i]
});
newEles = newEles.union(newEdge);
}
}
return {
eles: newEles,
location: location
};
}
},
"drag": {
_do: function (args) {
if (args.move){
moveNodes(args.positionDiff, args.nodes);
cy.elements().unselect();
}
return args;
},
_undo: function (args) {
var diff = {
x: -1 * args.positionDiff.x,
y: -1 * args.positionDiff.y
};
var result = {
positionDiff: args.positionDiff,
nodes: args.nodes,
move: true
};
moveNodes(diff, args.nodes);
cy.elements().unselect();
return result;
}
},
"layout": {
_do: function (args) {
if (args.firstTime){
var positions = getNodePositions();
var layout;
if(args.eles) {
layout = getEles(args.eles).layout(args.options);
}
else {
layout = cy.layout(args.options);
}
// Do this check for cytoscape.js backward compatibility
if (layout && layout.run) {
layout.run();
}
return positions;
} else
return returnToPositions(args);
},
_undo: function (nodesData) {
return returnToPositions(nodesData);
}
},
"changeParent": {
_do: function (args) {
return (cy.nodes()[0].component ? changeParentNew(args) : changeParentOld(args));
},
_undo: function (args) {
return (cy.nodes()[0].component ? changeParentNew(args) : changeParentOld(args));
}
},
"batch": {
_do: function (args) {
return batch(args, "do");
},
_undo: function (args) {
return batch(args, "undo");
}
}
};
}
};
if (typeof module !== 'undefined' && module.exports) { // expose as a commonjs module
module.exports = register;
}
if (typeof define !== 'undefined' && define.amd) { // expose as an amd/requirejs module
define('cytoscape.js-undo-redo', function () {
return register;
});
}
if (typeof cytoscape !== 'undefined') { // expose to global cytoscape (i.e. window.cytoscape)
register(cytoscape);
}
})();