zz-chart
Version:
Alauda Chart components by Alauda Frontend Team
104 lines • 3.2 kB
JavaScript
import { each } from 'lodash-es';
import { getAction } from './action/index.js';
// 执行 Action
function executeAction(actionObject, context) {
const action = actionObject.action;
const { methodName } = actionObject;
if (action?.[methodName]) {
action[methodName](context);
}
else {
throw new Error(`Action(${action.name}) doesn't have a method called ${methodName}`);
}
}
/**
* 交互的基类。
*/
export default class Interaction {
constructor(view, steps) {
this.callbackCaches = new Map();
this.getActionObject = (actionStr) => {
const [actionName, methodName] = actionStr.split(':');
const Action = getAction(actionName);
if (!Action) {
throw new Error(`There is no action named ${actionName}`);
}
return {
action: new Action(this.view),
methodName,
};
};
this.view = view;
this.steps = steps;
}
/**
* 初始化。
*/
init() {
this.initActionObject();
this.initEvents();
}
/**
* 绑定事件
*/
initEvents() {
// TODO: point 下 tooltip trigger 为 element
const point = this.view.shapeComponents.get('point');
each(this.steps, (value, stepName) => {
value.forEach(step => {
const callback = this.getActionCallback(stepName, step);
const isPlot = step.trigger.includes('plot');
this.view.on(point && isPlot
? step.trigger.replace('plot', 'element')
: step.trigger, callback);
});
});
}
// 初始化 action object
initActionObject() {
const steps = this.steps;
// 生成具体的 Action
each(steps, subSteps => {
each(subSteps, step => {
step.actionObject = this.getActionObject(step.action);
});
});
}
getActionCallback(stepName, step) {
const callbackCaches = this.callbackCaches;
if (step.action) {
const key = stepName;
if (!callbackCaches.get(key)) {
// 生成执行的方法,执行对应 action 的名称
const actionCallback = (context) => {
executeAction(step.actionObject, context);
step.callback?.(context); // 执行callback
};
callbackCaches.set(stepName, actionCallback);
}
return callbackCaches.get(stepName);
}
return null;
}
/**
* 销毁事件
*/
clearEvents() {
const point = this.view.shapeComponents.get('point');
each(this.steps, (value) => {
value.forEach(step => {
const isPlot = step.trigger.includes('plot');
this.view.off(point && isPlot
? step.trigger.replace('plot', 'element')
: step.trigger);
});
});
}
/**
* 销毁。
*/
destroy() {
this.clearEvents();
}
}
//# sourceMappingURL=interaction.js.map