-
Notifications
You must be signed in to change notification settings - Fork 879
Expand file tree
/
Copy pathCell.mjs
More file actions
1001 lines (767 loc) · 30.4 KB
/
Cell.mjs
File metadata and controls
1001 lines (767 loc) · 30.4 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
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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
uniqueId,
union,
result,
merge,
forIn,
isObject,
isEqual,
isString,
cloneDeep,
omit,
uuid,
isEmpty,
assign,
uniq,
toArray,
setByPath,
unsetByPath,
getByPath,
timing,
interpolate,
nextFrame,
without,
cancelFrame,
defaultsDeep,
has,
sortBy,
defaults,
objectDifference
} from '../util/util.mjs';
import { Model } from '../mvc/Model.mjs';
import { cloneCells } from '../util/cloneCells.mjs';
import { attributes } from './attributes/index.mjs';
import * as g from '../g/index.mjs';
// Cell base model.
// --------------------------
const attributesMerger = function(a, b) {
if (Array.isArray(a)) {
return b;
}
};
function removeEmptyAttributes(obj) {
// Remove toplevel empty attributes
for (const key in obj) {
const objValue = obj[key];
const isRealObject = isObject(objValue) && !Array.isArray(objValue);
if (!isRealObject) continue;
if (isEmpty(objValue)) {
delete obj[key];
}
}
}
export const Cell = Model.extend({
// This is the same as mvc.Model with the only difference that is uses util.merge
// instead of just _.extend. The reason is that we want to mixin attributes set in upper classes.
constructor: function(attributes, options) {
var defaults;
var attrs = attributes || {};
if (typeof this.preinitialize === 'function') {
// Check to support an older version
this.preinitialize.apply(this, arguments);
}
this.cid = uniqueId('c');
this.attributes = {};
if (options && options.collection) this.collection = options.collection;
if (options && options.parse) attrs = this.parse(attrs, options) || {};
if ((defaults = result(this, 'defaults'))) {
//<custom code>
// Replaced the call to _.defaults with util.merge.
const customizer = (options && options.mergeArrays === true) ? false : attributesMerger;
attrs = merge({}, defaults, attrs, customizer);
//</custom code>
}
this.set(attrs, options);
this.changed = {};
this.initialize.apply(this, arguments);
},
translate: function(dx, dy, opt) {
throw new Error('Must define a translate() method.');
},
toJSON: function(opt) {
const { ignoreDefaults, ignoreEmptyAttributes = false } = opt || {};
const defaults = result(this.constructor.prototype, 'defaults');
if (ignoreDefaults === false) {
// Return all attributes without omitting the defaults
const finalAttributes = cloneDeep(this.attributes);
if (!ignoreEmptyAttributes) return finalAttributes;
removeEmptyAttributes(finalAttributes);
return finalAttributes;
}
let defaultAttributes = {};
let attributes = cloneDeep(this.attributes);
if (ignoreDefaults === true) {
// Compare all attributes with the defaults
defaultAttributes = defaults;
} else {
// Compare only the specified attributes with the defaults, use `attrs` as a default if not specified
const differentiateKeys = Array.isArray(ignoreDefaults) ? ignoreDefaults : ['attrs'];
differentiateKeys.forEach((key) => {
defaultAttributes[key] = defaults[key] || {};
});
}
// Omit `id` and `type` attribute from the defaults since it should be always present
const finalAttributes = objectDifference(attributes, omit(defaultAttributes, 'id', 'type'), { maxDepth: 4 });
if (ignoreEmptyAttributes) {
removeEmptyAttributes(finalAttributes);
}
return finalAttributes;
},
initialize: function(options) {
const idAttribute = this.getIdAttribute();
if (!options || options[idAttribute] === undefined) {
this.set(idAttribute, this.generateId(), { silent: true });
}
this._transitionIds = {};
this._scheduledTransitionIds = {};
// Collect ports defined in `attrs` and keep collecting whenever `attrs` object changes.
this.processPorts();
this.on('change:attrs', this.processPorts, this);
},
getIdAttribute: function() {
return this.idAttribute || 'id';
},
generateId: function() {
return uuid();
},
/**
* @deprecated
*/
processPorts: function() {
// Whenever `attrs` changes, we extract ports from the `attrs` object and store it
// in a more accessible way. Also, if any port got removed and there were links that had `target`/`source`
// set to that port, we remove those links as well (to follow the same behaviour as
// with a removed element).
var previousPorts = this.ports;
// Collect ports from the `attrs` object.
var ports = {};
forIn(this.get('attrs'), function(attrs, selector) {
if (attrs && attrs.port) {
// `port` can either be directly an `id` or an object containing an `id` (and potentially other data).
if (attrs.port.id !== undefined) {
ports[attrs.port.id] = attrs.port;
} else {
ports[attrs.port] = { id: attrs.port };
}
}
});
// Collect ports that have been removed (compared to the previous ports) - if any.
// Use hash table for quick lookup.
var removedPorts = {};
forIn(previousPorts, function(port, id) {
if (!ports[id]) removedPorts[id] = true;
});
// Remove all the incoming/outgoing links that have source/target port set to any of the removed ports.
if (this.graph && !isEmpty(removedPorts)) {
var inboundLinks = this.graph.getConnectedLinks(this, { inbound: true });
inboundLinks.forEach(function(link) {
if (removedPorts[link.get('target').port]) link.remove();
});
var outboundLinks = this.graph.getConnectedLinks(this, { outbound: true });
outboundLinks.forEach(function(link) {
if (removedPorts[link.get('source').port]) link.remove();
});
}
// Update the `ports` object.
this.ports = ports;
},
remove: function(opt = {}) {
// Store the graph in a variable because `this.graph` won't be accessible
// after `this.trigger('remove', ...)` down below.
const { graph, collection } = this;
if (!graph) {
// The collection is a common mvc collection (not the graph collection).
if (collection) collection.remove(this, opt);
return this;
}
graph.startBatch('remove');
// First, unembed this cell from its parent cell if there is one.
const parentCell = this.getParentCell();
if (parentCell) {
parentCell.unembed(this, opt);
}
// Remove also all the cells, which were embedded into this cell
const embeddedCells = this.getEmbeddedCells();
for (let i = 0, n = embeddedCells.length; i < n; i++) {
const embed = embeddedCells[i];
if (embed) {
embed.remove(opt);
}
}
this.trigger('remove', this, graph.attributes.cells, opt);
graph.stopBatch('remove');
return this;
},
toFront: function(opt) {
const { graph } = this;
if (graph) {
opt = defaults(opt || {}, { foregroundEmbeds: true });
let cells;
if (opt.deep) {
cells = this.getEmbeddedCells({ deep: true, breadthFirst: opt.breadthFirst !== false, sortSiblings: opt.foregroundEmbeds });
cells.unshift(this);
} else {
cells = [this];
}
const sortedCells = opt.foregroundEmbeds ? cells : sortBy(cells, cell => cell.z());
const layerName = this.layer();
const maxZ = graph.maxZIndex(layerName);
let z = maxZ - cells.length + 1;
const layerCells = graph.getLayerCells(layerName);
let shouldUpdate = (layerCells.indexOf(sortedCells[0]) !== (layerCells.length - cells.length));
if (!shouldUpdate) {
shouldUpdate = sortedCells.some(function(cell, index) {
return cell.z() !== z + index;
});
}
if (shouldUpdate) {
this.startBatch('to-front');
z = z + cells.length;
sortedCells.forEach(function(cell, index) {
cell.set('z', z + index, opt);
});
this.stopBatch('to-front');
}
}
return this;
},
toBack: function(opt) {
const { graph } = this;
if (graph) {
opt = defaults(opt || {}, { foregroundEmbeds: true });
let cells;
if (opt.deep) {
cells = this.getEmbeddedCells({ deep: true, breadthFirst: opt.breadthFirst !== false, sortSiblings: opt.foregroundEmbeds });
cells.unshift(this);
} else {
cells = [this];
}
const sortedCells = opt.foregroundEmbeds ? cells : sortBy(cells, cell => cell.z());
const layerName = this.layer();
let z = graph.minZIndex(layerName);
const layerCells = graph.getLayerCells(layerName);
let shouldUpdate = (layerCells.indexOf(sortedCells[0]) !== 0);
if (!shouldUpdate) {
shouldUpdate = sortedCells.some(function(cell, index) {
return cell.z() !== z + index;
});
}
if (shouldUpdate) {
this.startBatch('to-back');
z -= cells.length;
sortedCells.forEach(function(cell, index) {
cell.set('z', z + index, opt);
});
this.stopBatch('to-back');
}
}
return this;
},
parent: function(parent, opt) {
// getter
if (parent === undefined) return this.get('parent');
// setter
return this.set('parent', parent, opt);
},
embed: function(cell, opt = {}) {
const cells = Array.isArray(cell) ? cell : [cell];
if (!this.canEmbed(cells)) {
throw new Error('Recursive embedding not allowed.');
}
if (opt.reparent) {
const parents = uniq(cells.map(c => c.getParentCell()));
// Unembed cells from their current parents.
parents.forEach((parent) => {
// Cell doesn't have to be embedded.
if (!parent) return;
// Pass all the `cells` since the `dia.Cell._unembedCells` method can handle cases
// where not all elements of `cells` are embedded in the same parent.
parent._unembedCells(cells, opt);
});
} else if (cells.some(c => c.isEmbedded() && this.id !== c.parent())) {
throw new Error('Embedding of already embedded cells is not allowed.');
}
this._embedCells(cells, opt);
return this;
},
unembed: function(cell, opt) {
const cells = Array.isArray(cell) ? cell : [cell];
this._unembedCells(cells, opt);
return this;
},
canEmbed: function(cell) {
const cells = Array.isArray(cell) ? cell : [cell];
return cells.every(c => this !== c && !this.isEmbeddedIn(c));
},
_embedCells: function(cells, opt) {
const batchName = 'embed';
this.startBatch(batchName);
const embeds = assign([], this.get('embeds'));
cells.forEach(cell => {
// We keep all element ids after link ids.
embeds[cell.isLink() ? 'unshift' : 'push'](cell.id);
cell.parent(this.id, opt);
});
this.set('embeds', uniq(embeds), opt);
this.stopBatch(batchName);
},
_unembedCells: function(cells, opt) {
const batchName = 'unembed';
this.startBatch(batchName);
cells.forEach(cell => cell.unset('parent', opt));
this.set('embeds', without(this.get('embeds'), ...cells.map(cell => cell.id)), opt);
this.stopBatch(batchName);
},
getParentCell: function() {
// unlike link.source/target, cell.parent stores id directly as a string
var parentId = this.parent();
var graph = this.graph;
return (parentId && graph && graph.getCell(parentId)) || null;
},
// Return an array of ancestor cells.
// The array is ordered from the parent of the cell
// to the most distant ancestor.
getAncestors: function() {
var ancestors = [];
if (!this.graph) {
return ancestors;
}
var parentCell = this.getParentCell();
while (parentCell) {
ancestors.push(parentCell);
parentCell = parentCell.getParentCell();
}
return ancestors;
},
getEmbeddedCells: function(opt) {
opt = opt || {};
// Cell models can only be retrieved when this element is part of a collection.
// There is no way this element knows about other cells otherwise.
// This also means that calling e.g. `translate()` on an element with embeds before
// adding it to a graph does not translate its embeds.
if (!this.graph) {
return [];
}
if (opt.deep) {
if (opt.breadthFirst) {
return this._getEmbeddedCellsBfs(opt.sortSiblings);
} else {
return this._getEmbeddedCellsDfs(opt.sortSiblings);
}
}
const embeddedIds = this.get('embeds');
if (isEmpty(embeddedIds)) {
return [];
}
let cells = embeddedIds.map(this.graph.getCell, this.graph);
if (opt.sortSiblings) {
cells = sortBy(cells, cell => cell.z());
}
return cells;
},
_getEmbeddedCellsBfs: function(sortSiblings) {
const cells = [];
const queue = [];
queue.push(this);
while (queue.length > 0) {
const current = queue.shift();
cells.push(current);
const embeddedCells = current.getEmbeddedCells({ sortSiblings: sortSiblings });
queue.push(...embeddedCells);
}
cells.shift();
return cells;
},
_getEmbeddedCellsDfs: function(sortSiblings) {
const cells = [];
const stack = [];
stack.push(this);
while (stack.length > 0) {
const current = stack.pop();
cells.push(current);
const embeddedCells = current.getEmbeddedCells({ sortSiblings: sortSiblings });
// When using the stack, cells that are embedded last are processed first.
// To maintain the original order, we need to push the cells in reverse order
for (let i = embeddedCells.length - 1; i >= 0; --i) {
stack.push(embeddedCells[i]);
}
}
cells.shift();
return cells;
},
isEmbeddedIn: function(cell, opt) {
var cellId = isString(cell) ? cell : cell.id;
var parentId = this.parent();
opt = assign({ deep: true }, opt);
// See getEmbeddedCells().
if (this.graph && opt.deep) {
while (parentId) {
if (parentId === cellId) {
return true;
}
parentId = this.graph.getCell(parentId).parent();
}
return false;
} else {
// When this cell is not part of a collection check
// at least whether it's a direct child of given cell.
return parentId === cellId;
}
},
// Whether or not the cell is embedded in any other cell.
isEmbedded: function() {
return !!this.parent();
},
// Isolated cloning. Isolated cloning has two versions: shallow and deep (pass `{ deep: true }` in `opt`).
// Shallow cloning simply clones the cell and returns a new cell with different ID.
// Deep cloning clones the cell and all its embedded cells recursively.
clone: function(opt) {
opt = opt || {};
if (!opt.deep) {
// Shallow cloning.
var clone = Model.prototype.clone.apply(this, arguments);
// We don't want the clone to have the same ID as the original.
clone.set(this.getIdAttribute(), this.generateId());
// A shallow cloned element does not carry over the original embeds.
clone.unset('embeds');
// And can not be embedded in any cell
// as the clone is not part of the graph.
clone.unset('parent');
return clone;
} else {
// Deep cloning.
// For a deep clone, simply call `graph.cloneCells()` with the cell and all its embedded cells.
return toArray(cloneCells([this].concat(this.getEmbeddedCells({ deep: true }))));
}
},
// A convenient way to set nested properties.
// This method merges the properties you'd like to set with the ones
// stored in the cell and makes sure change events are properly triggered.
// You can either set a nested property with one object
// or use a property path.
// The most simple use case is:
// `cell.prop('name/first', 'John')` or
// `cell.prop({ name: { first: 'John' } })`.
// Nested arrays are supported too:
// `cell.prop('series/0/data/0/degree', 50)` or
// `cell.prop({ series: [ { data: [ { degree: 50 } ] } ] })`.
prop: function(props, value, opt) {
var delim = '/';
var _isString = isString(props);
if (_isString || Array.isArray(props)) {
// Get/set an attribute by a special path syntax that delimits
// nested objects by the colon character.
if (arguments.length > 1) {
var path;
var pathArray;
if (_isString) {
path = props;
pathArray = path.split('/');
} else {
path = props.join(delim);
pathArray = props.slice();
}
var property = pathArray[0];
var pathArrayLength = pathArray.length;
const options = opt || {};
options.propertyPath = path;
options.propertyValue = value;
options.propertyPathArray = pathArray;
if (!('rewrite' in options)) {
options.rewrite = false;
}
var update = {};
// Initialize the nested object. Sub-objects are either arrays or objects.
// An empty array is created if the sub-key is an integer. Otherwise, an empty object is created.
// Note that this imposes a limitation on object keys one can use with Inspector.
// Pure integer keys will cause issues and are therefore not allowed.
var initializer = update;
var prevProperty = property;
for (var i = 1; i < pathArrayLength; i++) {
var pathItem = pathArray[i];
var isArrayIndex = Number.isFinite(_isString ? Number(pathItem) : pathItem);
initializer = initializer[prevProperty] = isArrayIndex ? [] : {};
prevProperty = pathItem;
}
// Fill update with the `value` on `path`.
update = setByPath(update, pathArray, value, '/');
var baseAttributes = merge({}, this.attributes);
// if rewrite mode enabled, we replace value referenced by path with
// the new one (we don't merge).
options.rewrite && unsetByPath(baseAttributes, path, '/');
// Merge update with the model attributes.
var attributes = merge(baseAttributes, update);
// Finally, set the property to the updated attributes.
return this.set(property, attributes[property], options);
} else {
return getByPath(this.attributes, props, delim);
}
}
const options = value || {};
// Note: '' is not the path to the root. It's a path with an empty string i.e. { '': {}}.
options.propertyPath = null;
options.propertyValue = props;
options.propertyPathArray = [];
if (!('rewrite' in options)) {
options.rewrite = false;
}
// Create a new object containing only the changed attributes.
const changedAttributes = {};
for (const key in props) {
// Merging the values of changed attributes with the current ones.
const { changedValue } = merge({}, { changedValue: this.attributes[key] }, { changedValue: props[key] });
changedAttributes[key] = changedValue;
}
return this.set(changedAttributes, options);
},
// A convenient way to unset nested properties
removeProp: function(path, opt) {
opt = opt || {};
var pathArray = Array.isArray(path) ? path : path.split('/');
// Once a property is removed from the `attrs` attribute
// the cellView will recognize a `dirty` flag and re-render itself
// in order to remove the attribute from SVG element.
var property = pathArray[0];
if (property === 'attrs') opt.dirty = true;
if (pathArray.length === 1) {
// A top level property
return this.unset(path, opt);
}
// A nested property
var nestedPath = pathArray.slice(1);
var propertyValue = this.get(property);
if (propertyValue === undefined || propertyValue === null) return this;
propertyValue = cloneDeep(propertyValue);
unsetByPath(propertyValue, nestedPath, '/');
return this.set(property, propertyValue, opt);
},
// A convenient way to set nested attributes.
attr: function(attrs, value, opt) {
var args = Array.from(arguments);
if (args.length === 0) {
return this.get('attrs');
}
if (Array.isArray(attrs)) {
args[0] = ['attrs'].concat(attrs);
} else if (isString(attrs)) {
// Get/set an attribute by a special path syntax that delimits
// nested objects by the colon character.
args[0] = 'attrs/' + attrs;
} else {
args[0] = { 'attrs' : attrs };
}
return this.prop.apply(this, args);
},
// A convenient way to unset nested attributes
removeAttr: function(path, opt) {
if (Array.isArray(path)) {
return this.removeProp(['attrs'].concat(path));
}
return this.removeProp('attrs/' + path, opt);
},
transition: function(path, value, opt, delim) {
delim = delim || '/';
var defaults = {
duration: 100,
delay: 10,
timingFunction: timing.linear,
valueFunction: interpolate.number
};
opt = assign(defaults, opt);
var firstFrameTime = 0;
var interpolatingFunction;
var setter = function(runtime) {
var id, progress, propertyValue;
firstFrameTime = firstFrameTime || runtime;
runtime -= firstFrameTime;
progress = runtime / opt.duration;
if (progress < 1) {
this._transitionIds[path] = id = nextFrame(setter);
} else {
progress = 1;
delete this._transitionIds[path];
}
propertyValue = interpolatingFunction(opt.timingFunction(progress));
opt.transitionId = id;
this.prop(path, propertyValue, opt);
if (!id) this.trigger('transition:end', this, path);
}.bind(this);
const { _scheduledTransitionIds } = this;
let initialId;
var initiator = (callback) => {
if (_scheduledTransitionIds[path]) {
_scheduledTransitionIds[path] = without(_scheduledTransitionIds[path], initialId);
if (_scheduledTransitionIds[path].length === 0) {
delete _scheduledTransitionIds[path];
}
}
this.stopPendingTransitions(path, delim);
interpolatingFunction = opt.valueFunction(getByPath(this.attributes, path, delim), value);
this._transitionIds[path] = nextFrame(callback);
this.trigger('transition:start', this, path);
};
initialId = setTimeout(initiator, opt.delay, setter);
_scheduledTransitionIds[path] || (_scheduledTransitionIds[path] = []);
_scheduledTransitionIds[path].push(initialId);
return initialId;
},
getTransitions: function() {
return union(
Object.keys(this._transitionIds),
Object.keys(this._scheduledTransitionIds)
);
},
stopScheduledTransitions: function(path, delim = '/') {
const { _scheduledTransitionIds = {}} = this;
let transitions = Object.keys(_scheduledTransitionIds);
if (path) {
const pathArray = path.split(delim);
transitions = transitions.filter((key) => {
return isEqual(pathArray, key.split(delim).slice(0, pathArray.length));
});
}
transitions.forEach((key) => {
const transitionIds = _scheduledTransitionIds[key];
// stop the initiator
transitionIds.forEach(transitionId => clearTimeout(transitionId));
delete _scheduledTransitionIds[key];
// Note: we could trigger transition:cancel` event here
});
return this;
},
stopPendingTransitions(path, delim = '/') {
const { _transitionIds = {}} = this;
let transitions = Object.keys(_transitionIds);
if (path) {
const pathArray = path.split(delim);
transitions = transitions.filter((key) => {
return isEqual(pathArray, key.split(delim).slice(0, pathArray.length));
});
}
transitions.forEach((key) => {
const transitionId = _transitionIds[key];
// stop the setter
cancelFrame(transitionId);
delete _transitionIds[key];
this.trigger('transition:end', this, key);
});
},
stopTransitions: function(path, delim = '/') {
this.stopScheduledTransitions(path, delim);
this.stopPendingTransitions(path, delim);
return this;
},
// A shorcut making it easy to create constructs like the following:
// `var el = (new joint.shapes.standard.Rectangle()).addTo(graph)`.
addTo: function(graph, opt) {
graph.addCell(this, opt);
return this;
},
// A shortcut for an equivalent call: `paper.findViewByModel(cell)`
// making it easy to create constructs like the following:
// `cell.findView(paper).highlight()`
findView: function(paper) {
return paper.findViewByModel(this);
},
isElement: function() {
return false;
},
isLink: function() {
return false;
},
startBatch: function(name, opt) {
if (this.graph) { this.graph.startBatch(name, assign({}, opt, { cell: this })); }
return this;
},
stopBatch: function(name, opt) {
if (this.graph) { this.graph.stopBatch(name, assign({}, opt, { cell: this })); }
return this;
},
getChangeFlag: function(attributes) {
var flag = 0;
if (!attributes) return flag;
for (var key in attributes) {
if (!attributes.hasOwnProperty(key) || !this.hasChanged(key)) continue;
flag |= attributes[key];
}
return flag;
},
angle: function() {
// To be overridden.
return 0;
},
position: function() {
// To be overridden.
return new g.Point(0, 0);
},
z: function() {
return this.get('z') || 0;
},
getPointFromConnectedLink: function() {
// To be overridden
return new g.Point();
},
getBBox: function() {
// To be overridden
return new g.Rect(0, 0, 0, 0);
},
getPointRotatedAroundCenter(angle, x, y) {
const point = new g.Point(x, y);
if (angle) point.rotate(this.getBBox().center(), angle);
return point;
},
getAbsolutePointFromRelative(x, y) {
// Rotate the position to take the model angle into account
return this.getPointRotatedAroundCenter(
-this.angle(),
// Transform the relative position to absolute
this.position().offset(x, y)
);
},
getRelativePointFromAbsolute(x, y) {
return this
// Rotate the coordinates to mitigate the element's rotation.
.getPointRotatedAroundCenter(this.angle(), x, y)
// Transform the absolute position into relative
.difference(this.position());
},
layer: function(layerName, opt) {
// if strictly null unset the layer
if (layerName === null) {
return this.unset('layer', opt);
}
// if undefined return the current layer name
if (layerName === undefined) {
let layer = this.get('layer') || null;
// If the cell is part of a graph, use the graph's default layer.
if (layer == null && this.graph) {
layer = this.graph.getDefaultLayer().name;
}
return layer;
}
// otherwise set the layer name
if (!isString(layerName)) {
throw new Error('Layer name must be a string.');
}
return this.set('layer', layerName, opt);
}
}, {
getAttributeDefinition: function(attrName) {
var defNS = this.attributes;
var globalDefNS = attributes;
return (defNS && defNS[attrName]) || globalDefNS[attrName];
},
define: function(type, defaults, protoProps, staticProps) {
protoProps = assign({
defaults: defaultsDeep({ type: type }, defaults, this.prototype.defaults)
}, protoProps);
var Cell = this.extend(protoProps, staticProps);
// es5 backward compatibility
/* eslint-disable no-undef */
if (typeof joint !== 'undefined' && has(joint, 'shapes')) {
setByPath(joint.shapes, type, Cell, '.');
}
/* eslint-enable no-undef */
return Cell;
}
});