/**
* @fileOverview tooltip plugin
* @author huangtonger@aliyun.com
*/
const G6 = require('@antv/g6');
const Util = G6.Util;
class Plugin {
constructor(options) {
this.options = {
/**
* horizontal offset
* @type {number}
*/
dx: 10,
/**
* vertical offset
* @type {number}
*/
dy: 10,
/**
* get tooltip dom
* @type {function}
* @return {string|null} tooltip dom
*/
getTooltip({ item }) {
if (item) {
const model = item.getModel();
const tooltip = model.tooltip;
if (tooltip) {
let lis = '';
tooltip.forEach(subTooltip => {
lis += '
' + subTooltip[0] + ': ' + subTooltip[1] + '';
});
return `
`;
}
}
return null;
},
...options
};
}
init() {
const graph = this.graph;
graph.on('mouseenter', ev => {
ev.shape && this.onMouseEnter(ev);
});
graph.on('mousemove', ev => {
this.onMouseMove(ev);
});
graph.on('mouseleave', ev => {
this.onMouseLeave(ev);
});
}
onMouseEnter(ev) {
const graph = this.graph;
const graphContainer = graph.getGraphContainer();
const options = this.options;
const tooltipHtml = options.getTooltip(ev);
let tooltip = this.tooltip;
tooltip && this.tooltip.destroy();
if (tooltipHtml) {
tooltip = Util.createDOM(tooltipHtml);
tooltip.css({
position: 'absolute'
});
graphContainer.appendChild(tooltip);
} else {
tooltip = null;
}
this.tooltip = tooltip;
}
onMouseMove({ domX, domY }) {
const tooltip = this.tooltip;
if (tooltip) {
const graph = this.graph;
const w0 = Util.getOuterWidth(tooltip);
const h0 = Util.getOuterHeight(tooltip);
const w1 = graph.getWidth();
const h1 = graph.getHeight();
tooltip.css({
top: this._getTop(h0, h1, domY),
left: this._getLeft(w0, w1, domX)
});
}
}
onMouseLeave() {
if (this.tooltip) {
this.tooltip.destroy();
this.tooltip = null;
}
}
_getTop(h0, h1, domY) {
const { dy } = this.options;
if (h0 * 2 >= h1) {
return '0px';
}
if (domY < h0 + dy) {
return domY + dy + 'px';
}
return domY - h0 - dy + 'px';
}
_getLeft(w0, w1, domX) {
const { dx } = this.options;
if (w0 * 2 >= w1) {
return '0px';
}
if (w1 - domX - dx < w0) {
return domX - w0 - dx + 'px';
}
return domX + dx + 'px';
}
}
G6.Plugins['tool.tooltip'] = Plugin;
module.exports = Plugin;