@antv/g6
Version:
graph visualization frame work
120 lines (112 loc) • 2.95 kB
JavaScript
/**
* @fileOverview mode
* @author wuyue.lwy <wyueliu@gmail.com>
*/
var Util = require('../util');
var Handler = require('../handler');
var Mixin = {};
Mixin.CFG = {
/**
* mode list key - value, key - mode name, value - behaviors
* @type {object}
*/
modes: {},
/**
* current mode name
* @type {string}
*/
mode: 'default'
};
Mixin.INIT = '_initModes';
Mixin.AUGMENT = {
_initModes: function _initModes() {
this._eventStash = {};
var modes = this.get('modes');
var mode = this.get('mode');
if (Util.isEmpty(modes)) {
modes = Util.cloneDeep(this.constructor.Modes);
this.set('modes', modes);
}
this.changeMode(mode);
},
/**
* change mode
* @param {string} modeName - name of mode
*/
changeMode: function changeMode(modeName) {
var modes = this.get('modes');
if (Util.isEmpty(modes) || Util.isEmpty(modes[modeName])) {
return;
}
Handler.resetMode(modes[modeName], this);
this.set('mode', modeName);
},
/**
* add behavior to the current mode
* @param {Array | String} behaviour - add a behaviour or a list behaviours to the current mode
* @return {object} - graph object
*/
addBehaviour: function addBehaviour(behaviour) {
var modes = this.get('modes');
var mode = this.get('mode');
if (Util.isEmpty(modes[mode])) {
modes[mode] = [];
}
// remove repetition
var currentModes = modes[mode];
var list = [].concat(behaviour);
Util.each(list, function (tmp) {
if (currentModes.indexOf(tmp) === -1) {
currentModes.push(tmp);
}
});
Handler.resetMode(modes[mode], this);
return this;
},
/**
* remove behavior from the current mode
* @param {Array | String} behaviour - a behaviour or a list behaviours
* @return {object} this
*/
removeBehaviour: function removeBehaviour(behaviour) {
var modes = this.get('modes');
var mode = this.get('mode');
var currentModes = modes[mode];
if (Util.isEmpty(currentModes)) {
return;
}
var removes = [].concat(behaviour);
currentModes = currentModes.filter(function (item) {
return removes.indexOf(item) === -1;
});
Handler.resetMode(currentModes, this);
return this;
},
/**
* add a behaviour
* @param {string} type - behaviour type
* @param {function} fn - behaivour body
*/
behaviourOn: function behaviourOn(type, fn) {
var eventStash = this._eventStash;
if (!eventStash[type]) {
eventStash[type] = [];
}
eventStash[type].push(fn);
this.on(type, fn);
},
/**
* remove all behaviours added by user
*/
_off: function _off() {
var _this = this;
var eventStash = this._eventStash;
Util.each(eventStash, function (fns, type) {
Util.each(fns, function (fn) {
_this.off(type, fn);
});
});
this._eventStash = {};
}
};
module.exports = Mixin;